I did exactly what you're looking for in a very simple way. It is perfectly smooth in Google Chrome and Opera, and almost perfect in Firefox and Safari. Not tested in IE.
function newTab(url)
{
var tab=window.open("");
tab.document.write("<!DOCTYPE html><html>"+document.getElementsByTagName("html")[0].innerHTML+"</html>");
tab.document.close();
window.location.href=url;
}
Fiddle : http://jsfiddle.net/tFCnA/show/
Explanations:
Let's say there is windows A1 and B1 and websites A2 and B2.
Instead of opening B2 in B1 and then return to A1, I open B2 in A1 and re-open A2 in B1.
(Another thing that makes it work is that I don't make the user re-download A2, see line 4)
The only thing you may doesn't like is that the new tab opens before the main page.
I use 1 plug in for Firefox that gives me the IP and country for the hosting website and it's Web Server name called Domain Details, and for javascript framework I use WTFramework
I still need to wonder what script it was written on, but it is a start :)
Hope it helps.
P.S. the output will be something like this:
alt text http://img88.imageshack.us/img88/2505/200812282328ha0.png
wxHexEditor is the only GUI disk editor for linux. to google "wxhexeditor site:archive.getdeb.net" and download the .deb file to install
You can do it like this:
string tmp = "Hello 'World'";
tmp.replace("'", "");
But that will just replace single quotes. To replace double quotes, you must first escape them, like so:
string tmp = "Hello, \"World\"";
tmp.replace("\"", "");
You can replace it with a space, or just leave it empty (I believe you wanted it to be left blank, but your question title implies otherwise.
For Spring 4, using Spring Boot we can have the following example without using the anti-pattern of getting the Bean from the ApplicationContext directly:
package com.yourproject;
@SpringBootApplication
public class TestBed implements CommandLineRunner {
private MyService myService;
@Autowired
public TestBed(MyService myService){
this.myService = myService;
}
public static void main(String... args) {
SpringApplication.run(TestBed.class, args);
}
@Override
public void run(String... strings) throws Exception {
System.out.println("myService: " + MyService );
}
}
@Service
public class MyService{
public String getSomething() {
return "something";
}
}
Make sure that all your injected services are under com.yourproject
or its subpackages.
I found that if you just want to change the height of the element the image takes up, this will be the code that will help
.carousel-item {
height: 600px !important;
}
however, this won't make the size of the image dynamic, it will simply crop the image to its size.
Here is what I use.
Write-Host -NoNewLine 'Press any key to continue...';
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');
I was also facing same problem but i renamed contact-form-7 plugin from /wp-content/plugins directory to contact-form-7-rename and problem solved.
So this is due to unsupportable plugins or theme.
In PostgreSQL you can use :
SELECT extract(epoch from now());
on MySQL :
SELECT unix_timestamp(now());
The reason this problem occurs is because the fastcgi configurations in nginx do not function as required and in place or processing, they respond as html data. There are two possible ways in which you can configure your nginx to avoid this problem.
Method 1:
location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
# With php5-fpm:
fastcgi_pass unix:/run/php5-fpm.sock;
fastcgi_index index.php;
include fastcgi.conf;
}
Method 2:
location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
include snippets/fastcgi-php.conf;
# With php5-fpm:
fastcgi_pass unix:/var/run/php5-fpm.sock;
include fastcgi_params;
}
Both the methods would work properly, you can go ahead and take any one of them. They almost perform the same operations with a very few difference.
The script tag to the api has changed recently. Use something like this to query the Geocoding API and get the JSON object back
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/geocode/json?address=THE_ADDRESS_YOU_WANT_TO_GEOCODE&key=YOUR_API_KEY"></script>
The address could be something like
1600+Amphitheatre+Parkway,+Mountain+View,+CA (URI Encoded; you should Google it. Very useful)
or simply
1600 Amphitheatre Parkway, Mountain View, CA
By entering this address https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=YOUR_API_KEY
inside the browser, along with my API Key, I get back a JSON object which contains the Latitude & Longitude for the city of Moutain view, CA.
{"results" : [
{
"address_components" : [
{
"long_name" : "1600",
"short_name" : "1600",
"types" : [ "street_number" ]
},
{
"long_name" : "Amphitheatre Parkway",
"short_name" : "Amphitheatre Pkwy",
"types" : [ "route" ]
},
{
"long_name" : "Mountain View",
"short_name" : "Mountain View",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Santa Clara County",
"short_name" : "Santa Clara County",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "California",
"short_name" : "CA",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United States",
"short_name" : "US",
"types" : [ "country", "political" ]
},
{
"long_name" : "94043",
"short_name" : "94043",
"types" : [ "postal_code" ]
}
],
"formatted_address" : "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
"geometry" : {
"location" : {
"lat" : 37.4222556,
"lng" : -122.0838589
},
"location_type" : "ROOFTOP",
"viewport" : {
"northeast" : {
"lat" : 37.4236045802915,
"lng" : -122.0825099197085
},
"southwest" : {
"lat" : 37.4209066197085,
"lng" : -122.0852078802915
}
}
},
"place_id" : "ChIJ2eUgeAK6j4ARbn5u_wAGqWA",
"types" : [ "street_address" ]
}],"status" : "OK"}
Web Frameworks such like AngularJS allow us to perform these queries with ease.
#define NUM_TYPES 4
If you use Express 4.x, you can use the req.get(headerName)
method as described in Express 4.x API Reference
A good plugin that I have used before is DataTables.
It's really a matter of opinion. In your example, System.out.println(5)
would be slightly more efficient, as you only refer to the number once and never change it. As was said in a comment, int
is a primitive type and not a reference - thus it doesn't take up much space. However, you might want to set actual reference variables to null only if they are used in a very complicated method. All local reference variables are garbage collected when the method they are declared in returns.
Upfront, I am a bit lacking in my GIT skills.
That is going to clone a bare repository on your machine, which only contains the folders within .git
which is a hidden directory. execute ls -al
and you should see .git
or cd .git
inside your repository.
Can you add a description of your intent so that someone with more GIT skills can help? What is it you really want to do not how you plan on doing it?
To forcefully kill a process like that, use the following command
lsof -n -i4TCP:3000
Where 3000 is the port number the process is running at
this returns the process id(PID) and run
kill -9 "PID"
Replace PID with the number you get after running the first command
I use this, when i know the index of the list.
$("#yourlist :nth(1)").prop("selected","selected").change();
This allows the list to change, and fire the change event. The ":nth(n)" is counting from index 0
As I understand it, you have a function that receives 3 arguments, but if it does not it will run on default behavior. Since you have not explained what should happen when 1 or 2 arguments are supplied I will assume it should simply do the default behavior. In which case, I think you will find the following answer very advantageous:
def method(a=None, b=None, c=None):
if all([a, b, c]):
# received 3 arguments
else:
# default behavior
However, if you want 1 or 2 arguments to be handled differently:
def method(a=None, b=None, c=None):
args = [a, b, c]
if all(args):
# received 3 arguments
elif not any(args):
# default behavior
else:
# some args (raise exception?)
note: This assumes that "False
" values will not be passed into this method.
Summary
Type BST (*) Heap
Insert average log(n) 1
Insert worst log(n) log(n) or n (***)
Find any worst log(n) n
Find max worst 1 (**) 1
Create worst n log(n) n
Delete worst log(n) log(n)
All average times on this table are the same as their worst times except for Insert.
*
: everywhere in this answer, BST == Balanced BST, since unbalanced sucks asymptotically**
: using a trivial modification explained in this answer***
: log(n)
for pointer tree heap, n
for dynamic array heapAdvantages of binary heap over a BST
average time insertion into a binary heap is O(1)
, for BST is O(log(n))
. This is the killer feature of heaps.
There are also other heaps which reach O(1)
amortized (stronger) like the Fibonacci Heap, and even worst case, like the Brodal queue, although they may not be practical because of non-asymptotic performance: Are Fibonacci heaps or Brodal queues used in practice anywhere?
binary heaps can be efficiently implemented on top of either dynamic arrays or pointer-based trees, BST only pointer-based trees. So for the heap we can choose the more space efficient array implementation, if we can afford occasional resize latencies.
binary heap creation is O(n)
worst case, O(n log(n))
for BST.
Advantage of BST over binary heap
search for arbitrary elements is O(log(n))
. This is the killer feature of BSTs.
For heap, it is O(n)
in general, except for the largest element which is O(1)
.
"False" advantage of heap over BST
heap is O(1)
to find max, BST O(log(n))
.
This is a common misconception, because it is trivial to modify a BST to keep track of the largest element, and update it whenever that element could be changed: on insertion of a larger one swap, on removal find the second largest. Can we use binary search tree to simulate heap operation? (mentioned by Yeo).
Actually, this is a limitation of heaps compared to BSTs: the only efficient search is that for the largest element.
Average binary heap insert is O(1)
Sources:
Intuitive argument:
In a binary heap, increasing the value at a given index is also O(1)
for the same reason. But if you want to do that, it is likely that you will want to keep an extra index up-to-date on heap operations How to implement O(logn) decrease-key operation for min-heap based Priority Queue? e.g. for Dijkstra. Possible at no extra time cost.
GCC C++ standard library insert benchmark on real hardware
I benchmarked the C++ std::set
(Red-black tree BST) and std::priority_queue
(dynamic array heap) insert to see if I was right about the insert times, and this is what I got:
So clearly:
heap insert time is basically constant.
We can clearly see dynamic array resize points. Since we are averaging every 10k inserts to be able to see anything at all above system noise, those peaks are in fact about 10k times larger than shown!
The zoomed graph excludes essentially only the array resize points, and shows that almost all inserts fall under 25 nanoseconds.
BST is logarithmic. All inserts are much slower than the average heap insert.
BST vs hashmap detailed analysis at: What data structure is inside std::map in C++?
GCC C++ standard library insert benchmark on gem5
gem5 is a full system simulator, and therefore provides an infinitely accurate clock with with m5 dumpstats
. So I tried to use it to estimate timings for individual inserts.
Interpretation:
heap is still constant, but now we see in more detail that there are a few lines, and each higher line is more sparse.
This must correspond to memory access latencies are done for higher and higher inserts.
TODO I can't really interpret the BST fully one as it does not look so logarithmic and somewhat more constant.
With this greater detail however we can see can also see a few distinct lines, but I'm not sure what they represent: I would expect the bottom line to be thinner, since we insert top bottom?
Benchmarked with this Buildroot setup on an aarch64 HPI CPU.
BST cannot be efficiently implemented on an array
Heap operations only need to bubble up or down a single tree branch, so O(log(n))
worst case swaps, O(1)
average.
Keeping a BST balanced requires tree rotations, which can change the top element for another one, and would require moving the entire array around (O(n)
).
Heaps can be efficiently implemented on an array
Parent and children indexes can be computed from the current index as shown here.
There are no balancing operations like BST.
Delete min is the most worrying operation as it has to be top down. But it can always be done by "percolating down" a single branch of the heap as explained here. This leads to an O(log(n)) worst case, since the heap is always well balanced.
If you are inserting a single node for every one you remove, then you lose the advantage of the asymptotic O(1) average insert that heaps provide as the delete would dominate, and you might as well use a BST. Dijkstra however updates nodes several times for each removal, so we are fine.
Dynamic array heaps vs pointer tree heaps
Heaps can be efficiently implemented on top of pointer heaps: Is it possible to make efficient pointer-based binary heap implementations?
The dynamic array implementation is more space efficient. Suppose that each heap element contains just a pointer to a struct
:
the tree implementation must store three pointers for each element: parent, left child and right child. So the memory usage is always 4n
(3 tree pointers + 1 struct
pointer).
Tree BSTs would also need further balancing information, e.g. black-red-ness.
the dynamic array implementation can be of size 2n
just after a doubling. So on average it is going to be 1.5n
.
On the other hand, the tree heap has better worst case insert, because copying the backing dynamic array to double its size takes O(n)
worst case, while the tree heap just does new small allocations for each node.
Still, the backing array doubling is O(1)
amortized, so it comes down to a maximum latency consideration. Mentioned here.
Philosophy
BSTs maintain a global property between a parent and all descendants (left smaller, right bigger).
The top node of a BST is the middle element, which requires global knowledge to maintain (knowing how many smaller and larger elements are there).
This global property is more expensive to maintain (log n insert), but gives more powerful searches (log n search).
Heaps maintain a local property between parent and direct children (parent > children).
The top node of a heap is the big element, which only requires local knowledge to maintain (knowing your parent).
Comparing BST vs Heap vs Hashmap:
BST: can either be either a reasonable:
heap: is just a sorting machine. Cannot be an efficient unordered set, because you can only check for the smallest/largest element fast.
hash map: can only be an unordered set, not an efficient sorting machine, because the hashing mixes up any ordering.
Doubly-linked list
A doubly linked list can be seen as subset of the heap where first item has greatest priority, so let's compare them here as well:
O(1)
worst case since we have pointers to the items, and the update is really simpleO(1)
average, thus worse than linked list. Tradeoff for having more general insertion position.O(n)
for bothAn use case for this is when the key of the heap is the current timestamp: in that case, new entries will always go to the beginning of the list. So we can even forget the exact timestamp altogether, and just keep the position in the list as the priority.
This can be used to implement an LRU cache. Just like for heap applications like Dijkstra, you will want to keep an additional hashmap from the key to the corresponding node of the list, to find which node to update quickly.
Comparison of different Balanced BST
Although the asymptotic insert and find times for all data structures that are commonly classified as "Balanced BSTs" that I've seen so far is the same, different BBSTs do have different trade-offs. I haven't fully studied this yet, but it would be good to summarize these trade-offs here:
See also
Similar question on CS: https://cs.stackexchange.com/questions/27860/whats-the-difference-between-a-binary-search-tree-and-a-binary-heap
Be very careful with the Excel MOD(a,b) function and the VBA a Mod b operator. Excel returns a floating point result and VBA an integer.
In Excel =Mod(90.123,90) returns 0.123000000000005 instead of 0.123 In VBA 90.123 Mod 90 returns 0
They are certainly not equivalent!
Equivalent are: In Excel: =Round(Mod(90.123,90),3) returning 0.123 and In VBA: ((90.123 * 1000) Mod 90000)/1000 returning also 0.123
Yo can try this:
SELECT CURDATE();
If you check the following:
SELECT NOW(); SELECT DATE(NOW()); SELECT DATE_FORMAT(NOW(),'%Y-%m-%d');
You can see that it takes a long time.
Unfortunately that approach is not portable C++ (so far).
All standard names are in namespace std
and moreover you cannot know which names are NOT defined by including and header (in other words it's perfectly legal for an implementation to declare the name std::string
directly or indirectly when using #include <vector>
).
Despite this however you are required by the language to know and tell the compiler which standard header includes which part of the standard library. This is a source of portability bugs because if you forget for example #include <map>
but use std::map
it's possible that the program compiles anyway silently and without warnings on a specific version of a specific compiler, and you may get errors only later when porting to another compiler or version.
In my opinion there are no valid technical excuses because this is necessary for the general user: the compiler binary could have all standard namespace built in and this could actually increase the performance even more than precompiled headers (e.g. using perfect hashing for lookups, removing standard headers parsing or loading/demarshalling and so on).
The use of standard headers simplifies the life of who builds compilers or standard libraries and that's all. It's not something to help users.
However this is the way the language is defined and you need to know which header defines which names so plan for some extra neurons to be burnt in pointless configurations to remember that (or try to find and IDE that automatically adds the standard headers you use and removes the ones you don't... a reasonable alternative).
An SMS Push is a message to tell the terminal to initiate the session. This happens because you can't initiate an IP session simply because you don't know the IP Adress of the mobile terminal. Mostly used to send a few lines of data to end recipient, to the effect of sending information, or reminding of events.
WAP Push is an SMS within the header of which is included a link to a WAP address. On receiving a WAP Push, the compatible mobile handset automatically gives the user the option to access the WAP content on his handset. The WAP Push directs the end-user to a WAP address where content is stored ready for viewing or downloading onto the handset. This wap address may be a page or a WAP site.
The user may “take action” by using a developer-defined soft-key to immediately activate an application to accomplish a specific task, such as downloading a picture, making a purchase, or responding to a marketing offer.
If you look at your XAMPP Control Panel, it's clearly stated that the port to the MySQL server is 3306
- you provided 3360
. The 3306
is default, and thus doesn't need to be specified. Even so, the 5th parameter of mysqli_connect()
is the port, which is where it should be specified.
You could just remove the port specification altogether, as you're using the default port, making it
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db = 'test_db13';
References
There is a pseudocolumn called %%physloc%% that shows the physical address of the row.
You get the error because if
can only evaluate a logical
vector of length 1.
Maybe you miss the difference between &
(|
) and &&
(||
). The shorter version works element-wise and the longer version uses only the first element of each vector, e.g.:
c(TRUE, TRUE) & c(TRUE, FALSE)
# [1] TRUE FALSE
# c(TRUE, TRUE) && c(TRUE, FALSE)
[1] TRUE
You don't need the if
statement at all:
mut1 <- trip$Ref.y=='G' & trip$Variant.y=='T'|trip$Ref.y=='C' & trip$Variant.y=='A'
trip[mut1, "mutType"] <- "G:C to T:A"
My curl was not ignoring the proxy on Ubuntu 12.04 until I set the "no_proxy" (lowercase) environment variable. The --noproxy option was not available.
You can use title
attribute.
<img src="smiley.gif" title="Smiley face"/>
You can change the source of image as you want.
And as @Gray commented:
You can also use the title
on other things like <a ...
anchors, <p>
, <div>
, <input>
, etc.
See: this
MSDN has provided easy way to debug the stored procedure. Please check this link-
How to: Debug Stored Procedures
win32com.client
is a part of pywin32
So, download pywin32 from here
These are positional arguments of the script.
Executing
./script.sh Hello World
Will make
$0 = ./script.sh
$1 = Hello
$2 = World
Note
If you execute ./script.sh
, $0
will give output ./script.sh
but if you execute it with bash script.sh
it will give output script.sh
.
While the accepted answer is correct, I'll add a more elegant version (in my opinion):
boolean idExists = tabPane.getTabs().stream()
.map(Tab::getId)
.anyMatch(idToCheck::equals);
Don't neglect using Stream#map() which allows to flatten the data structure before applying the Predicate
.
I think it is called next.
Just add:
import os
in the beginning, before:
from settings import PROJECT_ROOT
This will import the python's module os, which apparently is used later in the code of your module without being imported.
Yes, querySelectorAll
does take a group of selectors:
form, p, legend
Change the rule on your <a>
element from:
.navigation ul a {
color: #000;
display: block;
padding: 0 65px 0 0;
text-decoration: none;
}?
to
.navigation ul a {
color: #000;
display: block;
padding: 0 65px 0 0;
text-decoration: none;
width:100%;
text-align:center;
}?
Just add two new rules (width:100%;
and text-align:center;
). You need to make the anchor expand to take up the full width of the list item and then text-align center it.
If /foo/bar
is on NFS (or possibly some FUSE filesystem), that might be the problem.
Either way, adding -O
/ --omit-dir-times
to your command line will avoid it trying to set modification times on directories.
---- Remove Constraint ----
EXEC sp_MSForEachTable "ALTER TABLE ? NOCHECK CONSTRAINT all"
---- Delete Data ----
EXEC sp_MSForEachTable "DELETE FROM ?"
---- Add Constraint ----
EXEC sp_MSForEachTable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"
---- Reset Identity value ----
EXEC sp_MSForEachTable "DBCC CHECKIDENT ( '?', RESEED, 0)"
One of the possible solutions is:
const names = {
afshin: 'afshin',
saeed: 'saeed',
larry: 'larry'
};
switch (varName) {
case names[varName]: {
alert('Hey');
break;
}
default: {
alert('Default case');
break;
}
}
The isinstance
built-in is the preferred way if you really must, but even better is to remember Python's motto: "it's easier to ask forgiveness than permission"!-) (It was actually Grace Murray Hopper's favorite motto;-). I.e.:
def my_print(text, begin, end):
"Print 'text' in UPPER between 'begin' and 'end' in lower"
try:
print begin.lower() + text.upper() + end.lower()
except (AttributeError, TypeError):
raise AssertionError('Input variables should be strings')
This, BTW, lets the function work just fine on Unicode strings -- without any extra effort!-)
I assume you are meaning "internally" within your application.
you can create your own <a>
tag and insert a url in the href like this
<a href="<?php echo site_url('controller/function/uri') ?>">Link</a>
OR you can use the URL helper this way to generate an <a>
tag
anchor(uri segments, text, attributes)
So... to use it...
<?php echo anchor('controller/function/uri', 'Link', 'class="link-class"') ?>
and that will generate
<a href="http://domain.com/index.php/controller/function/uri" class="link-class">Link</a>
For the additional commented question
I would use my first example
so...
<a href="<?php echo site_url('controller/function') ?>"><img src="<?php echo base_url() ?>img/path/file.jpg" /></a>
for images (and other assets) I wouldn't put the file path within the php, I would just echo the base_url() and then add the path normally.
I had an issue where I was doing commit --amend
even after issuing a git add .
and it still wasn't working. Turns out I made some .vimrc
customizations and my editor wasn't working correctly. Fixing these errors so that vim
returns the correct code resolved the issue.
<script>
function reloadIt() {
if (window.location.href.substr(-2) !== "?r") {
window.location = window.location.href + "?r";
}
}
setTimeout('reloadIt()', 1000)();
</script>
this works perfectly
Here is the answer if you need resize textView
and tableViewCell
dynamically in staticTableView
SELECT DISTINCT a.StoreID
FROM tableName a
LEFT JOIN tableName b
ON a.StoreID = b.StoreID AND b.ClientID = 5
WHERE b.StoreID IS NULL
OUTPUT
+---------+
¦ STOREID ¦
¦---------¦
¦ 3 ¦
+---------+
Adding # coding=utf-8 line in first line of your .py file will fix the problem.
Please read more about the problem and its fix on below link, in this article problem and its solution is beautifully described : https://www.python.org/dev/peps/pep-0263/
If you don't want to use float, the easiest and cleanest way to do it is by using an auto width column:
<div class="row">
<div class="col">
<h3 class="one">Text</h3>
</div>
<div class="col-auto">
<button class="btn btn-secondary pull-right">Button</button>
</div>
</div>
I have tried all of the answers above but none of them work. After so many attempts I've finally found a reliable way to set WKWebview cookie.
First you have to create an instance of WKProcessPool and set it to the WKWebViewConfiguration that is to be used to initialize the WkWebview itself:
private lazy var mainWebView: WKWebView = {
let webConfiguration = WKWebViewConfiguration()
webConfiguration.processPool = WKProcessPool()
let webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.navigationDelegate = self
return webView
}()
Setting WKProcessPool is the most important step here. WKWebview makes use of process isolation - which means it runs on a different process than the process of your app. This can sometimes cause conflict and prevent your cookie from being synced properly with the WKWebview.
Now let's look at the definition of WKProcessPool
The process pool associated with a web view is specified by its web view configuration. Each web view is given its own Web Content process until an implementation-defined process limit is reached; after that, web views with the same process pool end up sharing Web Content processes.
Pay attention to the last sentence if you plan to use the same WKWebview for subsequence requests
web views with the same process pool end up sharing Web Content processes
what I means is that if you don't use the same instance of WKProcessPool each time you configure a WKWebView for the same domain (maybe you have a VC A that contains a WKWebView and you want to create different instances of VC A in different places), there can be conflict setting cookies. To solve the problem, after the first creation of the WKProcessPool for a WKWebView that loads domain B, I save it in a singleton and use that same WKProcessPool every time I have to create a WKWebView that loads the same domain B
private lazy var mainWebView: WKWebView = {
let webConfiguration = WKWebViewConfiguration()
if Enviroment.shared.processPool == nil {
Enviroment.shared.processPool = WKProcessPool()
}
webConfiguration.processPool = Enviroment.shared.processPool!
webConfiguration.processPool = WKProcessPool()
let webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.navigationDelegate = self
return webView
}()
After the initialization process, you can load an URLRequest inside the completion block of httpCookieStore.setCookie
. Here, you have to attach the cookie to the request header otherwise it won't work.
P/s: I stole the extension from the fantastic answer above by Dan Loewenherz
mainWebView.configuration.websiteDataStore.httpCookieStore.setCookie(your_cookie) {
self.mainWebView.load(your_request, with: [your_cookie])
}
extension WKWebView {
func load(_ request: URLRequest, with cookies: [HTTPCookie]) {
var request = request
let headers = HTTPCookie.requestHeaderFields(with: cookies)
for (name, value) in headers {
request.addValue(value, forHTTPHeaderField: name)
}
load(request)
}
}
There is another way...
header('Content-Type: text/plain; charset=utf-8');
This makes the whole page served as plain text... better is htmlspecialchars...
Hope this helps...
those icons are a way of Egit to show you status of the current file/folder in git. You might want to check this out:
The &
means that the function accepts the address (or reference) to a variable, instead of the value of the variable.
For example, note the difference between this:
void af(int& g)
{
g++;
cout<<g;
}
int main()
{
int g = 123;
cout << g;
af(g);
cout << g;
return 0;
}
And this (without the &
):
void af(int g)
{
g++;
cout<<g;
}
int main()
{
int g = 123;
cout << g;
af(g);
cout << g;
return 0;
}
Try to start path\to\cygwin\bin\bash.exe
Old Microsoft Sql Sever (< 2012)
RETURN dateadd(month, 12 * @year + @month - 22801, @day - 1)
I am surprised that none of the answers mentioned the insertAdjacentHTML()
method. Check it out here. The first parameter is where you want the string appended and takes ("beforebegin", "afterbegin", "beforeend", "afterend"). In the OP's situation you would use "beforeend". The second parameter is just the html string.
Basic usage:
var d1 = document.getElementById('one');
d1.insertAdjacentHTML('beforeend', '<div id="two">two</div>');
<textarea id="editor1" name="editor1">This is sample text</textarea>
<div id="trackingDiv" ></div>
<script type="text/javascript">
CKEDITOR.replace( 'editor1' );
</script>
Let try this..
Update :
To set data :
Create instance First::
var editor = CKEDITOR.instances['editor1'];
Then,
editor.setData('your data');
or
editor.insertHtml('your html data');
or
editor.insertText('your text data');
And Retrieve data from your editor::
editor.getData();
If change the particular para HTML data in CKEditor.
var html = $(editor.editable.$);
$('#id_of_para',html).html('your html data');
These are the possible ways that I know in CKEditor
A simple swap is far better for "moving something up" in an ArrayList:
if(i > 0) {
Item toMove = arrayList.get(i);
arrayList.set(i, arrayList.get(i-1));
arrayList.set(i-1, toMove);
}
Because an ArrayList uses an array, if you remove an item from an ArrayList, it has to "shift" all the elements after that item upward to fill in the gap in the array. If you insert an item, it has to shift all the elements after that item to make room to insert it. These shifts can get very expensive if your array is very big. Since you know that you want to end up with the same number of elements in the list, doing a swap like this allows you to "move" an element to another location in the list very efficiently.
As Chris Buckler and Michal Kreuzman point out, there is even a handy method in the Collections class to reduce these three lines of code to one:
Collections.swap(arrayList, i, i-1);
It is pretty simple, leave the images on the server and send the PHP + CSS to them...
$to = '[email protected]';
$subject = 'Website Change Reqest';
$headers = "From: " . strip_tags($_POST['req-email']) . "\r\n";
$headers .= "Reply-To: ". strip_tags($_POST['req-email']) . "\r\n";
$headers .= "CC: [email protected]\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8\r\n";
$message = '<p><strong>This is strong text</strong> while this is not.</p>';
mail($to, $subject, $message, $headers);
It is this line that tells the mailer and the recipient that the email contains (hopefully) well formed HTML that it will need to interpret:
$headers .= "Content-Type: text/html; charset=UTF-8\r\n";
Here is the link I got the info.. (link...)
You will need security though...
If you are using AFNetworking library to download image and that images are using in UITableview then You can use below code in cellForRowAtIndexPath
[self setImageWithURL:user.user_ProfilePicturePath toControl:cell.imgView];
-(void)setImageWithURL:(NSURL*)url toControl:(id)ctrl
{
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFImageRequestOperation *operation = [AFImageRequestOperation imageRequestOperationWithRequest:request imageProcessingBlock:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
if (image) {
if([ctrl isKindOfClass:[UIButton class]])
{
UIButton btn =(UIButton)ctrl;
[btn setBackgroundImage:image forState:UIControlStateNormal];
}
else
{
UIImageView imgView = (UIImageView)ctrl;
imgView.image = image;
}
}
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
NSLog(@"No Image");
}];
[operation start];}
To the top voted answer. I prefer passing by rvalue reference.
I understand what's the problem about passing by rvalue reference may cause. But let's divide this problem to two sides:
I must write code Base newBase(std::move(<lvalue>))
or Base newBase(<rvalue>)
.
Library author should guarantee it will actually move the unique_ptr to initialize member if it want own the ownership.
That's all.
If you pass by rvalue reference, it will only invoke one "move" instruction, but if pass by value, it's two.
Yep, if library author is not expert about this, he may not move unique_ptr to initialize member, but it's the problem of author, not you. Whatever it pass by value or rvalue reference, your code is same!
If you are writing a library, now you know you should guarantee it, so just do it, passing by rvalue reference is a better choice than value. Client who use you library will just write same code.
Now, for your question. How do I pass a unique_ptr argument to a constructor or a function?
You know what's the best choice.
http://scottmeyers.blogspot.com/2014/07/should-move-only-types-ever-be-passed.html
You have set #slider
as absolute
, which means that it "is positioned relative to the nearest positioned ancestor" (confusing, right?). Meanwhile, #content
div is placed relative, which means "relative to its normal position". So the position of the 2 divs is not related.
You can read about CSS positioning here
If you set both to relative
, the divs will be one after the other, as shown here:
#slider {
position:relative;
left:0;
height:400px;
border-style:solid;
border-width:5px;
}
#slider img {
width:100%;
}
#content {
position:relative;
}
#content #text {
position:relative;
width:950px;
height:215px;
color:red;
}
You cannot simply add a link using CSS. CSS is used for styling.
You can style your using CSS.
If you want to give a link dynamically to then I will advice you to use jQuery or Javascript.
You can accomplish that very easily using jQuery.
I have done a sample for you. You can refer that.
$('#link').attr('href','http://www.google.com');
This single line will do the trick.
this is very old question, but since I came here while searching worth putting my answer.
SELECT DATEPART(ISO_WEEK,'2020-11-13') AS ISO_8601_WeekNr
double *ptr = malloc(sizeof(double *) * TIME); /* ... */ for(tcount = 0; tcount <= TIME; tcount++) ^^
<=
to <
or alloc
SIZE + 1
elementsmalloc
is wrong, you'll want sizeof(double)
instead of
sizeof(double *)
ouah
comments, although not directly linked to your corruption problem, you're using *(ptr+tcount)
without initializing itptr[tcount]
instead of *(ptr + tcount)
malloc
+ free
since you already know SIZE
From SQL Server point of view:
Clustering will give you an active - passive configuration. Meaning in a 2 node cluster, one of them will be the active (serving) and the other one will be passive (waiting to take over when the active node fails). It's a high availability from hardware point of view.
You can have an active-active cluster, but it will require multiple instances of SQL Server running on each node. (i.e. Instance 1 on Node A failing over to Instance 2 on Node B, and instance 1 on Node B failing over to instance 2 on Node A).
Load balancing (at least from SQL Server point of view) does not exists (at least in the same sense of web server load balancing). You can't balance load that way. However, you can split your application to run on some database on server 1 and also run on some database on server 2, etc. This is the primary mean of "load balancing" in SQL world.
If you work in MS Visual Studio just do following
Correct WSDL file like this YourSchemeFile.xsd
Use visual Studio using this great example How to generate service reference with only physical wsdl file
Notice that you have to put the path to your WSDL file manually. There is no way to use Open File dialog box out there.
To add on to Andrea's solution, if you are passing an array of JSONs for instance
[
{"name":"value"},
{"name":"value2"}
]
Then you will need to set up the Spring Boot Controller like so:
@RequestMapping(
value = "/process",
method = RequestMethod.POST)
public void process(@RequestBody Map<String, Object>[] payload)
throws Exception {
System.out.println(payload);
}
Autocommit is SQL Server's default transaction management mode. (SQL 2000 onwards)
May be the private key itself is not present in the file.I was also faced the same issue but the problem is that there is no private key present in the file.
One option that'll work with any version of PHP is to do what's already been suggested, which is something like this:
$eventTime = '2010-04-28 17:25:43';
$age = time() - strtotime($eventTime);
That will give you the age in seconds. From there, you can display it however you wish.
One problem with this approach, however, is that it won't take into account time shifts causes by DST. If that's not a concern, then go for it. Otherwise, you'll probably want to use the diff() method in the DateTime class. Unfortunately, this is only an option if you're on at least PHP 5.3.
The magic number comes from UNIX-type systems where the first few bytes of a file held a marker indicating the file type.
Python puts a similar marker into its pyc
files when it creates them.
Then the python interpreter makes sure this number is correct when loading it.
Anything that damages this magic number will cause your problem. This includes editing the pyc
file or trying to run a pyc
from a different version of python (usually later) than your interpreter.
If they are your pyc
files, just delete them and let the interpreter re-compile the py
files. On UNIX type systems, that could be something as simple as:
rm *.pyc
or:
find . -name '*.pyc' -delete
If they are not yours, you'll have to either get the py
files for re-compilation, or an interpreter that can run the pyc
files with that particular magic value.
One thing that might be causing the intermittent nature. The pyc
that's causing the problem may only be imported under certain conditions. It's highly unlikely it would import sometimes. You should check the actual full stack trace when the import fails?
As an aside, the first word of all my 2.5.1(r251:54863)
pyc
files is 62131
, 2.6.1(r261:67517)
is 62161
. The list of all magic numbers can be found in Python/import.c
, reproduced here for completeness (current as at the time the answer was posted, it may have changed since then):
1.5: 20121
1.5.1: 20121
1.5.2: 20121
1.6: 50428
2.0: 50823
2.0.1: 50823
2.1: 60202
2.1.1: 60202
2.1.2: 60202
2.2: 60717
2.3a0: 62011
2.3a0: 62021
2.3a0: 62011
2.4a0: 62041
2.4a3: 62051
2.4b1: 62061
2.5a0: 62071
2.5a0: 62081
2.5a0: 62091
2.5a0: 62092
2.5b3: 62101
2.5b3: 62111
2.5c1: 62121
2.5c2: 62131
2.6a0: 62151
2.6a1: 62161
2.7a0: 62171
Put your div inside another div, apply the border to the outer div with n amount of padding/margin where n is the space you want between them.
To replace anything that starts with "text" until the last character:
text.+(.*)$
Example
text hsjh sdjh sd jhsjhsdjhsdj hsd ^ last character
text.+(\ 123)
Example
text fuhfh283nfnd03no3 d90d3nd 3d 123 udauhdah au dauh ej2e ^ ^ From here To here
I'm using apache-tomcat-7.0.70 with jdk1.7.0_45 and none of the solutions here and elsewhere on stackoverflow worked for me. Just sharing this solution as it hopefully might help someone as this is very high on Google's search
What worked is doing BOTH of these steps:
Starting my tomcat with "export JAVA_OPTS="$JAVA_OPTS -Dhttps.protocols=TLSv1.2" by adding it to tomcat/bin/setenv.sh (Syntax slightly different on Windows)
Manually building/forcing HttpClients or anything else you need with the TLS1.2 protocol:
Context ctx = SSLContexts.custom().useProtocol("TLSv1.2").build();
HttpClient httpClient = HttpClientBuilder.create().setSslcontext(ctx).build();
HttpPost httppost = new HttpPost(scsTokenVerificationUrl);
List<NameValuePair> paramsAccessToken = new ArrayList<NameValuePair>(2);
paramsAccessToken.add(new BasicNameValuePair("token", token));
paramsAccessToken.add(new BasicNameValuePair("client_id", scsClientId));
paramsAccessToken.add(new BasicNameValuePair("secret", scsClientSecret));
httppost.setEntity(new UrlEncodedFormEntity(paramsAccessToken, "utf-8"));
//Execute and get the response.
HttpResponse httpResponseAccessToken = httpClientAccessToken.execute(httppost);
String responseJsonAccessToken = EntityUtils.toString(httpResponseAccessToken.getEntity());
The supplied link has a very simply example of the n + 1 problem. If you apply it to Hibernate it's basically talking about the same thing. When you query for an object, the entity is loaded but any associations (unless configured otherwise) will be lazy loaded. Hence one query for the root objects and another query to load the associations for each of these. 100 objects returned means one initial query and then 100 additional queries to get the association for each, n + 1.
If you want to use the Jupyter Notebook API (and not the IPython one anymore), I find the ipywidgets Jupyter's sub-project. You have an Image
widget. Docstring specifies that you have a value
parameter which is a bytes. So you can do:
import requests
from ipywidgets import Image
Image(value=requests.get('https://octodex.github.com/images/yaktocat.png').content)
I agree, it's simpler to use the Markdown style. But it shows you the Image display Notebook API. You can also resize the image with the width
and height
parameters.
I found one good thing about using bind is that you get to know the trigger event: something like: "You clicked with event = [ButtonPress event state=Mod1 num=1 x=43 y=20]" due to the code below:
self.submit.bind('<Button-1>', self.parse)
def parse(self, trigger_event):
print("You clicked with event = {}".format(trigger_event))
Comparing the following two ways of coding a button click:
btn = Button(root, text="Click me to submit", command=(lambda: reply(ent.get())))
btn = Button(root, text="Click me to submit")
btn.bind('<Button-1>', (lambda event: reply(ent.get(), e=event)))
def reply(name, e = None):
messagebox.showinfo(title="Reply", message = "Hello {0}!\nevent = {1}".format(name, e))
The first one is using the command function which doesn't take an argument, so no event pass-in is possible. The second one is a bind function which can take an event pass-in and print something like "Hello Charles! event = [ButtonPress event state=Mod1 num=1 x=68 y=12]"
We can left click, middle click or right click a mouse which corresponds to the event number of 1, 2 and 3, respectively. Code:
btn = Button(root, text="Click me to submit")
buttonClicks = ["<Button-1>", "<Button-2>", "<Button-3>"]
for bc in buttonClicks:
btn.bind(bc, lambda e : print("Button clicked with event = {}".format(e.num)))
Output:
Button clicked with event = 1
Button clicked with event = 2
Button clicked with event = 3
<style>
a {
color: ;
}
</style>
This code changes the color from the default to what is specified in the style. Using a:hover, you can change the color of the text from the default on hover.
To check if file is empty or has only white spaces, you can use grep:
if [[ -z $(grep '[^[:space:]]' $filename) ]] ; then
echo "Empty file"
...
fi
***
Just close and reopen
*** your project in eclipse. Sometime there are linkage problems. This solved my problem
class EnumHelpers {
static getNamesAndValues<T extends number>(e: any) {
return EnumHelpers.getNames(e).map(n => ({ name: n, value: e[n] as T }));
}
static getNames(e: any) {
return EnumHelpers.getObjValues(e).filter(v => typeof v === 'string') as string[];
}
static getValues<T extends number>(e: any) {
return EnumHelpers.getObjValues(e).filter(v => typeof v === 'number') as T[];
}
static getSelectList<T extends number, U>(e: any, stringConverter: (arg: U) => string) {
const selectList = new Map<T, string>();
this.getValues(e).forEach(val => selectList.set(val as T, stringConverter(val as unknown as U)));
return selectList;
}
static getSelectListAsArray<T extends number, U>(e: any, stringConverter: (arg: U) => string) {
return Array.from(this.getSelectList(e, stringConverter), value => ({ value: value[0] as T, presentation: value[1] }));
}
private static getObjValues(e: any): (number | string)[] {
return Object.keys(e).map(k => e[k]);
}
}
Just wondering why you are using 2 directives?
It seems like, in this case it would be more straightforward to have a controller as the parent - handle adding the data from your service to its $scope, and pass the model you need from there into your warrantyDirective.
Or for that matter, you could use 0 directives to achieve the same result. (ie. move all functionality out of the separate directives and into a single controller).
It doesn't look like you're doing any explicit DOM transformation here, so in this case, perhaps using 2 directives is overcomplicating things.
Alternatively, have a look at the Angular documentation for directives: http://docs.angularjs.org/guide/directive The very last example at the bottom of the page explains how to wire up dependent directives.
How about passing the controller function with bidirectional binding? Then you can use it in the directive exactly the same way as in a regular template (I stripped irrelevant parts for simplicity):
<div ng-controller="testCtrl">
<!-- pass the function with no arguments -->
<test color1="color1" update-fn="updateFn"></test>
</div>
<script>
angular.module('dr', [])
.controller("testCtrl", function($scope) {
$scope.updateFn = function(msg) {
alert(msg);
}
})
.directive('test', function() {
return {
scope: {
updateFn: '=' // '=' bidirectional binding
},
template: "<button ng-click='updateFn(1337)'>Click</button>"
}
});
</script>
I landed at this question, because I tried the method above befire, but somehow it didn't work. Now it works perfectly.
My general pattern is that if it fits on one line, I'll do:
if(true) do_something();
If there's an else clause, or if the code I want to execute on true
is of significant length, braces all the way:
if(true) {
do_something_and_pass_arguments_to_it(argument1, argument2, argument3);
}
if(false) {
do_something();
} else {
do_something_else();
}
Ultimately, it comes down to a subjective issue of style and readability. The general programming world, however, pretty much splits into two parties (for languages that use braces): either use them all the time without exception, or use them all the time with exception. I'm part of the latter group.
If you're in a RHEL environment the package name containing tools.jar would end with "openjdk-devel".
client = new OkHttpClient();
Request request = new Request.Builder().header("authorization", token).url(url).build();
MyWebSocketListener wsListener = new MyWebSocketListener(LudoRoomActivity.this);
client.newWebSocket(request, wsListener);
client.dispatcher().executorService().shutdown();
GROUP BY is used to group rows in a select, usually when aggregating rows (e.g. calculating totals, averages, etc. for a set of rows with the same values for some fields).
ORDER BY is used to order the rows resulted from a select statement.
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>
To spool from a BEGIN
END
block is pretty simple. For example if you need to spool result from two tables into a file, then just use the for loop
. Sample code is given below.
BEGIN
FOR x IN
(
SELECT COLUMN1,COLUMN2 FROM TABLE1
UNION ALL
SELECT COLUMN1,COLUMN2 FROM TABLEB
)
LOOP
dbms_output.put_line(x.COLUMN1 || '|' || x.COLUMN2);
END LOOP;
END;
/
Here is the complete code that I've tested and absolutely does NOT give me a "address already in use" error. You can save this in a file and run the file from within the base directory of the HTML files you want to serve. Additionally, you could programmatically change directories prior to starting the server
import socket
import SimpleHTTPServer
import SocketServer
# import os # uncomment if you want to change directories within the program
PORT = 8000
# Absolutely essential! This ensures that socket resuse is setup BEFORE
# it is bound. Will avoid the TIME_WAIT issue
class MyTCPServer(SocketServer.TCPServer):
def server_bind(self):
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.bind(self.server_address)
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = MyTCPServer(("", PORT), Handler)
# os.chdir("/My/Webpages/Live/here.html")
httpd.serve_forever()
# httpd.shutdown() # If you want to programmatically shut off the server
You want to use rand()
. Note (VERY IMPORTANT): make sure to set the seed for the rand function. If you do not, your random numbers are not truly random. This is very, very, very important. Thankfully, you can usually use some combination of the system ticks timer and the date to get a good seed.
Surprised that no one mentioned how a logger is created/retrieved. For example, below shows how Log4J logger is retrieved.
// Retrieve a logger named according to the value of the name parameter. If the named logger already exists, then the existing instance will be returned. Otherwise, a new instance is created.
public static Logger getLogger(String name)
There are some levels of indirections, but the key part is below method which pretty much tells everything about how it works. It uses a hash table to store the exiting loggers and the key is derived from name. If the logger doesn't exist for a give name, it uses a factory to create the logger and then adds it to the hash table.
69 Hashtable ht;
...
258 public
259 Logger getLogger(String name, LoggerFactory factory) {
260 //System.out.println("getInstance("+name+") called.");
261 CategoryKey key = new CategoryKey(name);
262 // Synchronize to prevent write conflicts. Read conflicts (in
263 // getChainedLevel method) are possible only if variable
264 // assignments are non-atomic.
265 Logger logger;
266
267 synchronized(ht) {
268 Object o = ht.get(key);
269 if(o == null) {
270 logger = factory.makeNewLoggerInstance(name);
271 logger.setHierarchy(this);
272 ht.put(key, logger);
273 updateParents(logger);
274 return logger;
275 } else if(o instanceof Logger) {
276 return (Logger) o;
277 }
...
For doing this in iOS 7:
[[UINavigationBar appearance] setBarTintColor:myColor];
if you are using inline coding in single page and not using oops than go with this full example, it will sure help
//connect to the db
$dbh = new PDO('mysql:host=localhost;dbname=mydb', dbuser, dbpw);
//build the query
$query="SELECT field1, field2
FROM ubertable
WHERE field1 > 6969";
//execute the query
$data = $dbh->query($query);
//convert result resource to array
$result = $data->fetchAll(PDO::FETCH_ASSOC);
//view the entire array (for testing)
print_r($result);
//display array elements
foreach($result as $output) {
echo output[field1] . " " . output[field1] . "<br />";
}
To append to an array, just use the +=
operator.
$Target += $TargetObject
Also, you need to declare $Target = @()
before your loop because otherwise, it will empty the array every loop.
I think the best method :)
int angle = 0;
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
angle = angle + 90;
imageView.setRotation(angle);
}
});
Use \overleftarrow
to create a long arrow to the left.
\overleftarrow{blahblahblah}
Those are all good answers, but don't quite touch the deep cause of the problem one most likely has if faced with the OP question. That is, not knowing the ORIGINAL "starting" password created during the installation time.
And all these command lines with "-u root ..." etc. imply knowing and using THAT password.
Now this part from the original installation message may help anyone facing the problem above:
Initial password for first time use of MySQL is saved in $HOME/.mysql_secret
ie. when you want to use "mysql -u root -p" first you should see password
in /root/.mysql_secret
You can also get some sample swagger files online to verify this(if you have errors in your swagger doc).
If the link has javascript:, then it will run javascript, otherwise, I agree with everyone else here, there's no way to do it.
SO is smart enough to filter this out!
Once you remove the ID "page_navigation" that element no longer has an ID and so cannot be found when you attempt to access it a second time.
The solution is to cache a reference to the element:
$(document).ready(function(){
// This reference remains available to the following functions
// even when the ID is removed.
var page_navigation = $("#page_navigation1");
$("#add").click(function(){
page_navigation.attr("id","page_navigation1");
});
$("#remove").click(function(){
page_navigation.removeAttr("id");
});
});
You can install the Microsoft Report Viewer 2012 Runtime and change your references so they point to the ones installed by the runtime.
http://www.microsoft.com/en-gb/download/details.aspx?id=35747
I have installed the runtime without it asking for SQL Server 2012. Before installing try uninstalling any previous versions of report viewer.
Your local web server is running different code than what you're actually working on. Ensure you have stopped debugging, stop your local web server, clean and rebuild as Peter suggested, double-check your global.asax and global.asax.cs, and try again.
If this doesn't work and you are using local IIS, try removing the site in IIS Manager and recreating it manually.
I posted a fix for this here
You can use this function to modify JSON.stringify
to encode arrays
, just post it near the beginning of your script (check the link above for more detail):
// Upgrade for JSON.stringify, updated to allow arrays
(function(){
// Convert array to object
var convArrToObj = function(array){
var thisEleObj = new Object();
if(typeof array == "object"){
for(var i in array){
var thisEle = convArrToObj(array[i]);
thisEleObj[i] = thisEle;
}
}else {
thisEleObj = array;
}
return thisEleObj;
};
var oldJSONStringify = JSON.stringify;
JSON.stringify = function(input){
if(oldJSONStringify(input) == '[]')
return oldJSONStringify(convArrToObj(input));
else
return oldJSONStringify(input);
};
})();
^[^_]*_
will match all text up to the first underscore. Replace that with the empty string.
For example, in C#:
resultString = Regex.Replace(subjectString,
@"^ # Match start of string
[^_]* # Match 0 or more characters except underscore
_ # Match the underscore", "", RegexOptions.IgnorePatternWhitespace);
For learning regexes, take a look at http://www.regular-expressions.info
For symfony 2.6 and above we can use
{{ app.user.getFirstname() }}
as app.security global variable for Twig template has been deprecated and will be removed from 3.0
more info:
http://symfony.com/blog/new-in-symfony-2-6-security-component-improvements
and see the global variables in
http://symfony.com/doc/current/reference/twig_reference.html
There are a few operations you can only do with DI/SI (or their extended counterparts, if you didn't learn ASM in 1985). Among these are
REP STOSB
REP MOVSB
REP SCASB
Which are, respectively, operations for repeated (= mass) storing, loading and scanning. What you do is you set up SI and/or DI to point at one or both operands, perhaps put a count in CX and then let 'er rip. These are operations that work on a bunch of bytes at a time, and they kind of put the CPU in automatic. Because you're not explicitly coding loops, they do their thing more efficiently (usually) than a hand-coded loop.
Just in case you're wondering: Depending on how you set the operation up, repeated storing can be something simple like punching the value 0 into a large contiguous block of memory; MOVSB is used, I think, to copy data from one buffer (well, any bunch of bytes) to another; and SCASB is used to look for a byte that matches some search criterion (I'm not sure if it's only searching on equality, or what – you can look it up :) )
That's most of what those regs are for.
Error:Execution failed for task com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException:
finished with non-zero exit value 1
One reason for this error to occure is that the file path to a resource file is to long:
Error: File path too long on Windows, keep below 240 characters
Fix: Move your project folder closer to the root of your disk
Don't:// folder/folder/folder/folder/very_long_folder_name/MyProject...
Do://folder/short_name/MyProject
Another reason could be duplicated resources or name spaces
Example:
<style name="MyButton" parent="android:Widget.Button">
<item name="android:textColor">@color/accent_color</item>
<item name="android:textColor">#000000</item>
</style>
And make sure all file names and extensions are in lowercase
Wrong
myimage.PNG
myImage.png
Correct
my_image.png
Make sure to Clean/Rebuild project
(delete the 'build' folder)
Try the Date
function. It will give you today's date in a MM/DD/YYYY format. If you're looking for today's date in the MM-DD-YYYY format try Date$
. Now()
also includes the current time (which you might not need). It all depends on what you need. :)
Maybe... :
datestamp=yyyy-MM-dd/HH:mm:ss.SSS/zzz
layout=%d{${datestamp}} ms=%-4r [%t] %-5p %l %n%m %n%n
# infoFile
log4j.appender.infoFile=org.apache.log4j.RollingFileAppender
log4j.appender.infoFile.File=${MY_HOME}/logs/message.log
log4j.appender.infoFile.layout=org.apache.log4j.PatternLayout
log4j.appender.infoFile.layout.ConversionPattern=${layout}
You get the question-mark-diamond characters when your textfile uses high-ANSI encoding -- meaning it uses characters between 127 and 255. Those characters have the eighth (i.e. the most significant) bit set. When ASP.NET reads the textfile it assumes UTF-8 encoding, and that most significant bit has a special meaning.
You must force ASP.NET to interpret the textfile as high-ANSI encoding, by telling it the codepage is 1252:
String textFilePhysicalPath = System.Web.HttpContext.Current.Server.MapPath("~/textfiles/MyInputFile.txt");
String contents = File.ReadAllText(textFilePhysicalPath, System.Text.Encoding.GetEncoding(1252));
lblContents.Text = contents.Replace("\n", "<br />"); // change linebreaks to HTML
Works for any number from 0 to 999999999.
This program gets a number from the user, divides it into three parts and stores them separately in an array. The three numbers are passed through a function that convert them into words. Then it adds "million" to the first part and "thousand" to the second part.
#include <iostream>
using namespace std;
int buffer = 0, partFunc[3] = {0, 0, 0}, part[3] = {0, 0, 0}, a, b, c, d;
long input, nFake = 0;
const char ones[][20] = {"", "one", "two", "three",
"four", "five", "six", "seven",
"eight", "nine", "ten", "eleven",
"twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen"};
const char tens[][20] = {"", "ten", "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"};
void convert(int funcVar);
int main() {
cout << "Enter the number:";
cin >> input;
nFake = input;
buffer = 0;
while (nFake) {
part[buffer] = nFake % 1000;
nFake /= 1000;
buffer++;
}
if (buffer == 0) {
cout << "Zero.";
} else if (buffer == 1) {
convert(part[0]);
} else if (buffer == 2) {
convert(part[1]);
cout << " thousand,";
convert(part[0]);
} else {
convert(part[2]);
cout << " million,";
if (part[1]) {
convert(part[1]);
cout << " thousand,";
} else {
cout << "";
}
convert(part[0]);
}
system("pause");
return (0);
}
void convert(int funcVar) {
buffer = 0;
if (funcVar >= 100) {
a = funcVar / 100;
b = funcVar % 100;
if (b)
cout << " " << ones[a] << " hundred and";
else
cout << " " << ones[a] << " hundred ";
if (b < 20)
cout << " " << ones[b];
else {
c = b / 10;
cout << " " << tens[c];
d = b % 10;
cout << " " << ones[d];
}
} else {
b = funcVar;
if (b < 20)
cout << ones[b];
else {
c = b / 10;
cout << tens[c];
d = b % 10;
cout << " " << ones[d];
}
}
}
You do not need to make an extra view for this, the functionality is already built in.
First each page with a login link needs to know the current path, and the easiest way is to add the request context preprosessor to settings.py (the 4 first are default), then the request object will be available in each request:
settings.py:
TEMPLATE_CONTEXT_PROCESSORS = (
"django.core.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.request",
)
Then add in the template you want the Login link:
base.html:
<a href="{% url django.contrib.auth.views.login %}?next={{request.path}}">Login</a>
This will add a GET argument to the login page that points back to the current page.
The login template can then be as simple as this:
registration/login.html:
{% block content %}
<form method="post" action="">
{{form.as_p}}
<input type="submit" value="Login">
</form>
{% endblock %}
You could easily replace the forward slashes /
with something like an underscore _
such as Wikipedia uses for spaces. Replacing special characters with underscores, etc., is common practice.
Just for more one option...You can do it this way too:
MYJSON = {
'username': 'gula_gut',
'pics': '/0/myfavourite.jpeg',
'id': '1'
}
#changing username
MYJSON['username'] = 'calixto'
print(MYJSON['username'])
I hope this can help.
and a shortcut:
C:\Windows\System32\cmd.exe /c start shell:AppsFolder\Microsoft.MicrosoftEdge_8wekyb3d8bbwe!MicrosoftEdge http://localhost:6516
I don't have enough reputation to comment, but in case somebody is looking for an extrapolation wrapper for a linear 2d-interpolation with scipy, I have adapted the answer that was given here for the 1d interpolation.
def extrap2d(interpolator):
xs = interpolator.x
ys = interpolator.y
zs = interpolator.z
zs = np.reshape(zs, (-1, len(xs)))
def pointwise(x, y):
if x < xs[0] or y < ys[0]:
x1_index = np.argmin(np.abs(xs - x))
x2_index = x1_index + 1
y1_index = np.argmin(np.abs(ys - y))
y2_index = y1_index + 1
x1 = xs[x1_index]
x2 = xs[x2_index]
y1 = ys[y1_index]
y2 = ys[y2_index]
z11 = zs[x1_index, y1_index]
z12 = zs[x1_index, y2_index]
z21 = zs[x2_index, y1_index]
z22 = zs[x2_index, y2_index]
return (z11 * (x2 - x) * (y2 - y) +
z21 * (x - x1) * (y2 - y) +
z12 * (x2 - x) * (y - y1) +
z22 * (x - x1) * (y - y1)
) / ((x2 - x1) * (y2 - y1) + 0.0)
elif x > xs[-1] or y > ys[-1]:
x1_index = np.argmin(np.abs(xs - x))
x2_index = x1_index - 1
y1_index = np.argmin(np.abs(ys - y))
y2_index = y1_index - 1
x1 = xs[x1_index]
x2 = xs[x2_index]
y1 = ys[y1_index]
y2 = ys[y2_index]
z11 = zs[x1_index, y1_index]
z12 = zs[x1_index, y2_index]
z21 = zs[x2_index, y1_index]
z22 = zs[x2_index, y2_index]#
return (z11 * (x2 - x) * (y2 - y) +
z21 * (x - x1) * (y2 - y) +
z12 * (x2 - x) * (y - y1) +
z22 * (x - x1) * (y - y1)
) / ((x2 - x1) * (y2 - y1) + 0.0)
else:
return interpolator(x, y)
def ufunclike(xs, ys):
if isinstance(xs, int) or isinstance(ys, int) or isinstance(xs, np.int32) or isinstance(ys, np.int32):
res_array = pointwise(xs, ys)
else:
res_array = np.zeros((len(xs), len(ys)))
for x_c in range(len(xs)):
res_array[x_c, :] = np.array([pointwise(xs[x_c], ys[y_c]) for y_c in range(len(ys))]).T
return res_array
return ufunclike
I haven't commented a lot and I am aware, that the code isn't super clean. If anybody sees any errors, please let me know. In my current use-case it is working without a problem :)
Try this tag. This will refresh the index.html
page every 30 seconds.
<meta http-equiv="refresh" content="30;url=index.html">
The simpliest way to do it is to use CancelableCallback. You should check the first action is complete and then call the second:
mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, size.x, height, 0), new CancelableCallback() {
@Override
public void onFinish() {
CameraUpdate cu_scroll = CameraUpdateFactory.scrollBy(0, 500);
mMap.animateCamera(cu_scroll);
}
@Override
public void onCancel() {
}
});
I can think of a cheeky way to do it, I don't think this will be the best option but it will work.
Create the header as a separate table then place the other in a div and set a max size, then allow the scroll to come in by using overflow
.
table {_x000D_
width: 500px;_x000D_
}_x000D_
_x000D_
.scroll {_x000D_
max-height: 60px;_x000D_
overflow: auto;_x000D_
}
_x000D_
<table border="1">_x000D_
<tr>_x000D_
<th>head1</th>_x000D_
<th>head2</th>_x000D_
<th>head3</th>_x000D_
<th>head4</th>_x000D_
</tr>_x000D_
</table>_x000D_
<div class="scroll">_x000D_
<table>_x000D_
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
<tr><td>More Text</td><td>More Text</td><td>More Text</td><td>More Text</td></tr>_x000D_
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
<tr><td>Even More Text Text</td><td>Even More Text Text</td><td>Even More Text Text</td><td>Even More Text Text</td></tr>_x000D_
</table>_x000D_
</div>
_x000D_
Note: If you have written any crash handler yourself, then the core might not get generated. So search for code with something on the line:
signal(SIGSEGV, <handler> );
so the SIGSEGV will be handled by handler and you will not get the core dump.
Here are the two main approaches. I prefer this one for its readability:
bar <- subset(foo, location == "there")
Note that you can string together many conditionals with &
and |
to create complex subsets.
The second is the indexing approach. You can index rows in R with either numeric, or boolean slices. foo$location == "there"
returns a vector of T
and F
values that is the same length as the rows of foo
. You can do this to return only rows where the condition returns true.
foo[foo$location == "there", ]
your log files shows it is stopping on error "0x8004C000"
From MS Website (http://social.technet.microsoft.com/wiki/contents/articles/15716.visual-studio-2012-and-the-error-code-2147205120.aspx):
Setup Status
Block
Restart not required
0x80044000 [-2147205120]
Restart required
0x8004C000 [-2147172352]
Description
If the only block to be reported is “Reboot Pending,” the returned value is the Incomplete-Reboot Required value (0x80048bc7).
Try not to do DOM manipulation by referring the DOM directly, it will have lot of performance issue, also event handling becomes more tricky when we try to access DOM directly, instead use data and directives to manipulate the DOM.
This will give you more control over the manipulation, also you will be able to manage functionalities in the modular format.
Some of more advanced Oracle database features such as session trace do not work properly in Oracle 11g XE 32-bit if installed on Windows 64-bit system. I needed session trace on Windows 7 64-bit.
Apart from that it works well for me in multiple production MS Windows 64-bit systems: Windows Server 2008 R2 and Windows Server 2003 R2.
You can also try
db.Courses.Include("Modules.Chapters").Single(c => c.Id == id);
in Nodejs you can use Buffer :
let str = "hello world"
let buffer = Buffer.alloc(2, str) // replace 2 by 1 for the first char
console.log(buffer.toString('utf-8')) // display he
console.log(buffer.toString('utf-8').length) // display 2
in my case the problem was the Resource
statement in the user access policy.
First we had "Resource": "arn:aws:s3:::BUCKET_NAME"
,
but in order to have access to objects within a bucket you need a /*
at the end:
"Resource": "arn:aws:s3:::BUCKET_NAME/*"
From the AWS documentation:
Bucket access permissions specify which users are allowed access to the objects in a bucket and which types of access they have. Object access permissions specify which users are allowed access to the object and which types of access they have. For example, one user might have only read permission, while another might have read and write permissions.
If using Suexec, ensure that the script and its directory are owned by the same user you specified in suexec.
In addition, ensure that the user running the cgi script has permissions execute permissions to the file AND the program specified in the shebang.
For example if my cgi script starts with
#! /usr/bin/cgirunner
Then the user needs permissions to execute /usr/bin/cgirunner.
Simple solution
{{ orderTotal | number : '1.2-2'}}
//output like this
// public orderTotal = 220.45892221
// {{ orderTotal | number : '1.2-2'}}
// final Output
// 220.45
We were using an incompatible version of Ruby inside of Terminal (Mac), but once we used RVM to switch to Ruby 2.1.2, Cocoapods came back.
The storage_path
function returns the fully qualified path to the storage directory:
$path = storage_path();
You may also use the storage_path
function to generate a fully qualified path to a given file relative to the storage directory:
$app_path = storage_path('app');
$file_path = storage_path('app/file.txt');
Source: Laravel Doc
I use runjs
like:
runjs example.js
The package is called just run
npm install -g run
scikit-learn's LinearRegression doesn't calculate this information but you can easily extend the class to do it:
from sklearn import linear_model
from scipy import stats
import numpy as np
class LinearRegression(linear_model.LinearRegression):
"""
LinearRegression class after sklearn's, but calculate t-statistics
and p-values for model coefficients (betas).
Additional attributes available after .fit()
are `t` and `p` which are of the shape (y.shape[1], X.shape[1])
which is (n_features, n_coefs)
This class sets the intercept to 0 by default, since usually we include it
in X.
"""
def __init__(self, *args, **kwargs):
if not "fit_intercept" in kwargs:
kwargs['fit_intercept'] = False
super(LinearRegression, self)\
.__init__(*args, **kwargs)
def fit(self, X, y, n_jobs=1):
self = super(LinearRegression, self).fit(X, y, n_jobs)
sse = np.sum((self.predict(X) - y) ** 2, axis=0) / float(X.shape[0] - X.shape[1])
se = np.array([
np.sqrt(np.diagonal(sse[i] * np.linalg.inv(np.dot(X.T, X))))
for i in range(sse.shape[0])
])
self.t = self.coef_ / se
self.p = 2 * (1 - stats.t.cdf(np.abs(self.t), y.shape[0] - X.shape[1]))
return self
Stolen from here.
You should take a look at statsmodels for this kind of statistical analysis in Python.
I had this problem after enabling a new service API on the Google console and trying to use the previously made credentials.
To fix the problem, I had to go back to the credential page, clicking on the credential name, and clicking "Save" again. After that, I could authenticate just fine.
Using only configuration in your app.config:
<system.diagnostics>
<trace autoflush="true" indentsize="4">
<listeners>
<add name="consoleListener" type="System.Diagnostics.ConsoleTraceListener"/>
<!--
<add name="logListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="TextWriterOutput.log" />
<add name="EventLogListener" type="System.Diagnostics.EventLogTraceListener" initializeData="MyEventLog"/>
-->
<!--
Remove the Default listener to avoid duplicate messages
being sent to the debugger for display
-->
<remove name="Default" />
</listeners>
</trace>
</system.diagnostics>
For testing, you can use DebugView before running the program, then we can easily view all of the log messages.
References:
http://blogs.msdn.com/b/jjameson/archive/2009/06/18/configuring-logging-in-a-console-application.aspx
http://www.thejoyofcode.com/from_zero_to_logging_with_system_diagnostics_in_15_minutes.aspx
Redirect Trace output to Console
Problem redirecting debug output to a file using trace listener
https://ukadcdiagnostics.codeplex.com/
http://geekswithblogs.net/theunstablemind/archive/2009/09/09/adventures-in-system.diagnostics.aspx
I was looking at @jaider's solution which worked but I'm offering a slightly different approach that I think is more easy to work with and which I've seen to be good across browsers.
ul{
list-style-type: disc;
-webkit-columns: 2;
-moz-columns: 2;
columns: 2;
list-style-position: inside;//this is important addition
}
By default un-ordered list display the bullet position outside but then in some browsers it would cause some display problems based on the browser's way of laying out your website.
To get it to display in the format:
A B
C D
E
etc. use the following:
ul li{
float: left;
width: 50%;//helps to determine number of columns, for instance 33.3% displays 3 columns
}
ul{
list-style-type: disc;
}
This should solve all your problems with displaying columns. All the best and thanks @jaider as your response helped to guide me to discover this.
Use Range in Python 3.
Here is a example function that return in between numbers from two numbers
def get_between_numbers(a, b):
"""
This function will return in between numbers from two numbers.
:param a:
:param b:
:return:
"""
x = []
if b < a:
x.extend(range(b, a))
x.append(a)
else:
x.extend(range(a, b))
x.append(b)
return x
Result
print(get_between_numbers(5, 9))
print(get_between_numbers(9, 5))
[5, 6, 7, 8, 9]
[5, 6, 7, 8, 9]
I made my small method to log JsonObject fields, and get some stings. See if it can be usefull.
object JsonParser {
val TAG = "JsonParser"
/**
* parse json object
* @param objJson
* @return Map<String, String>
* @throws JSONException
*/
@Throws(JSONException::class)
fun parseJson(objJson: Any?): Map<String, String> {
val map = HashMap<String, String>()
// If obj is a json array
if (objJson is JSONArray) {
for (i in 0 until objJson.length()) {
parseJson(objJson[i])
}
} else if (objJson is JSONObject) {
val it: Iterator<*> = objJson.keys()
while (it.hasNext()) {
val key = it.next().toString()
// If you get an array
when (val jobject = objJson[key]) {
is JSONArray -> {
Log.e(TAG, " JSONArray: $jobject")
parseJson(jobject)
}
is JSONObject -> {
Log.e(TAG, " JSONObject: $jobject")
parseJson(jobject)
}
else -> {
Log.e(TAG, " adding to map: $key $jobject")
map[key] = jobject.toString()
}
}
}
}
return map
}
}
select * into newtable from oldtable
Simple function to alert contents of an object or an array .
Call this function with an array or string or an object it alerts the contents.
Function
function print_r(printthis, returnoutput) {
var output = '';
if($.isArray(printthis) || typeof(printthis) == 'object') {
for(var i in printthis) {
output += i + ' : ' + print_r(printthis[i], true) + '\n';
}
}else {
output += printthis;
}
if(returnoutput && returnoutput == true) {
return output;
}else {
alert(output);
}
}
Usage
var data = [1, 2, 3, 4];
print_r(data);
Simple way to deal with merging single array values.
var values[0] = {"id":1235,"name":"value 1"}
values[1] = {"id":4323,"name":"value 2"}
var object=null;
var first=values[0];
for (var i in values)
if(i>0)
object= $.merge(values[i],first)
If you're using WPF and the previous answers don't help, you can retrieve the result using:
var result = MessageBox.Show("Message", "caption", MessageBoxButton.YesNo, MessageBoxImage.Question);
if (result == MessageBoxResult.Yes)
{
// Do something
}
Thanks all for your help! Finally I used JQuery/AJAX as you suggested, passing the parameter using model.
So, in JS:
$('#divPoints').load('/Schedule/UpdatePoints', UpdatePointsAction);
var points= $('#newpoints').val();
$element.find('PointsDiv').html("You have" + points+ " points");
In Controller:
var model = _newPoints;
return PartialView(model);
In View
<div id="divPoints"></div>
@Html.Hidden("newpoints", Model)
As mentioned in previous answers, you can cast directly to the underlying datatype (int -> enum type) or parse (string -> enum type).
but beware - there is no .TryParse for enums, so you WILL need a try/catch block around the parse to catch failures.
Which method is used to check if SESSION exists or not? Answer:
isset($_SESSION['variable_name'])
Example:
isset($_SESSION['id'])
Modified this SO answer by @DannyA
private void copyAssets(String path, String outPath) {
AssetManager assetManager = this.getAssets();
String assets[];
try {
assets = assetManager.list(path);
if (assets.length == 0) {
copyFile(path, outPath);
} else {
String fullPath = outPath + "/" + path;
File dir = new File(fullPath);
if (!dir.exists())
if (!dir.mkdir()) Log.e(TAG, "No create external directory: " + dir );
for (String asset : assets) {
copyAssets(path + "/" + asset, outPath);
}
}
} catch (IOException ex) {
Log.e(TAG, "I/O Exception", ex);
}
}
private void copyFile(String filename, String outPath) {
AssetManager assetManager = this.getAssets();
InputStream in;
OutputStream out;
try {
in = assetManager.open(filename);
String newFileName = outPath + "/" + filename;
out = new FileOutputStream(newFileName);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
out.flush();
out.close();
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
Preparations
in src/main/assets
add folder with name fold
Usage
File outDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString());
copyAssets("fold",outDir.toString());
In to the external directory find all files and directories that are within the fold assets
I don't believe the expression is sensical as it is.
Elvis means "if truthy, use the value, else use this other thing."
Your "other thing" is a closure, and the value is status != null
, neither of which would seem to be what you want. If status
is null, Elvis says true
. If it's not, you get an extra layer of closure.
Why can't you just use:
(it.description == desc) && ((status == null) || (it.status == status))
Even if that didn't work, all you need is the closure to return the appropriate value, right? There's no need to create two separate find
calls, just use an intermediate variable.
because if you change your code with
def gukan(count):
while count!=100:
print(count)
count=count+3;
gukan(0)
count reaches 99 and then, at the next iteration 102.
So
count != 100
never evaluates true and the loop continues forever
If you want to count up to 100 you may use
def gukan(count):
while count <= 100:
print(count)
count=count+3;
gukan(0)
or (if you want 100 always printed)
def gukan(count):
while count <= 100:
print(count)
count=count+3;
if count > 100:
count = 100
gukan(0)
There is a difference between single and double quotes. (I am using PowerShell 4).
You can do this (as Benjamin said):
$name = 'Slim Shady'
Write-Host 'My name is'$name
-> My name is Slim Shady
Or you can do this:
$name = 'Slim Shady'
Write-Host "My name is $name"
-> My name is Slim Shady
The single quotes are for literal, output the string exactly like this, please. The double quotes are for when you want some pre-processing done (such as variables, special characters, etc.)
So:
$name = "Marshall Bruce Mathers III"
Write-Host "$name"
-> Marshall Bruce Mathers III
Whereas:
$name = "Marshall Bruce Mathers III"
Write-Host '$name'
-> $name
(I find How-to: Escape characters, Delimiters and Quotes good for reference).
As an alternative to @Mark Byers' approach, you can use while True
:
guess = 50 # this should be outside the loop, I think
while True: # infinite loop
n = raw_input("\n\nTrue, False or Correct?: ")
if n == "Correct":
break # stops the loop
elif n == "True":
# etc.
Every coder need to simplify their code to make it easily understood....even for beginners.
So array of structures using dynamically is easy, if you understand the concepts.
// Dynamically sized array of structures
#include <stdio.h>
#include <stdlib.h>
struct book
{
char name[20];
int p;
}; //Declaring book structure
int main ()
{
int n, i;
struct book *b; // Initializing pointer to a structure
scanf ("%d\n", &n);
b = (struct book *) calloc (n, sizeof (struct book)); //Creating memory for array of structures dynamically
for (i = 0; i < n; i++)
{
scanf ("%s %d\n", (b + i)->name, &(b + i)->p); //Getting values for array of structures (no error check)
}
for (i = 0; i < n; i++)
{
printf ("%s %d\t", (b + i)->name, (b + i)->p); //Printing values in array of structures
}
scanf ("%d\n", &n); //Get array size to re-allocate
b = (struct book *) realloc (b, n * sizeof (struct book)); //change the size of an array using realloc function
printf ("\n");
for (i = 0; i < n; i++)
{
printf ("%s %d\t", (b + i)->name, (b + i)->p); //Printing values in array of structures
}
return 0;
}
Well i have watched these answers but in my case i fell into the same issue and got refuge through a very handy and easiest solution that involves putting a very small innocent attribute in your Scrollview tag residing in your xml file. That is
android:isScrollContainer="false"
Good luck!
Try this:
TextView c1 = new TextView(activity);
c1.setTextColor(getResources().getColor(R.color.solid_red));
c1.setText("My Text");
I agree that a color and a resource have the same type, but I also spend a few hours to find this solution.
Just in case you actually mean 'discard changes' whenever you use 'git stash' (and don't really use git stash to stash it temporarily), in that case you can use
git checkout -- <file>
Note that git stash is just a quicker and simple alternative to branching and doing stuff.
You can create a custom discrete colorbar quite easily by using a BoundaryNorm as normalizer for your scatter. The quirky bit (in my method) is making 0 showup as grey.
For images i often use the cmap.set_bad() and convert my data to a numpy masked array. That would be much easier to make 0 grey, but i couldnt get this to work with the scatter or the custom cmap.
As an alternative you can make your own cmap from scratch, or read-out an existing one and override just some specific entries.
import numpy as np
import matplotlib as mpl
import matplotlib.pylab as plt
fig, ax = plt.subplots(1, 1, figsize=(6, 6)) # setup the plot
x = np.random.rand(20) # define the data
y = np.random.rand(20) # define the data
tag = np.random.randint(0, 20, 20)
tag[10:12] = 0 # make sure there are some 0 values to show up as grey
cmap = plt.cm.jet # define the colormap
# extract all colors from the .jet map
cmaplist = [cmap(i) for i in range(cmap.N)]
# force the first color entry to be grey
cmaplist[0] = (.5, .5, .5, 1.0)
# create the new map
cmap = mpl.colors.LinearSegmentedColormap.from_list(
'Custom cmap', cmaplist, cmap.N)
# define the bins and normalize
bounds = np.linspace(0, 20, 21)
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
# make the scatter
scat = ax.scatter(x, y, c=tag, s=np.random.randint(100, 500, 20),
cmap=cmap, norm=norm)
# create a second axes for the colorbar
ax2 = fig.add_axes([0.95, 0.1, 0.03, 0.8])
cb = plt.colorbar.ColorbarBase(ax2, cmap=cmap, norm=norm,
spacing='proportional', ticks=bounds, boundaries=bounds, format='%1i')
ax.set_title('Well defined discrete colors')
ax2.set_ylabel('Very custom cbar [-]', size=12)
I personally think that with 20 different colors its a bit hard to read the specific value, but thats up to you of course.
Here other Example with simple jQuery and property data-checked
:
$("#checkbox")_x000D_
.click(function(e) {_x000D_
var el = $(this);_x000D_
_x000D_
switch (el.data('checked')) {_x000D_
_x000D_
// unchecked, going indeterminate_x000D_
case 0:_x000D_
el.data('checked', 1);_x000D_
el.prop('indeterminate', true);_x000D_
break;_x000D_
_x000D_
// indeterminate, going checked_x000D_
case 1:_x000D_
el.data('checked', 2);_x000D_
el.prop('indeterminate', false);_x000D_
el.prop('checked', true);_x000D_
break;_x000D_
_x000D_
// checked, going unchecked_x000D_
default:_x000D_
el.data('checked', 0);_x000D_
el.prop('indeterminate', false);_x000D_
el.prop('checked', false);_x000D_
_x000D_
}_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<label><input type="checkbox" name="checkbox" value="" checked id="checkbox"> Tri-State Checkbox </label>
_x000D_
I like to do something similar to this (though it is still very similar to using a cursor)
[code]
-- Table variable to hold list of things that need looping
DECLARE @holdStuff TABLE (
id INT IDENTITY(1,1) ,
isIterated BIT DEFAULT 0 ,
someInt INT ,
someBool BIT ,
otherStuff VARCHAR(200)
)
-- Populate your @holdStuff with... stuff
INSERT INTO @holdStuff (
someInt ,
someBool ,
otherStuff
)
SELECT
1 , -- someInt - int
1 , -- someBool - bit
'I like turtles' -- otherStuff - varchar(200)
UNION ALL
SELECT
42 , -- someInt - int
0 , -- someBool - bit
'something profound' -- otherStuff - varchar(200)
-- Loop tracking variables
DECLARE @tableCount INT
SET @tableCount = (SELECT COUNT(1) FROM [@holdStuff])
DECLARE @loopCount INT
SET @loopCount = 1
-- While loop variables
DECLARE @id INT
DECLARE @someInt INT
DECLARE @someBool BIT
DECLARE @otherStuff VARCHAR(200)
-- Loop through item in @holdStuff
WHILE (@loopCount <= @tableCount)
BEGIN
-- Increment the loopCount variable
SET @loopCount = @loopCount + 1
-- Grab the top unprocessed record
SELECT TOP 1
@id = id ,
@someInt = someInt ,
@someBool = someBool ,
@otherStuff = otherStuff
FROM @holdStuff
WHERE isIterated = 0
-- Update the grabbed record to be iterated
UPDATE @holdAccounts
SET isIterated = 1
WHERE id = @id
-- Execute your stored procedure
EXEC someRandomSp @someInt, @someBool, @otherStuff
END
[/code]
Note that you don't need the identity or the isIterated column on your temp/variable table, i just prefer to do it this way so i don't have to delete the top record from the collection as i iterate through the loop.
You are right. If you want to delete the User and all associated objects -> destroy_all
However, if you just want to delete the User without suppressing all associated objects -> delete_all
According to this post : Rails :dependent => :destroy VS :dependent => :delete_all
destroy
/ destroy_all
: The associated objects are destroyed alongside this object by calling their destroy methoddelete
/ delete_all
: All associated objects are destroyed immediately without calling their :destroy methodYou are not using the "null" and therefore you don't get the exception. If you want the NullPointer, just do
String s = null;
s = s.toString() + "hello";
And I think what you want to do is:
String s = "";
s = s + "hello";
To my surprise, clearing temp files located in the %TEMP%
directory resolved the issue for me.
Note: This path is generally at C:\Users\(yourusername)\AppData\Local\Temp
As @Warren-P included, you can navigate to the temp folder by putting in %temp%
in Start Menu, or launch "File Explorer" and enter %temp%
in the address bar.
If it's an unknown amount of strings you could trim off the last character by doing s = s.TrimEnd('','!').Trim();
Have you considered using a regular expression? If you only want to allow alpha numeric characters you can use regex to replace the symbols, What if instead of a ! you get a %?
Since this question become popular on Stack Overflow, I am posting an answer which answers this question for me. I found this answer on udemy website. Hope this will help future users and newbies searching for a good answer on this topic.
The key difference is that RDBMS (relational database management system) applications store data in a tabular form, while DBMS applications store data as files.
Does that mean there are no tables in a DBMS?
There can be, but there will be no “relation” between the tables, like in a RDBMS. In DBMS, data is generally stored in either a hierarchical form or a navigational form. This means that a single data unit will have one parent node and zero, one or more children nodes. It may even be stored in a graph form, which can be seen in the network model.
In a RDBMS, the tables will have an identifier called primary key. Data values will be stored in the form of tables. The relationships between these data values will be stored in the form of a table as well. Every value stored in the relational database is accessible. This value can be updated by the system. The data in this system is also physically and logically independent.
You can say that a RDBMS is an extension of a DBMS, even if there are many differences between the two. Most software products in the market today are both DBMS and RDBMS compliant. Essentially, they can maintain databases in a (relational) tabular form as well as a file form, or both. This means that today a RDBMS application is a DBMS application, and vice versa. However, there are still major differences between a relational database system for storing data and a plain database system.
Python 3:
import urllib.request
htmlsource = urllib.request.FancyURLopener({"http":"http://127.0.0.1:8080"}).open(url).read().decode("utf-8")
add this cookie plugin for jquery.
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
Here is another tool that works very well...
http://www.convertcsv.com/csv-to-sql.htm
It can take tab separated values and generate an INSERT script. Just copy and paste and in the options under step 2 check the box "First row is column names"
Then scroll down and under step 3, enter your table name in the box "Schema.Table or View Name:"
Pay attention to the delete and create table check boxes as well, and make sure you examine the generated script before running it.
This is the quickest and most reliable way I've found.
You can use /* tslint:disable-next-line */
to locally disable tslint. However, as this is a compiler error disabling tslint might not help.
You can always temporarily cast $
to any
:
delete ($ as any).summernote.options.keyMap.pc.TAB
which will allow you to access whatever properties you want.
Edit: As of Typescript 2.6, you can now bypass a compiler error/warning for a specific line:
if (false) {
// @ts-ignore: Unreachable code error
console.log("hello");
}
Note that the official docs "recommend you use [this] very sparingly". It is almost always preferable to cast to any
instead as that better expresses intent.
I loved the FireFox Header Spy extension so much that i built a HTTP Spy extension for Chrome. I used to use the developer tools too for debugging headers, but now my life is so much better.
Here is a Chrome extension that allows you to view request-, response headers and cookies without any extra clicks right after the page is loaded.
It also handles redirects. It comes with an unobtrusive micro-mode that only shows a hand picked selection of response headers and a normal mode that shows all the information.
https://chrome.google.com/webstore/detail/http-spy/agnoocojkneiphkobpcfoaenhpjnmifb
Enjoy!
Try this, add this lines in the web.config.
<system.webServer>
<staticContent>
<mimeMap fileExtension=".woff" mimeType="application/octet-stream" />
</staticContent>
</system.webServer>
size_t lf = strlen(first);
size_t ls = strlen(second);
char *both = (char*) malloc((lf + ls + 2) * sizeof(char));
strcpy(both, first);
both[lf] = ' ';
strcpy(&both[lf+1], second);
Either use window.onload
this way
<script>
window.onload = function() {
// ...
}
</script>
or alternatively
<script>
window.onload = functionName;
</script>
(yes, without the parentheses)
Or just put the script at the very bottom of page, right before </body>
. At that point, all HTML DOM elements are ready to be accessed by document
functions.
<body>
...
<script>
functionName();
</script>
</body>
Steps to Create Radio Button
BasicStep : take Two Button. set image for both like selected and unselected. than add action to both button. now start code
1)Create variable :
var btnTag : Int = 0
2)In ViewDidLoad Define :
btnTag = btnSelected.tag
3)Now In Selected Tap Action :
@IBAction func btnSelectedTapped(sender: AnyObject) {
btnTag = 1
if btnTag == 1 {
btnSelected.setImage(UIImage(named: "icon_radioSelected"), forState: .Normal)
btnUnSelected.setImage(UIImage(named: "icon_radioUnSelected"), forState: .Normal)
btnTag = 0
}
}
4)Do code for UnCheck Button
@IBAction func btnUnSelectedTapped(sender: AnyObject) {
btnTag = 1
if btnTag == 1 {
btnUnSelected.setImage(UIImage(named: "icon_radioSelected"), forState: .Normal)
btnSelected.setImage(UIImage(named: "icon_radioUnSelected"), forState: .Normal)
btnTag = 0
}
}
Radio Button is Ready for you
This is another approach.
render() {
return {this[`renderStep${this.state.step}`]()}
renderStep0() { return 'step 0' }
renderStep1() { return 'step 1' }
Two approaches that come to mind:
>>> df
A B C D
0 0.424634 1.716633 0.282734 2.086944
1 -1.325816 2.056277 2.583704 -0.776403
2 1.457809 -0.407279 -1.560583 -1.316246
3 -0.757134 -1.321025 1.325853 -2.513373
4 1.366180 -1.265185 -2.184617 0.881514
>>> df.iloc[:, 2]
0 0.282734
1 2.583704
2 -1.560583
3 1.325853
4 -2.184617
Name: C
>>> df[df.columns[2]]
0 0.282734
1 2.583704
2 -1.560583
3 1.325853
4 -2.184617
Name: C
Edit: The original answer suggested the use of df.ix[:,2]
but this function is now deprecated. Users should switch to df.iloc[:,2]
.
Change the group permission for the folder
sudo chown -R w3cert /home/w3cert/.composer/cache/repo/https---packagist.org
and the Files folder too
sudo chown -R w3cert /home/w3cert/.composer/cache/files/
I'm assuming w3cert is your username, if not change the 4th parameter to your username.
If the problem still persists try
sudo chown -R w3cert /home/w3cert/.composer
Now, there is a chance that you won't be able to create your app directory, if that happens do the same for your html folder or the folder you are trying to create your laravel project in.
Hope this helps.
I use this "Win64 OpenSSL v1.1.1h" -> EXE from https://slproweb.com/products/Win32OpenSSL.html
i've installed it and works
404 Not Found technically means that uri does not currently map to a resource. In your example, I interpret a request to http://mywebsite/api/user/13
that returns a 404 to imply that this url was never mapped to a resource. To the client, that should be the end of conversation.
To address concerns with ambiguity, you can enhance your API by providing other response codes. For example, suppose you want to allow clients to issue GET requests the url http://mywebsite/api/user/13
, you want to communicate that clients should use the canonical url http://mywebsite/restapi/user/13
. In that case, you may want to consider issuing a permanent redirect by returning a 301 Moved Permanently and supply the canonical url in the Location header of the response. This tells the client that for future requests they should use the canonical url.
The compiler doesn't know that the Environment.Exit() is going to terminate the program; it just sees you executing a static method on a class. Just initialize queue
to null when you declare it.
Queue queue = null;
To show months as Jan 2017 Feb 2017 etc:
scale_x_date(date_breaks = "1 month", date_labels = "%b %Y")
Angle the dates if they take up too much space:
theme(axis.text.x=element_text(angle=60, hjust=1))
You have to replace the values one by one such as in a for-loop or copying another array over another such as using memcpy(..)
or std::copy
e.g.
for (int i = 0; i < arrayLength; i++) {
array[i] = newValue[i];
}
Take care to ensure proper bounds-checking and any other checking that needs to occur to prevent an out of bounds problem.
Put them in brackets []
:
var cleanString = dirtyString.replace(/[\|&;\$%@"<>\(\)\+,]/g, "");
I haven't checked this extensively, but I'm under the impression that this isn't (yet?) possible, due to the way in which select
elements are generated by the OS on which the browser runs, rather than the browser itself.
All of the answers (at the time of this writing) assume each of Redis, MongoDB, and perhaps an SQL-based relational database are essentially the same tool: "store data". They don't consider data models at all.
MongoDB is a document store. To compare with an SQL-driven relational database: relational databases simplify to indexed CSV files, each file being a table; document stores simplify to indexed JSON files, each file being a document, with multiple files grouped together.
JSON files are similar in structure to XML and YAML files, and to dictionaries as in Python, so think of your data in that sort of hierarchy. When indexing, the structure is the key: A document contains named keys, which contain either further documents, arrays, or scalar values. Consider the below document.
{
_id: 0x194f38dc491a,
Name: "John Smith",
PhoneNumber:
Home: "555 999-1234",
Work: "555 999-9876",
Mobile: "555 634-5789"
Accounts:
- "379-1111"
- "379-2574"
- "414-6731"
}
The above document has a key, PhoneNumber.Mobile
, which has value 555 634-5789
. You can search through a collection of documents where the key, PhoneNumber.Mobile
, has some value; they're indexed.
It also has an array of Accounts
which hold multiple indexes. It is possible to query for a document where Accounts
contains exactly some subset of values, all of some subset of values, or any of some subset of values. That means you can search for Accounts = ["379-1111", "379-2574"]
and not find the above; you can search for Accounts includes ["379-1111"]
and find the above document; and you can search for Accounts includes any of ["974-3785","414-6731"]
and find the above and whatever document includes account "974-3785", if any.
Documents go as deep as you want. PhoneNumber.Mobile
could hold an array, or even a sub-document (PhoneNumber.Mobile.Work
and PhoneNumber.Mobile.Personal
). If your data is highly structured, documents are a large step up from relational databases.
If your data is mostly flat, relational, and rigidly structured, you're better off with a relational database. Again, the big sign is whether your data models best to a collection of interrelated CSV files or a collection of XML/JSON/YAML files.
For most projects, you'll have to compromise, accepting a minor work-around in some small areas where either SQL or Document Stores don't fit; for some large, complex projects storing a broad spread of data (many columns; rows are irrelevant), it will make sense to store some data in one model and other data in another model. Facebook uses both SQL and a graph database (where data is put into nodes, and nodes are connected to other nodes); Craigslist used to use MySQL and MongoDB, but had been looking into moving entirely onto MongoDB. These are places where the span and relationship of the data faces significant handicaps if put under one model.
Redis is, most basically, a key-value store. Redis lets you give it a key and look up a single value. Redis itself can store strings, lists, hashes, and a few other things; however, it only looks up by name.
Cache invalidation is one of computer science's hard problems; the other is naming things. That means you'll use Redis when you want to avoid hundreds of excess look-ups to a back-end, but you'll have to figure out when you need a new look-up.
The most obvious case of invalidation is update on write: if you read user:Simon:lingots = NOTFOUND
, you might SELECT Lingots FROM Store s INNER JOIN UserProfile u ON s.UserID = u.UserID WHERE u.Username = Simon
and store the result, 100
, as SET user:Simon:lingots = 100
. Then when you award Simon 5 lingots, you read user:Simon:lingots = 100
, SET user:Simon:lingots = 105
, and UPDATE Store s INNER JOIN UserProfile u ON s.UserID = u.UserID SET s.Lingots = 105 WHERE u.Username = Simon
. Now you have 105 in your database and in Redis, and can get user:Simon:lingots
without querying the database.
The second case is updating dependent information. Let's say you generate chunks of a page and cache their output. The header shows the player's experience, level, and amount of money; the player's Profile page has a block that shows their statistics; and so forth. The player gains some experience. Well, now you have several templates:Header:Simon
, templates:StatsBox:Simon
, templates:GrowthGraph:Simon
, and so forth fields where you've cached the output of a half-dozen database queries run through a template engine. Normally, when you display these pages, you say:
$t = GetStringFromRedis("templates:StatsBox:" + $playerName);
if ($t == null) {
$t = BuildTemplate("StatsBox.tmpl",
GetStatsFromDatabase($playerName));
SetStringInRedis("Templates:StatsBox:" + $playerName, $t);
}
print $t;
Because you just updated the results of GetStatsFromDatabase("Simon")
, you have to drop templates:*:Simon
out of your key-value cache. When you try to render any of these templates, your application will churn away fetching data from your database (PostgreSQL, MongoDB) and inserting it into your template; then it will store the result in Redis and, hopefully, not bother making database queries and rendering templates the next time it displays that block of output.
Redis also lets you do publisher-subscribe message queues and such. That's another topic entirely. Point here is Redis is a key-value cache, which differs from a relational database or a document store.
Pick your tools based on your needs. The largest need is usually data model, as that determines how complex and error-prone your code is. Specialized applications will lean on performance, places where you write everything in a mixture of C and Assembly; most applications will just handle the generalized case and use a caching system such as Redis or Memcached, which is a lot faster than either a high-performance SQL database or a document store.
Most modern browser support console.dir(obj)
, which will return all the properties of an object that it inherited through its constructor. See Mozilla's documentation for more info and current browser support.
console.dir(Math)
=> MathConstructor
E: 2.718281828459045
LN2: 0.6931471805599453
...
tan: function tan() { [native code] }
__proto__: Object
This scenario comes up when you -- or forces greater than you -- have mangled a file in your local repo and you just want to restore a fresh copy of the latest version of it from the repo. Simply deleting the file with /bin/rm (not git rm) or renaming/hiding it and then issuing a git pull
will not work: git notices the file's absence and assumes you probably want it gone from the repo (git diff
will show all lines deleted from the missing file).
git pull
not restoring locally missing files has always frustrated me about git, perhaps since I have been influenced by other version control systems (e.g. svn update which I believe will restore files that have been locally hidden).
git reset --hard HEAD
is an alternative way to restore the file of interest as it throws away any uncommitted changes you have. However, as noted here, git reset is is a potentially dangerous command if you have any other uncommitted changes that you care about.
The git fetch ... git checkout
strategy noted above by @chrismillah is a nice surgical way to restore the file in question.
See also here: http://sqlblog.com/blogs/alexander_kuznetsov/archive/2008/06/26/fun-with-dbcc-chekident.aspx
This is documented behavior, why do you run CHECKIDENT if you recreate the table, in that case skip the step or use TRUNCATE (if you don't have FK relationships)
strRetMsg ="<script>window.location.href = '../Other/Home.htm';</script>";
Page.ClientScript.RegisterStartupScript(this.GetType(), "Script", strRetMsg,false);
Put this code in Page Load.
Java is a verbose language.
If you are only 3 days in, and this is already bothering you, maybe you'd be better off learning a different language like Scala:
scala> println("Hello World")
Hello World
In a loose sense, this would qualify as using a "library" to enable shorter expressions ;)
Along with the already suggested methods of using a foreach
loop, I thought I'd also mention that any object that implements IEnumerable
also provides an IEnumerator
interface via the GetEnumerator
method. Although this method is usually not necessary, this can be used for manually iterating over collections, and is particularly useful when writing your own extension methods for collections.
IEnumerable<T> mySequence;
using (var sequenceEnum = mySequence.GetEnumerator())
{
while (sequenceEnum.MoveNext())
{
// Do something with sequenceEnum.Current.
}
}
A prime example is when you want to iterate over two sequences concurrently, which is not possible with a foreach
loop.
in pure js just use offsetLeft
and offsetTop
properties.
Example fiddle: http://jsfiddle.net/WKZ8P/
var elm = document.querySelector('span');_x000D_
console.log(elm.offsetLeft, elm.offsetTop);
_x000D_
p { position:relative; left:10px; top:85px; border:1px solid blue; }_x000D_
span{ position:relative; left:30px; top:35px; border:1px solid red; }
_x000D_
<p>_x000D_
<span>paragraph</span>_x000D_
</p>
_x000D_
driver.execute_script("document.getElementById('your ID Element').scrollIntoView();")
it's working for my case.
You have three possibilites:
(new RegExp('word')).test(str)
// or
/word/.test(str)
str.indexOf('word') !== -1
str.includes('word')
Regular expressions seem to be faster (at least in Chrome 10).
Performance test - short haystack
Performance test - long haystack
It cannot be said with certainty which method is faster. The differences between the browsers is enormous. While in Chrome 10 indexOf
seems to be faster, in Safari 5, indexOf
is clearly slower than any other method.
You have to see and try for your self. It depends on your needs. For example a case-insensitive search is way faster with regular expressions.
Update 2018:
Just to save people from running the tests themselves, here are the current results for most common browsers, the percentages indicate performance increase over the next fastest result (which varies between browsers):
Chrome: indexOf (~98% faster) <-- wow
Firefox: cached RegExp (~18% faster)
IE11: cached RegExp(~10% faster)
Edge: indexOf (~18% faster)
Safari: cached RegExp(~0.4% faster)
Note that cached RegExp is: var r = new RegExp('simple'); var c = r.test(str);
as opposed to: /simple/.test(str)
Markup
<asp:TextBox ID="txtDateOfBirth" runat="server" onkeydown="javascript:preventInput(event);" onpaste="return false;"
TabIndex="1">
Script
function preventInput(evnt) {
//Checked In IE9,Chrome,FireFox
if (evnt.which != 9) evnt.preventDefault();}
Instead of using --no-optional
every single time, we can just add it to npm or yarn config.
For Yarn, there is a default no-optional config, so we can just edit that:
yarn config set ignore-optional true
For npm, there is no default config set, so we can create one:
npm config set ignore-optional true
Try this:
$(function() {
$("#type").change(function() {
if ($(this).val() === 'parcel') $("#row_dim").show();
else $("#row_dim").hide();
}
}
This obviously solution was not mentioned earlier. You can also use cookies to pass data from the browser back to the server.
Just set a cookie with the data you want to pass to PHP using javascript in the browser.
Then, simply read this cookie on the PHP side.
Read and remember each line
Identify the one you want to get rid of
Forget that one
Write the rest back over the top of the file