Simple PHP solution for subdomains and multi-domain web apps
Step 1. Provide DNS A record as "*" for domains (or domain) you gonna serve "example.org"
A record => *.example.org
A record => *.example.net
Step 2. Check uniquity of logins when user registering or changing login. Also, avoid dots in those logins.
Step 3. Then check the query
// Request was http://qwerty.example.org
$q = explode('.', $_SERVER['HTTP_HOST']);
/*
We get following array
Array
(
[0] => qwerty
[1] => example
[2] => org
)
*/
// Step 4.
// If second piece of array exists, request was for
// SUBDOMAIN which is stored in zero-piece $q[0]
// otherwise it was for DOMAIN
if(isset($q[2])) {
// Find stuff in database for login $q[0] or here it is "qwerty"
// Use $q[1] to check which domain is asked if u serve multiple domains
}
?>
This solution may serve different domains
qwerty.example.org
qwerty.example.net
johnsmith.somecompany.com
paulsmith.somecompany.com
If you need same nicks on different domains served differently, you may need to store user choise for domain when registering login.
smith.example.org // Show info about John Smith
smith.example.net // Show info about Paul Smith
This also works for https needed a solution to making project directories this was it. because chrome doesn't like non ssl anymore used free ssl. Notice: My Web Server is Wamp64 on Windows 10 so I wouldn't use this config because of variables unless your using wamp.
<VirtualHost *:443>
ServerAdmin [email protected]
ServerName test.com
ServerAlias *.test.com
SSLEngine On
SSLCertificateFile "conf/key/certificatecom.crt"
SSLCertificateKeyFile "conf/key/privatecom.key"
VirtualDocumentRoot "${INSTALL_DIR}/www/subdomains/%1/"
DocumentRoot "${INSTALL_DIR}/www/subdomains"
<Directory "${INSTALL_DIR}/www/subdomains/">
Options +Indexes +Includes +FollowSymLinks +MultiViews
AllowOverride All
Require all granted
</Directory>
As DotNetMensch said but you DO NOT need to add another site in IIS as this can also cause further problems and make things more complicated because you then have a website within a website so the file paths, masterpage paths and web.config paths may need changing. You just need to edit teh bindings of the existing site and add the new subdomain there.
So:
Add sub-domain to DNS records. My host (RackSpace) uses a web portal to do this so you just log in and go to Network->Domains(DNS)->Actions->Create Zone, and enter your subdomain as mysubdomain.domain.com etc, leave the other settings as default
Go to your domain in IIS, right-click->Edit Bindings->Add, and add your new subdomain leaving everything else the same e.g. mysubdomain.domain.com
You may need to wait 5-10 mins for the DNS records to update but that's all you need.
sub domain is part of the domain, it's like subletting a room of an apartment. A records has to be setup on the dns for the domain e.g
mydomain.com has IP 123.456.789.999 and hosted with Godaddy. Now to get the sub domain
anothersite.mydomain.com
of which the site is actually on another server then
login to Godaddy and add an A record dnsimple anothersite.mydomain.com and point the IP to the other server 98.22.11.11
And that's it.
Try to putting this .htaccess file on subdomain folder:
RewriteEngine On
RewriteRule ^(.*)?$ ./subdomains/sub/$1
It redirects to http://domain.com/subdomains/sub/, when you only want it to show http://sub.domain.com/
Another type of solution would be to autogenerate the nginx conf files via Jinja2 templates from ansible. The advantage of this is easy deployment to a cloud environment, and easy to replicate on multiple dev machines
Be careful if you are working on localhost ! If you store your cookie in js like this:
document.cookie = "key=value;domain=localhost"
It might not be accessible to your subdomain, like sub.localhost
. In order to solve this issue you need to use Virtual Host. For exemple you can configure your virtual host with ServerName
localhost.com
then you will be able to store your cookie on your domain and subdomain like this:
document.cookie = "key=value;domain=localhost.com"
If the DNS server is configured properly, you won't be able to get the entire domain. If for some reason is allows zone transfers from any host, you'll have to send it the correct packet to make that request. I suspect that's what the dig statement you included does.
this kind of solution causes many problems like this. for consistency and SEO considerations redirect on the main domain is the best solution.
do it redirection at the server level
How To Redirect www to Non-www with Nginx
or any other level like route 53 if are using
Just created local project (with vagrant) and it was working perfectly when accessed over ip address. Then I added some_name.test to hosts file and tried accessing it that way, but I was getting "bad request - 400" all the time. Wasted hours until I figured out that just changing domain name to some-name.test solves the problem. So at least locally on Mac OS it's not working.
First Go to Settings in Postman:
$host = $_SERVER['HTTP_HOST'];
preg_match("/[^\.\/]+\.[^\.\/]+$/", $host, $matches);
$domain = $matches[0];
$url = explode($domain, $host);
$subdomain = str_replace('.', '', $url[0]);
echo 'subdomain: '.$subdomain.'<br />';
echo 'domain: '.$domain.'<br />';
I found another solution that worked for me follow this link
https://stackoverflow.com/a/42687397/4559365
It basically overrides the method canScrollHorizontally
to disable swiping by finger. Howsoever setCurrentItem
still works.
The Original Question
Why is one loop so much slower than two loops?
Conclusion:
Case 1 is a classic interpolation problem that happens to be an inefficient one. I also think that this was one of the leading reasons why many machine architectures and developers ended up building and designing multi-core systems with the ability to do multi-threaded applications as well as parallel programming.
Looking at it from this kind of an approach without involving how the hardware, OS, and compiler(s) work together to do heap allocations that involve working with RAM, cache, page files, etc.; the mathematics that is at the foundation of these algorithms shows us which of these two is the better solution.
We can use an analogy of a Boss
being a Summation
that will represent a For Loop
that has to travel between workers A
& B
.
We can easily see that Case 2 is at least half as fast if not a little more than Case 1 due to the difference in the distance that is needed to travel and the time taken between the workers. This math lines up almost virtually and perfectly with both the benchmark times as well as the number of differences in assembly instructions.
I will now begin to explain how all of this works below.
Assessing The Problem
The OP's code:
const int n=100000;
for(int j=0;j<n;j++){
a1[j] += b1[j];
c1[j] += d1[j];
}
And
for(int j=0;j<n;j++){
a1[j] += b1[j];
}
for(int j=0;j<n;j++){
c1[j] += d1[j];
}
The Consideration
Considering the OP's original question about the two variants of the for
loops and his amended question towards the behavior of caches along with many of the other excellent answers and useful comments; I'd like to try and do something different here by taking a different approach about this situation and problem.
The Approach
Considering the two loops and all of the discussion about cache and page filing I'd like to take another approach as to looking at this from a different perspective. One that doesn't involve the cache and page files nor the executions to allocate memory, in fact, this approach doesn't even concern the actual hardware or the software at all.
The Perspective
After looking at the code for a while it became quite apparent what the problem is and what is generating it. Let's break this down into an algorithmic problem and look at it from the perspective of using mathematical notations then apply an analogy to the math problems as well as to the algorithms.
What We Do Know
We know is that this loop will run 100,000 times. We also know that a1
, b1
, c1
& d1
are pointers on a 64-bit architecture. Within C++ on a 32-bit machine, all pointers are 4 bytes and on a 64-bit machine, they are 8 bytes in size since pointers are of a fixed length.
We know that we have 32 bytes in which to allocate for in both cases. The only difference is we are allocating 32 bytes or two sets of 2-8 bytes on each iteration wherein the second case we are allocating 16 bytes for each iteration for both of the independent loops.
Both loops still equal 32 bytes in total allocations. With this information let's now go ahead and show the general math, algorithms, and analogy of these concepts.
We do know the number of times that the same set or group of operations that will have to be performed in both cases. We do know the amount of memory that needs to be allocated in both cases. We can assess that the overall workload of the allocations between both cases will be approximately the same.
What We Don't Know
We do not know how long it will take for each case unless if we set a counter and run a benchmark test. However, the benchmarks were already included from the original question and from some of the answers and comments as well; and we can see a significant difference between the two and this is the whole reasoning for this proposal to this problem.
Let's Investigate
It is already apparent that many have already done this by looking at the heap allocations, benchmark tests, looking at RAM, cache, and page files. Looking at specific data points and specific iteration indices were also included and the various conversations about this specific problem have many people starting to question other related things about it. How do we begin to look at this problem by using mathematical algorithms and applying an analogy to it? We start off by making a couple of assertions! Then we build out our algorithm from there.
Our Assertions:
F1()
, F2()
, f(a)
, f(b)
, f(c)
and f(d)
.The Algorithms:
1st Case: - Only one summation but two independent function calls.
Sum n=1 : [1,100000] = F1(), F2();
F1() = { f(a) = f(a) + f(b); }
F2() = { f(c) = f(c) + f(d); }
2nd Case: - Two summations but each has its own function call.
Sum1 n=1 : [1,100000] = F1();
F1() = { f(a) = f(a) + f(b); }
Sum2 n=1 : [1,100000] = F1();
F1() = { f(c) = f(c) + f(d); }
If you noticed F2()
only exists in Sum
from Case1
where F1()
is contained in Sum
from Case1
and in both Sum1
and Sum2
from Case2
. This will be evident later on when we begin to conclude that there is an optimization that is happening within the second algorithm.
The iterations through the first case Sum
calls f(a)
that will add to its self f(b)
then it calls f(c)
that will do the same but add f(d)
to itself for each 100000
iterations. In the second case, we have Sum1
and Sum2
that both act the same as if they were the same function being called twice in a row.
In this case we can treat Sum1
and Sum2
as just plain old Sum
where Sum
in this case looks like this: Sum n=1 : [1,100000] { f(a) = f(a) + f(b); }
and now this looks like an optimization where we can just consider it to be the same function.
Summary with Analogy
With what we have seen in the second case it almost appears as if there is optimization since both for loops have the same exact signature, but this isn't the real issue. The issue isn't the work that is being done by f(a)
, f(b)
, f(c)
, and f(d)
. In both cases and the comparison between the two, it is the difference in the distance that the Summation has to travel in each case that gives you the difference in execution time.
Think of the for
loops as being the summations that does the iterations as being a Boss
that is giving orders to two people A
& B
and that their jobs are to meat C
& D
respectively and to pick up some package from them and return it. In this analogy, the for loops or summation iterations and condition checks themselves don't actually represent the Boss
. What actually represents the Boss
is not from the actual mathematical algorithms directly but from the actual concept of Scope
and Code Block
within a routine or subroutine, method, function, translation unit, etc. The first algorithm has one scope where the second algorithm has two consecutive scopes.
Within the first case on each call slip, the Boss
goes to A
and gives the order and A
goes off to fetch B's
package then the Boss
goes to C
and gives the orders to do the same and receive the package from D
on each iteration.
Within the second case, the Boss
works directly with A
to go and fetch B's
package until all packages are received. Then the Boss
works with C
to do the same for getting all of D's
packages.
Since we are working with an 8-byte pointer and dealing with heap allocation let's consider the following problem. Let's say that the Boss
is 100 feet from A
and that A
is 500 feet from C
. We don't need to worry about how far the Boss
is initially from C
because of the order of executions. In both cases, the Boss
initially travels from A
first then to B
. This analogy isn't to say that this distance is exact; it is just a useful test case scenario to show the workings of the algorithms.
In many cases when doing heap allocations and working with the cache and page files, these distances between address locations may not vary that much or they can vary significantly depending on the nature of the data types and the array sizes.
The Test Cases:
First Case: On first iteration the Boss
has to initially go 100 feet to give the order slip to A
and A
goes off and does his thing, but then the Boss
has to travel 500 feet to C
to give him his order slip. Then on the next iteration and every other iteration after the Boss
has to go back and forth 500 feet between the two.
Second Case: The Boss
has to travel 100 feet on the first iteration to A
, but after that, he is already there and just waits for A
to get back until all slips are filled. Then the Boss
has to travel 500 feet on the first iteration to C
because C
is 500 feet from A
. Since this Boss( Summation, For Loop )
is being called right after working with A
he then just waits there as he did with A
until all of C's
order slips are done.
The Difference In Distances Traveled
const n = 100000
distTraveledOfFirst = (100 + 500) + ((n-1)*(500 + 500);
// Simplify
distTraveledOfFirst = 600 + (99999*100);
distTraveledOfFirst = 600 + 9999900;
distTraveledOfFirst = 10000500;
// Distance Traveled On First Algorithm = 10,000,500ft
distTraveledOfSecond = 100 + 500 = 600;
// Distance Traveled On Second Algorithm = 600ft;
The Comparison of Arbitrary Values
We can easily see that 600 is far less than 10 million. Now, this isn't exact, because we don't know the actual difference in distance between which address of RAM or from which cache or page file each call on each iteration is going to be due to many other unseen variables. This is just an assessment of the situation to be aware of and looking at it from the worst-case scenario.
From these numbers it would almost appear as if algorithm one should be 99%
slower than algorithm two; however, this is only the Boss's
part or responsibility of the algorithms and it doesn't account for the actual workers A
, B
, C
, & D
and what they have to do on each and every iteration of the Loop. So the boss's job only accounts for about 15 - 40% of the total work being done. The bulk of the work that is done through the workers has a slightly bigger impact towards keeping the ratio of the speed rate differences to about 50-70%
The Observation: - The differences between the two algorithms
In this situation, it is the structure of the process of the work being done. It goes to show that Case 2 is more efficient from both the partial optimization of having a similar function declaration and definition where it is only the variables that differ by name and the distance traveled.
We also see that the total distance traveled in Case 1 is much farther than it is in Case 2 and we can consider this distance traveled our Time Factor between the two algorithms. Case 1 has considerable more work to do than Case 2 does.
This is observable from the evidence of the assembly instructions that were shown in both cases. Along with what was already stated about these cases, this doesn't account for the fact that in Case 1 the boss will have to wait for both A
& C
to get back before he can go back to A
again for each iteration. It also doesn't account for the fact that if A
or B
is taking an extremely long time then both the Boss
and the other worker(s) are idle waiting to be executed.
In Case 2 the only one being idle is the Boss
until the worker gets back. So even this has an impact on the algorithm.
The OP's Amended Question(s)
EDIT: The question turned out to be of no relevance, as the behavior severely depends on the sizes of the arrays (n) and the CPU cache. So if there is further interest, I rephrase the question:
Could you provide some solid insight into the details that lead to the different cache behaviors as illustrated by the five regions on the following graph?
It might also be interesting to point out the differences between CPU/cache architectures, by providing a similar graph for these CPUs.
Regarding These Questions
As I have demonstrated without a doubt, there is an underlying issue even before the Hardware and Software becomes involved.
Now as for the management of memory and caching along with page files, etc. which all work together in an integrated set of systems between the following:
We can already see that there is a bottleneck that is happening within the first algorithm before we even apply it to any machine with any arbitrary architecture, OS, and programmable language compared to the second algorithm. There already existed a problem before involving the intrinsics of a modern computer.
The Ending Results
However; it is not to say that these new questions are not of importance because they themselves are and they do play a role after all. They do impact the procedures and the overall performance and that is evident with the various graphs and assessments from many who have given their answer(s) and or comment(s).
If you paid attention to the analogy of the Boss
and the two workers A
& B
who had to go and retrieve packages from C
& D
respectively and considering the mathematical notations of the two algorithms in question; you can see without the involvement of the computer hardware and software Case 2
is approximately 60%
faster than Case 1
.
When you look at the graphs and charts after these algorithms have been applied to some source code, compiled, optimized, and executed through the OS to perform their operations on a given piece of hardware, you can even see a little more degradation between the differences in these algorithms.
If the Data
set is fairly small it may not seem all that bad of a difference at first. However, since Case 1
is about 60 - 70%
slower than Case 2
we can look at the growth of this function in terms of the differences in time executions:
DeltaTimeDifference approximately = Loop1(time) - Loop2(time)
//where
Loop1(time) = Loop2(time) + (Loop2(time)*[0.6,0.7]) // approximately
// So when we substitute this back into the difference equation we end up with
DeltaTimeDifference approximately = (Loop2(time) + (Loop2(time)*[0.6,0.7])) - Loop2(time)
// And finally we can simplify this to
DeltaTimeDifference approximately = [0.6,0.7]*Loop2(time)
This approximation is the average difference between these two loops both algorithmically and machine operations involving software optimizations and machine instructions.
When the data set grows linearly, so does the difference in time between the two. Algorithm 1 has more fetches than algorithm 2 which is evident when the Boss
has to travel back and forth the maximum distance between A
& C
for every iteration after the first iteration while algorithm 2 the Boss
has to travel to A
once and then after being done with A
he has to travel a maximum distance only one time when going from A
to C
.
Trying to have the Boss
focusing on doing two similar things at once and juggling them back and forth instead of focusing on similar consecutive tasks is going to make him quite angry by the end of the day since he had to travel and work twice as much. Therefore do not lose the scope of the situation by letting your boss getting into an interpolated bottleneck because the boss's spouse and children wouldn't appreciate it.
Amendment: Software Engineering Design Principles
-- The difference between local Stack and heap allocated computations within iterative for loops and the difference between their usages, their efficiencies, and effectiveness --
The mathematical algorithm that I proposed above mainly applies to loops that perform operations on data that is allocated on the heap.
So when you are working with data that needs to be on the heap and you are traversing through them in loops, it is more efficient to keep each data set and its corresponding algorithms within its own single loop. You will get better optimizations compared to trying to factor out consecutive loops by putting multiple operations of different data sets that are on the heap into a single loop.
It is okay to do this with data that is on the stack since they are frequently cached, but not for data that has to have its memory address queried every iteration.
This is where software engineering and software architecture design comes into play. It is the ability to know how to organize your data, knowing when to cache your data, knowing when to allocate your data on the heap, knowing how to design and implement your algorithms, and knowing when and where to call them.
You might have the same algorithm that pertains to the same data set, but you might want one implementation design for its stack variant and another for its heap-allocated variant just because of the above issue that is seen from its O(n)
complexity of the algorithm when working with the heap.
From what I've noticed over the years, many people do not take this fact into consideration. They will tend to design one algorithm that works on a particular data set and they will use it regardless of the data set being locally cached on the stack or if it was allocated on the heap.
If you want true optimization, yes it might seem like code duplication, but to generalize it would be more efficient to have two variants of the same algorithm. One for stack operations, and the other for heap operations that are performed in iterative loops!
Here's a pseudo example: Two simple structs, one algorithm.
struct A {
int data;
A() : data{0}{}
A(int a) : data{a}{}
};
struct B {
int data;
B() : data{0}{}
A(int b) : data{b}{}
}
template<typename T>
void Foo( T& t ) {
// Do something with t
}
// Some looping operation: first stack then heap.
// Stack data:
A dataSetA[10] = {};
B dataSetB[10] = {};
// For stack operations this is okay and efficient
for (int i = 0; i < 10; i++ ) {
Foo(dataSetA[i]);
Foo(dataSetB[i]);
}
// If the above two were on the heap then performing
// the same algorithm to both within the same loop
// will create that bottleneck
A* dataSetA = new [] A();
B* dataSetB = new [] B();
for ( int i = 0; i < 10; i++ ) {
Foo(dataSetA[i]); // dataSetA is on the heap here
Foo(dataSetB[i]); // dataSetB is on the heap here
} // this will be inefficient.
// To improve the efficiency above, put them into separate loops...
for (int i = 0; i < 10; i++ ) {
Foo(dataSetA[i]);
}
for (int i = 0; i < 10; i++ ) {
Foo(dataSetB[i]);
}
// This will be much more efficient than above.
// The code isn't perfect syntax, it's only psuedo code
// to illustrate a point.
This is what I was referring to by having separate implementations for stack variants versus heap variants. The algorithms themselves don't matter too much, it's the looping structures that you will use them in that do.
Since react-native eject is depreciated in 60.3 and I was getting diff errors trying to upgrade form 60.1 to 60.3 regenerating the android folder was not working.
I had to
rm -R node_modules
Then update react-native in package.json to 59.1 (remove package-lock.json)
Run
npm install
react-native eject
This will regenerate your android and ios folders Finally upgrade back to 60.3
react-native upgrade
react-native upgrade while back and 59.1 did not regenerate my android folder so the eject was necessary.
This is not an answer to the question, but I couldn't figure out how to get decent code formatting in a comment above... so auto-down-reputation-be-damned here's my comment.
I have the recipe submtted by @Dobes in a fancy shmancy [alias] entry in my .gitconfig:
# to untrack a local branch when I can't remember 'git config --unset'
cbr = "!f(){ git symbolic-ref -q HEAD 2>/dev/null | sed -e 's|refs/heads/||'; }; f"
bruntrack = "!f(){ br=${1:-`git cbr`}; \
rm=`git config --get branch.$br.remote`; \
tr=`git config --get branch.$br.merge`; \
[ $rm:$tr = : ] && echo \"# untrack: not a tracking branch: $br\" && return 1; \
git config --unset branch.$br.remote; git config --unset branch.$br.merge; \
echo \"# untrack: branch $br no longer tracking $rm:$tr\"; return 0; }; f"
Then I can just run
$ git bruntrack branchname
Annotate type and gender properties with @XmlAttribute
and the description property with @XmlValue
:
package org.example.sport;
import javax.xml.bind.annotation.*;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
public class Sport {
@XmlAttribute
protected String type;
@XmlAttribute
protected String gender;
@XmlValue;
protected String description;
}
For More Information
You can also use map:
a = [1, 1, 1, 1, 1]
b = 1
list(map(lambda x: x + b, a))
It gives:
[2, 2, 2, 2, 2]
You just need to specify which columns you're inserting directly into:
INSERT INTO [dbo].[rLicenses] ([Name]) VALUES ('test')
Views can be picky like that.
These two attributes are commonly confused:
android:gravity
sets the gravity of the content of the View it's
used on. android:layout_gravity
sets the gravity of the View or
Layout relative to its parent.So either put android:gravity="center"
on the parent or android:layout_gravity="center"
on the LinearLayout itself.
I have caught myself a number of times mixing them up and wondering why things weren't centering properly...
I find that I do need the IP in order to configure /etc/hosts
on the host system to point at services on the fresh VM.
Here's a rough version of what I use to fetch the IP. Let Vagrant do its SSH magic and ask the VM for its address; tweak for your needs.
new_ip=$(vagrant ssh -c "ip address show eth0 | grep 'inet ' | sed -e 's/^.*inet //' -e 's/\/.*$//'")
I just found this in the Vagrant Docs. Looks like they consider it a valid approach:
This will automatically assign an IP address from the reserved address space. The IP address can be determined by using vagrant ssh to SSH into the machine and using the appropriate command line tool to find the IP, such as ifconfig.
For people looking to do if statements with multiple 'or' values.
<div ng-if="::(a || b || c || d || e || f)"><div>
As the creator of ElasticSearch, maybe I can give you some reasoning on why I went ahead and created it in the first place :).
Using pure Lucene is challenging. There are many things that you need to take care for if you want it to really perform well, and also, its a library, so no distributed support, it's just an embedded Java library that you need to maintain.
In terms of Lucene usability, way back when (almost 6 years now), I created Compass. Its aim was to simplify using Lucene and make everyday Lucene simpler. What I came across time and time again is the requirement to be able to have Compass distributed. I started to work on it from within Compass, by integrating with data grid solutions like GigaSpaces, Coherence, and Terracotta, but it's not enough.
At its core, a distributed Lucene solution needs to be sharded. Also, with the advancement of HTTP and JSON as ubiquitous APIs, it means that a solution that many different systems with different languages can easily be used.
This is why I went ahead and created ElasticSearch. It has a very advanced distributed model, speaks JSON natively, and exposes many advanced search features, all seamlessly expressed through JSON DSL.
Solr is also a solution for exposing an indexing/search server over HTTP, but I would argue that ElasticSearch provides a much superior distributed model and ease of use (though currently lacking on some of the search features, but not for long, and in any case, the plan is to get all Compass features into ElasticSearch). Of course, I am biased, since I created ElasticSearch, so you might need to check for yourself.
As for Sphinx, I have not used it, so I can't comment. What I can refer you is to this thread at Sphinx forum which I think proves the superior distributed model of ElasticSearch.
Of course, ElasticSearch has many more features than just being distributed. It is actually built with a cloud in mind. You can check the feature list on the site.
I recently ran into this problem again. It's been a while since I last worked with submodules and having learned more about git I realized that simply checking out the branch you want to commit on is sufficient. Git will keep the working tree even if you don't stash it.
git checkout existing_branch_name
If you want to work on a new branch this should work for you:
git checkout -b new_branch_name
The checkout will fail if you have conflicts in the working tree, but that should be quite unusual and if it happens you can just stash it, pop it and resolve the conflict.
Compared to the accepted answer, this answer will save you the execution of two commands, that don't really take that long to execute anyway. Therefore I will not accept this answer, unless it miraculously gets more upvotes (or at least close) than the currently accepted answer.
Something like this worked for me (references columns C and D from the row 8 till the end of the columns, in Excel 2013 if relevant):
=SUMIFS(INDIRECT(ADDRESS(ROW(D$8), COLUMN())&":"&ADDRESS(ROWS($C:$C), COLUMN())),INDIRECT("C$8:C"&ROWS($C:$C)),$C$2)
As noted in other answers, your code is not working primarily because String.replace(...)
does not change the target String
. (It can't - Java strings are immutable!) What replace
actually does is to create and return a new String
object with the characters changed as required. But your code then throws away that String
...
Here are some possible solutions. Which one is most correct depends on what exactly you are trying to do.
// #1
text = text.replace("\n", "");
Simply removes all the newline characters. This does not cope with Windows or Mac line terminations.
// #2
text = text.replace(System.getProperty("line.separator"), "");
Removes all line terminators for the current platform. This does not cope with the case where you are trying to process (for example) a UNIX file on Windows, or vice versa.
// #3
text = text.replaceAll("\\r|\\n", "");
Removes all Windows, UNIX or Mac line terminators. However, if the input file is text, this will concatenate words; e.g.
Goodbye cruel
world.
becomes
Goodbye cruelworld.
So you might actually want to do this:
// #4
text = text.replaceAll("\\r\\n|\\r|\\n", " ");
which replaces each line terminator with a space1. Since Java 8 you can also do this:
// #5
text = text.replaceAll("\\R", " ");
And if you want to replace multiple line terminator with one space:
// #6
text = text.replaceAll("\\R+", " ");
1 - Note there is a subtle difference between #3 and #4. The sequence \r\n
represents a single (Windows) line terminator, so we need to be careful not to replace it with two spaces.
instead of try
ing & catch
ing expressions.. its better to run regex on the string to ensure that it is a valid number..
Using absolute
as position
is not responsive + mobile friendly. I would suggest using a div
with a background-image
and then placing text in the div
will place text over the image. Depending on your html, you might need to use height
with vh
value
The method GetFileNameWithoutExtension
, as the name implies, does not return the extension on the file. In your case, it would only return "a". You want to append your ".Jpeg" to that result. However, at a different level, this seems strange, as image files have different metadata and cannot be converted so easily.
http://www.example.com/some/path/to/resource?param1=value1
The part before the question mark must use % encoding (so %20
for space), after the question mark you can use either %20
or +
for a space. If you need an actual +
after the question mark use %2B
.
ES6 is the way of the future.
arr.reduce((a, b) => Math.min(a, b));
I prefer this form because it's easily generalized for other use cases
create below stored procedure in your db(from which db u want to delete sp's)
then right click on that procedure - click on Execute Stored Procedure..
then click ok.
create Procedure [dbo].[DeleteAllProcedures]
As
declare @schemaName varchar(500)
declare @procName varchar(500)
declare cur cursor
for select s.Name, p.Name from sys.procedures p
INNER JOIN sys.schemas s ON p.schema_id = s.schema_id
WHERE p.type = 'P' and is_ms_shipped = 0 and p.name not like 'sp[_]%diagram%'
ORDER BY s.Name, p.Name
open cur
fetch next from cur into @schemaName,@procName
while @@fetch_status = 0
begin
if @procName <> 'DeleteAllProcedures'
exec('drop procedure ' + @schemaName + '.' + @procName)
fetch next from cur into @schemaName,@procName
end
close cur
deallocate cur
Sometimes it's better to think like a parser, like T-SQL parser. While executing the statement, parser does not have any value in Pivot section and you can't have any check expression in that section. By the way, you can simply use this:
SELECT CLASS
, IsNull([AZ], 0)
, IsNull([CA], 0)
, IsNull([TX], 0)
FROM #TEMP
PIVOT (
SUM(DATA)
FOR STATE IN (
[AZ]
, [CA]
, [TX]
)
) AS PVT
ORDER BY CLASS
This will convert it to an int:
char foo = '2';
int bar = foo - '0';
This works because each character is internally represented by a number. The characters '0' to '9' are represented by consecutive numbers, so finding the difference between the characters '0' and '2' results in the number 2.
Here are oneliners:
$(basename "${s%.*}")
$(basename "${s}" ".${s##*.}")
I needed this, the same as asked by bongbang and w4etwetewtwet.
I have this code that allow me to convert from HOST_ENDIAN_ORDER (whatever it is) to LITTLE_ENDIAN_ORDER or BIG_ENDIAN_ORDER. I use a template, so if I try to convert from HOST_ENDIAN_ORDER to LITTLE_ENDIAN_ORDER and they happen to be the same for the machine for wich I compile, no code will be generated.
Here is the code with some comments:
// We define some constant for little, big and host endianess. Here I use
// BOOST_LITTLE_ENDIAN/BOOST_BIG_ENDIAN to check the host indianess. If you
// don't want to use boost you will have to modify this part a bit.
enum EEndian
{
LITTLE_ENDIAN_ORDER,
BIG_ENDIAN_ORDER,
#if defined(BOOST_LITTLE_ENDIAN)
HOST_ENDIAN_ORDER = LITTLE_ENDIAN_ORDER
#elif defined(BOOST_BIG_ENDIAN)
HOST_ENDIAN_ORDER = BIG_ENDIAN_ORDER
#else
#error "Impossible de determiner l'indianness du systeme cible."
#endif
};
// this function swap the bytes of values given it's size as a template
// parameter (could sizeof be used?).
template <class T, unsigned int size>
inline T SwapBytes(T value)
{
union
{
T value;
char bytes[size];
} in, out;
in.value = value;
for (unsigned int i = 0; i < size / 2; ++i)
{
out.bytes[i] = in.bytes[size - 1 - i];
out.bytes[size - 1 - i] = in.bytes[i];
}
return out.value;
}
// Here is the function you will use. Again there is two compile-time assertion
// that use the boost librarie. You could probably comment them out, but if you
// do be cautious not to use this function for anything else than integers
// types. This function need to be calles like this :
//
// int x = someValue;
// int i = EndianSwapBytes<HOST_ENDIAN_ORDER, BIG_ENDIAN_ORDER>(x);
//
template<EEndian from, EEndian to, class T>
inline T EndianSwapBytes(T value)
{
// A : La donnée à swapper à une taille de 2, 4 ou 8 octets
BOOST_STATIC_ASSERT(sizeof(T) == 2 || sizeof(T) == 4 || sizeof(T) == 8);
// A : La donnée à swapper est d'un type arithmetic
BOOST_STATIC_ASSERT(boost::is_arithmetic<T>::value);
// Si from et to sont du même type on ne swap pas.
if (from == to)
return value;
return SwapBytes<T, sizeof(T)>(value);
}
I don't really understand the full scope of your question, but if all you need is a hash of the string, then it's very easy to get that.
Just use the GetHashCode method.
Like this:
string hash = username.GetHashCode();
This didn't work,
android:background="@android:color/transparent"
Setting the webview
background color as worked
webView.setBackgroundColor(0)
Additionally, I set window background drawable as transparent
ES6 one liner for the solution from mustache.js
const escapeHTML = str => (str+'').replace(/[&<>"'`=\/]/g, s => ({'&': '&','<': '<','>': '>','"': '"',"'": ''','/': '/','`': '`','=': '='})[s]);
I already found the solution to this problem which I forgot to post here.
@RunWith(PowerMockRunner.class)
@PrepareForTest({ Test.class })
public class SampleTest {
@Mock
Person person;
@Test
public void testPrintName() throws Exception {
PowerMockito.whenNew(Person.class).withNoArguments().thenReturn(person);
Test test= new Test();
test.testMethod();
}
}
Key points to this solution are:
Running my test cases with PowerMockRunner: @RunWith(PowerMockRunner.class)
Instruct Powermock to prepare Test.class
for manipulation of private fields: @PrepareForTest({ Test.class })
And finally mock the constructor for Person class:
PowerMockito.mockStatic(Person.class);
PowerMockito.whenNew(Person.class).withNoArguments().thenReturn(person);
Here is a really elegant solution from Chris Thielen ui-router-extras: $previousState
var previous = $previousState.get(); //Gets a reference to the previous state.
previous
is an object that looks like: { state: fromState, params: fromParams }
where fromState is the previous state and fromParams is
the previous state parameters.
One set of familiar operations that you can do in MapReduce is the set of normal SQL operations: SELECT, SELECT WHERE, GROUP BY, ect.
Another good example is matrix multiply, where you pass one row of M and the entire vector x and compute one element of M * x.
Change
private ArrayList finishingOrder;
//Make an ArrayList to hold RaceCar objects to determine winners
finishingOrder = Collections.synchronizedCollection(new ArrayList(numberOfRaceCars)
to
private List finishingOrder;
//Make an ArrayList to hold RaceCar objects to determine winners
finishingOrder = Collections.synchronizedList(new ArrayList(numberOfRaceCars)
List is a supertype of ArrayList so you need to specify that.
Otherwise, what you're doing seems fine. Other option is you can use Vector, which is synchronized, but this is probably what I would do.
public class Test extends AppCompatActivity {
EditText firstEditText;
EditText secondEditText;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
firstEditText = (EditText)findViewById(R.id.firstEditText);
secondEditText = (EditText)findViewById(R.id.secondEditText);
firstEditText.addTextChangedListener(new EditTextListener());
}
private class EditTextListener implements TextWatcher {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
secondEditText.setText(firstEditText.getText());
}
@Override
public void afterTextChanged(Editable s) {
}
}
}
There is an api in Express.
res.sendFile
app.get('/report/:chart_id/:user_id', function (req, res) {
// res.sendFile(filepath);
});
Observe that errorLogger is a wrapper around logger.trace. But the level of logger is ERROR so logger.trace will not log its message to logger's appenders.
The fix is to change logger.trace to logger.error in the body of errorLogger.
I'm assume you cannot get css working for your button using anchor tag. So you need to override the css styles which are being overwritten by other elements using !important
property.
HTML
<a href="#" class="selected_btn" data-role="button">Button name</a>
CSS
.selected_btn
{
border:1px solid red;
text-decoration:none;
font-family:helvetica;
color:red !important;
background:url('http://www.lessardstephens.com/layout/images/slideshow_big.png') repeat-x;
}
Here is the demo
If you are using skaffold, use 'context:' to specify context location for each image dockerfile - context: ../../../
apiVersion: skaffold/v2beta4
kind: Config
metadata:
name: frontend
build:
artifacts:
- image: nginx-angular-ui
context: ../../../
sync:
# A local build will update dist and sync it to the container
manual:
- src: './dist/apps'
dest: '/usr/share/nginx/html'
docker:
dockerfile: ./tools/pipelines/dockerfile/nginx.dev.dockerfile
- image: webapi/image
context: ../../../../api/
docker:
dockerfile: ./dockerfile
deploy:
kubectl:
manifests:
- ./.k8s/*.yml
skaffold run -f ./skaffold.yaml
Refreshing current webview's URL is not a common usage.
I used this in such a scenario: When user goes to another activity and user come back to webview's activity I reload current URL like this:
public class MyWebviewActivity extends Activity {
WebView mWebView;
....
....
....
@Override
public void onRestart() {
String url = mWebView.getUrl();
String postData = MyUtility.getOptionsDataForPOSTURL(mContext);
mWebView.postUrl(url, EncodingUtils.getBytes(postData, "BASE64"));
}
}
You can also use WebView's reload()
function. But note that if you loaded the webview with postUrl()
, then mWebView.reload();
doesn't work. This also works
String webUrl = webView.getUrl();
mWebView.loadUrl(webUrl);
I didn't want to introduce an asset catalog.
Per the answer from seahorseseaeo here, adding the following to info.plist worked for me. (I edited it as a "source code".) I then named the images [email protected] and [email protected]
<key>UILaunchImages</key>
<array>
<dict>
<key>UILaunchImageMinimumOSVersion</key>
<string>8.0</string>
<key>UILaunchImageName</key>
<string>Default-667h</string>
<key>UILaunchImageOrientation</key>
<string>Portrait</string>
<key>UILaunchImageSize</key>
<string>{375, 667}</string>
</dict>
<dict>
<key>UILaunchImageMinimumOSVersion</key>
<string>8.0</string>
<key>UILaunchImageName</key>
<string>Default-736h</string>
<key>UILaunchImageOrientation</key>
<string>Portrait</string>
<key>UILaunchImageSize</key>
<string>{414, 736}</string>
</dict>
</array>
Look up the specification of HTTP. Or to get started, try http://www.jmarshall.com/easy/http/
<?php
$dbname = 'mysql_dbname';
if (!mysql_connect('mysql_host', 'mysql_user', 'mysql_password')) {
echo 'Could not connect to mysql';
exit;
}
$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);
if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
while ($row = mysql_fetch_row($result)) {
echo "Table: {$row[0]}\n";
}
mysql_free_result($result);
?>
//Try This code is running perfectly !!!!!!!!!!
To make it easier add a custom function and call it when ever you want that changing the value also trigger change
$.fn.valAndTrigger = function (element) {
return $(this).val(element).trigger('change');
}
and
$("#sample").valAndTirgger("NewValue");
Or you can override the val function to always call the change when the val is called
(function ($) {
var originalVal = $.fn.val;
$.fn.val = function (value) {
this.trigger("change");
return originalVal.call(this, value);
};
})(jQuery);
Sample at http://jsfiddle.net/r60bfkub/
Do not use classpath. This may cause problems with different ClassLoaders (container vs. application). WEB-INF is always the better choice.
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-config.xml</param-value>
</context-param>
and
<bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>/WEB-INF/social.properties</value>
</property>
</bean>
I think you can't call
androidHttpTransport.call(SOAP_ACTION, envelope);
on main Thread.
Network operations should be done on different Thread.
Create another Thread or AsyncTask to call the method.
It seems that there is a typo, since 1104*1104*50=60940800
and you are trying to reshape to dimensions 50,1104,104
. So it seems that you need to change 104 to 1104.
This will convert char array back to string:
char[] charArray = {'a', 'b', 'c'};
String str = String.valueOf(charArray);
I had something similar when passing a script to a function with invoke-command. I ran the command in single quotes instead of double quotes, because it then becomes a string literal. 'Set-Mailbox $sourceUser -LitigationHoldEnabled $false -ElcProcessingDisabled $true';
If you don't want to use NPOI.Mapper, then I'd advise you to check out this solution - it handles reading excel cell into various type and also has a simple import helper: https://github.com/hidegh/NPOI.Extensions
var data = sheet.MapTo<OrderDetails>(true, rowMapper =>
{
// map singleItem
return new OrderDetails()
{
Date = rowMapper.GetValue<DateTime>(SheetColumnTitles.Date),
// use reusable mapper for re-curring scenarios
Region = regionMapper(rowMapper.GetValue<string>(SheetColumnTitles.Region)),
Representative = rowMapper.GetValue<string>(SheetColumnTitles.Representative),
Item = rowMapper.GetValue<string>(SheetColumnTitles.Item),
Units = rowMapper.GetValue<int>(SheetColumnTitles.Units),
UnitCost = rowMapper.GetValue<decimal>(SheetColumnTitles.UnitCost),
Total = rowMapper.GetValue<decimal>(SheetColumnTitles.Total),
// read date and total as string, as they're displayed/formatted on the excel
DateFormatted = rowMapper.GetValue<string>(SheetColumnTitles.Date),
TotalFormatted = rowMapper.GetValue<string>(SheetColumnTitles.Total)
};
});
What you mean is either
SELECT DISTINCT a, b FROM pairs;
or
SELECT a, b FROM pairs GROUP BY a, b;
In case of a large file you can use pandas.read_csv
with the chunksize
argument which allows to read the dataset per chunk:
import pandas as pd
INPUT_CSV = "input.csv"
OUTPUT_CSV = "output.csv"
CHUNKSIZE = 1_000 # Maximum number of rows in memory
header = True
mode = "w"
for chunk_df in pd.read_csv(INPUT_CSV, chunksize=CHUNKSIZE):
chunk_df["Berry"] = chunk_df["Name"]
# You apply any other transformation to the chunk
# ...
chunk_df.to_csv(OUTPUT_CSV, header=header, mode=mode)
header = False # Do not save the header for the other chunks
mode = "a" # 'a' stands for append mode, all the other chunks will be appended
If you want to update the file inplace, you can use a temporary file and erase it at the end
import pandas as pd
INPUT_CSV = "input.csv"
TMP_CSV = "tmp.csv"
CHUNKSIZE = 1_000 # Maximum number of rows in memory
header = True
mode = "w"
for chunk_df in pd.read_csv(INPUT_CSV, chunksize=CHUNKSIZE):
chunk_df["Berry"] = chunk_df["Name"]
# You apply any other transformation to the chunk
# ...
chunk_df.to_csv(TMP_CSV, header=header, mode=mode)
header = False # Do not save the header for the other chunks
mode = "a" # 'a' stands for append mode, all the other chunks will be appended
os.replace(TMP_CSV, INPUT_CSV)
Consider the limitations of the different Load*
methods. From the MSDN docs...
LoadFile does not load files into the LoadFrom context, and does not resolve dependencies using the load path, as the LoadFrom method does.
More information on Load Contexts can be found in the LoadFrom
docs.
I believe the more modern and simpler way to do this now is hg uncommit
. Note this leaves behind an empty commit which can be useful if you want to reuse the commit message later. If you don't, use hg uncommit --no-keep
to not leave the empty commit.
hg uncommit [OPTION]... [FILE]...
uncommit part or all of a local changeset
This command undoes the effect of a local commit, returning the affected files to their uncommitted state. This means that files modified or deleted in the changeset will be left unchanged, and so will remain modified in the working directory. If no files are specified, the commit will be left empty, unless --no-keep
Sorry, I am not sure what the equivalent is TortoiseHg.
After losing hours trying to find my error, the problem is your formula:
sigma = sum(y*(x-mean)**2)/n
This previous formula is wrong, the correct formula is the square root of this!;
sqrt(sum(y*(x-mean)**2)/n)
Hope this helps
Put this code somewhere in your C++ project:
#ifdef _DEBUG
TCHAR version[50];
sprintf(&version[0], "Version = %d", _MSC_VER);
MessageBox(NULL, (LPCTSTR)szMsg, "Visual Studio", MB_OK | MB_ICONINFORMATION);
#endif
Note that _MSC_VER
symbol is Microsoft specific. Here you can find a list of Visual Studio versions with the value for _MSC_VER
for each version.
Take a look at Job Control on UNIX systems
If you don't have control of your shell, simply hitting ctrl + C should stop the process. If that doesn't work, you can try ctrl + Z and using the jobs
and kill -9 %<job #>
to kill it. The '-9' is a type of signal. You can man kill
to see a list of signals.
I got exactly the same error message and in my case it turned out i didn't list the controller JS file (e.g. first-ctrl.js) in my index.html
If you are trying to keep a list
of list
s (similar to python
's list.append()
) then this might work:
a <- list(1,2,3)
b <- list(4,5,6)
c <- append(list(a), list(b))
> c
[[1]]
[[1]][[1]]
[1] 1
[[1]][[2]]
[1] 2
[[1]][[3]]
[1] 3
[[2]]
[[2]][[1]]
[1] 4
[[2]][[2]]
[1] 5
[[2]][[3]]
[1] 6
For posterity: you can also use classes to achieve something similar. For instance:
class Function_Wrapper():
def __init__(self, x, y, z):
self.x, self.y, self.z = x, y, z
def func(self):
return self.x + self.y + self.z # execute function
Button can then be simply created by:
instance1 = Function_Wrapper(x, y, z)
button1 = Button(master, text = "press", command = instance1.func)
This approach also allows you to change the function arguments by i.e. setting instance1.x = 3
.
Please note that if you made changes to textarea, after it had rendered; You will get the updated value instead of the initialized value.
<!doctype html>
<html lang="en">
<head>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
$(function () {
$('#btnShow').click(function () {
alert('text:' + $('#addressFieldName').text() + '\n value:' + $('#addressFieldName').val());
});
});
function updateAddress() {
$('#addressFieldName').val('District: Peshawar \n');
}
</script>
</head>
<body>
<?php
$address = "School: GCMHSS NO.1\nTehsil: ,\nDistrict: Haripur";
?>
<textarea id="addressFieldName" rows="4" cols="40" tabindex="5" ><?php echo $address; ?></textarea>
<?php echo '<script type="text/javascript">updateAddress();</script>'; ?>
<input type="button" id="btnShow" value='show' />
</body>
</html>
As you can see the value of textarea will be different than the text in between the opening and closing tag of concern textarea.
Arrays.asList
does not return instance of java.util.ArrayList
but it returns instance of java.util.Arrays.ArrayList
.
You will need to convert to ArrayList if you want to access ArrayList
specific information
allWords.addAll(Arrays.asList(strTemp.toLowerCase().split("\\s+")));
For Debian Jessie (which is the current default for the PHP image on Docker Hub):
apt-get install --yes zip unzip php-pclzip
You can omit the --yes, but it's useful when you're RUN-ing it in a Dockerfile.
You're not passing any credentials to sqlcmd.exe
So it's trying to authenticate you using the Windows Login credentials, but you mustn't have your SQL Server setup to accept those credentials...
When you were installing it, you would have had to supply a Server Admin password (for the sa
account)
Try...
sqlcmd.exe -U sa -P YOUR_PASSWORD -S ".\SQL2008"
for reference, theres more details here...
select * from tableName where columnName is null
Alternatively, you can use jinfo
jinfo -flags <vmid>
jinfo -sysprops <vmid>
You probably mean heap memory, not memory heap.
Heap memory is essentially a large pool of memory (typically per process) from which the running program can request chunks. This is typically called dynamic allocation.
It is different from the Stack, where "automatic variables" are allocated. So, for example, when you define in a C function a pointer variable, enough space to hold a memory address is allocated on the stack. However, you will often need to dynamically allocate space (With malloc) on the heap and then provide the address where this memory chunk starts to the pointer.
Rather than use multiple classes or class inheritance, perhaps a single Toy class that knows what "kind" it is:
class Toy:
num = 0
def __init__(self, name, kind, *args):
self.name = name
self.kind = kind
self.data = args
self.num = Toy.num
Toy.num += 1
def __repr__(self):
return ' '.join([self.name,self.kind,str(self.num)])
def playWith(self):
print self
def getNewToy(name, kind):
return Toy(name, kind)
t1 = Toy('Suzie', 'doll')
t2 = getNewToy('Jack', 'robot')
print t1
t2.playWith()
Running it:
$ python toy.py
Suzie doll 0
Jack robot 1
As you can see, getNewToy
is really unnecessary. Now you can modify playWith
to check the value of self.kind
and change behavior, you can redefine playWith
to designate a playmate:
def playWith(self, who=None):
if who: pass
print self
t1.playWith(t2)
This autofits all columns according to their content, fills the remaining empty space by stretching a specified column and prevents the 'jumping' behaviour by setting the last column to fill for any future resizing.
// autosize all columns according to their content
dgv.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
// make column 1 (or whatever) fill the empty space
dgv.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
// remove column 1 autosizing to prevent 'jumping' behaviour
dgv.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
// let the last column fill the empty space when the grid or any column is resized (more natural/expected behaviour)
dgv.Columns.GetLastColumn(DataGridViewElementStates.None, DataGridViewElementStates.None).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
You should also consider the security implications of running a process as an administrator level user or as Service. If any input is not being validated properly, such as if it is listening on a network interface. If the parser for this input doesn't validate properly, it can be abused, and possibly lead to an exploit that could run code as the elevated user. in abatishchev's example it shouldn't be much of a problem, but if it were to be deployed in an enterprise environment, do a security assessment prior to wide scale deployment.
As Ciro San descended Mount Fire Fox after deep meditation, his mind was clear and peaceful.
His hand however, was restless, and by itself grabbed a brush and jotted down the following notes.
0) Two different things can be called "prototype":
the prototype property, as in obj.prototype
the prototype internal property, denoted as [[Prototype]]
in ES5.
It can be retrieved via the ES5 Object.getPrototypeOf()
.
Firefox makes it accessible through the __proto__
property as an extension. ES6 now mentions some optional requirements for __proto__
.
1) Those concepts exist to answer the question:
When I do
obj.property
, where does JS look for.property
?
Intuitively, classical inheritance should affect property lookup.
2)
__proto__
is used for the dot .
property lookup as in obj.property
. .prototype
is not used for lookup directly, only indirectly as it determines __proto__
at object creation with new
.Lookup order is:
obj
properties added with obj.p = ...
or Object.defineProperty(obj, ...)
obj.__proto__
obj.__proto__.__proto__
, and so on__proto__
is null
, return undefined
.This is the so-called prototype chain.
You can avoid .
lookup with obj.hasOwnProperty('key')
and Object.getOwnPropertyNames(f)
3) There are two main ways to set obj.__proto__
:
new
:
var F = function() {}
var f = new F()
then new
has set:
f.__proto__ === F.prototype
This is where .prototype
gets used.
Object.create
:
f = Object.create(proto)
sets:
f.__proto__ === proto
4) The code:
var F = function(i) { this.i = i }
var f = new F(1)
Corresponds to the following diagram (some Number
stuff is omitted):
(Function) ( F ) (f)----->(1)
| ^ | | ^ | i |
| | | | | | |
| | | | +-------------------------+ | |
| |constructor | | | | |
| | | +--------------+ | | |
| | | | | | |
| | | | | | |
|[[Prototype]] |[[Prototype]] |prototype |constructor |[[Prototype]]
| | | | | | |
| | | | | | |
| | | | +----------+ | |
| | | | | | |
| | | | | +-----------------------+ |
| | | | | | |
v | v v | v |
(Function.prototype) (F.prototype) |
| | |
| | |
|[[Prototype]] |[[Prototype]] [[Prototype]]|
| | |
| | |
| +-------------------------------+ |
| | |
v v v
(Object.prototype) (Number.prototype)
| | ^
| | |
| | +---------------------------+
| | |
| +--------------+ |
| | |
| | |
|[[Prototype]] |constructor |prototype
| | |
| | |
| | -------------+
| | |
v v |
(null) (Object)
This diagram shows many language predefined object nodes:
null
Object
Object.prototype
Function
Function.prototype
1
Number.prototype
(can be found with (1).__proto__
, parenthesis mandatory to satisfy syntax)Our 2 lines of code only created the following new objects:
f
F
F.prototype
i
is now a property of f
because when you do:
var f = new F(1)
it evaluates F
with this
being the value that new
will return, which then gets assigned to f
.
5) .constructor
normally comes from F.prototype
through the .
lookup:
f.constructor === F
!f.hasOwnProperty('constructor')
Object.getPrototypeOf(f) === F.prototype
F.prototype.hasOwnProperty('constructor')
F.prototype.constructor === f.constructor
When we write f.constructor
, JavaScript does the .
lookup as:
f
does not have .constructor
f.__proto__ === F.prototype
has .constructor === F
, so take itThe result f.constructor == F
is intuitively correct, since F
is used to construct f
, e.g. set fields, much like in classic OOP languages.
6) Classical inheritance syntax can be achieved by manipulating prototypes chains.
ES6 adds the class
and extends
keywords, which are mostly syntax sugar for previously possible prototype manipulation madness.
class C {
constructor(i) {
this.i = i
}
inc() {
return this.i + 1
}
}
class D extends C {
constructor(i) {
super(i)
}
inc2() {
return this.i + 2
}
}
// Inheritance syntax works as expected.
c = new C(1)
c.inc() === 2
(new D(1)).inc() === 2
(new D(1)).inc2() === 3
// "Classes" are just function objects.
C.constructor === Function
C.__proto__ === Function.prototype
D.constructor === Function
// D is a function "indirectly" through the chain.
D.__proto__ === C
D.__proto__.__proto__ === Function.prototype
// "extends" sets up the prototype chain so that base class
// lookups will work as expected
var d = new D(1)
d.__proto__ === D.prototype
D.prototype.__proto__ === C.prototype
// This is what `d.inc` actually does.
d.__proto__.__proto__.inc === C.prototype.inc
// Class variables
// No ES6 syntax sugar apparently:
// http://stackoverflow.com/questions/22528967/es6-class-variable-alternatives
C.c = 1
C.c === 1
// Because `D.__proto__ === C`.
D.c === 1
// Nothing makes this work.
d.c === undefined
Simplified diagram without all predefined objects:
(c)----->(1)
| i
|
|
|[[Prototype]]
|
|
v __proto__
(C)<--------------(D) (d)
| | | |
| | | |
| |prototype |prototype |[[Prototype]]
| | | |
| | | |
| | | +---------+
| | | |
| | | |
| | v v
|[[Prototype]] (D.prototype)--------> (inc2 function object)
| | | inc2
| | |
| | |[[Prototype]]
| | |
| | |
| | +--------------+
| | |
| | |
| v v
| (C.prototype)------->(inc function object)
| inc
v
Function.prototype
Let's take a moment to study how the following works:
c = new C(1)
c.inc() === 2
The first line sets c.i
to 1
as explained in "4)".
On the second line, when we do:
c.inc()
.inc
is found through the [[Prototype]]
chain: c
-> C
-> C.prototype
-> inc
X.Y()
, JavaScript automatically sets this
to equal X
inside the Y()
function call! The exact same logic also explains d.inc
and d.inc2
.
This article https://javascript.info/class#not-just-a-syntax-sugar mentions further effects of class
worth knowing. Some of them may not be achievable without the class
keyword (TODO check which):
[[FunctionKind]]:"classConstructor"
, which forces the constructor to be called with new: What is the reason ES6 class constructors can't be called as normal functions?Object.defineProperty
.use strict
. Can be done with an explicit use strict
for every function, which is admittedly tedious.There was a really nice post on the Spring Blog from Keith Donald detailing howto Obtain Spring 3 Aritfacts with Maven, with comments detailing when you'd need each of the dependencies...
<!-- Shared version number properties -->
<properties>
<org.springframework.version>3.0.0.RELEASE</org.springframework.version>
</properties>
<!-- Core utilities used by other modules.
Define this if you use Spring Utility APIs
(org.springframework.core.*/org.springframework.util.*)-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Expression Language (depends on spring-core)
Define this if you use Spring Expression APIs
(org.springframework.expression.*)-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Bean Factory and JavaBeans utilities (depends on spring-core)
Define this if you use Spring Bean APIs
(org.springframework.beans.*)-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Aspect Oriented Programming (AOP) Framework
(depends on spring-core, spring-beans)
Define this if you use Spring AOP APIs
(org.springframework.aop.*)-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Application Context
(depends on spring-core, spring-expression, spring-aop, spring-beans)
This is the central artifact for Spring's Dependency Injection Container
and is generally always defined-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Various Application Context utilities, including EhCache, JavaMail, Quartz,
and Freemarker integration
Define this if you need any of these integrations-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Transaction Management Abstraction
(depends on spring-core, spring-beans, spring-aop, spring-context)
Define this if you use Spring Transactions or DAO Exception Hierarchy
(org.springframework.transaction.*/org.springframework.dao.*)-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- JDBC Data Access Library
(depends on spring-core, spring-beans, spring-context, spring-tx)
Define this if you use Spring's JdbcTemplate API
(org.springframework.jdbc.*)-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Object-to-Relation-Mapping (ORM) integration with Hibernate, JPA and iBatis.
(depends on spring-core, spring-beans, spring-context, spring-tx)
Define this if you need ORM (org.springframework.orm.*)-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Object-to-XML Mapping (OXM) abstraction and integration with JAXB, JiBX,
Castor, XStream, and XML Beans.
(depends on spring-core, spring-beans, spring-context)
Define this if you need OXM (org.springframework.oxm.*)-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Web application development utilities applicable to both Servlet and
Portlet Environments
(depends on spring-core, spring-beans, spring-context)
Define this if you use Spring MVC, or wish to use Struts, JSF, or another
web framework with Spring (org.springframework.web.*)-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Spring MVC for Servlet Environments
(depends on spring-core, spring-beans, spring-context, spring-web)
Define this if you use Spring MVC with a Servlet Container such as
Apache Tomcat (org.springframework.web.servlet.*)-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Spring MVC for Portlet Environments
(depends on spring-core, spring-beans, spring-context, spring-web)
Define this if you use Spring MVC with a Portlet Container
(org.springframework.web.portlet.*)-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc-portlet</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Support for testing Spring applications with tools such as JUnit and TestNG
This artifact is generally always defined with a 'test' scope for the
integration testing framework and unit testing stubs-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${org.springframework.version}</version>
<scope>test</scope>
</dependency>
I don't want to sound too negative, but there are occasions when what you want is almost impossible without a lot of "artificial" tuning of page breaks.
If the callout falls naturally near the bottom of a page, and the figure falls on the following page, moving the figure back one page will probably displace the callout forward.
I would recommend (as far as possible, and depending on the exact size of the figures):
In my experience, this is a big eater-up of non-available time (:-)
In reply to Jon's comment, I think this is an inherently difficult problem, because the LaTeX guys are no slouches. You may like to read Frank Mittelbach's paper.
Here is my code. The idea is that ImageView gets color filter when user touches it, and color filter is removed when user stops touching it.
Martin Booka Weser, András, Ah Lam, altosh, solution doesn't work when ImageView has also onClickEvent. worawee.s and kcoppock (with ImageButton) solution requires background, which has no sense when ImageView is not transparent.
This one is extension of AZ_ idea about color filter.
class PressedEffectStateListDrawable extends StateListDrawable {
private int selectionColor;
public PressedEffectStateListDrawable(Drawable drawable, int selectionColor) {
super();
this.selectionColor = selectionColor;
addState(new int[] { android.R.attr.state_pressed }, drawable);
addState(new int[] {}, drawable);
}
@Override
protected boolean onStateChange(int[] states) {
boolean isStatePressedInArray = false;
for (int state : states) {
if (state == android.R.attr.state_pressed) {
isStatePressedInArray = true;
}
}
if (isStatePressedInArray) {
super.setColorFilter(selectionColor, PorterDuff.Mode.MULTIPLY);
} else {
super.clearColorFilter();
}
return super.onStateChange(states);
}
@Override
public boolean isStateful() {
return true;
}
}
usage:
Drawable drawable = new FastBitmapDrawable(bm);
imageView.setImageDrawable(new PressedEffectStateListDrawable(drawable, 0xFF33b5e5));
You could always use "%p" in order to display 8 bit hex numbers.
int main (void)
{
uint8_t a;
uint32_t b;
a=15;
b=a<<28;
printf("%p", b);
return 0;
}
Output:
0xf0000000
$string = <p>Awesome</p><b> Website</b><i> by Narayan</i>. Thanks for visiting enter code here;
$tags = array("p", "i");
echo preg_replace('#<(' . implode( '|', $tags) . ')(?:[^>]+)?>.*?</\1>#s', '', $string);
Try this
If you are using moment.js in your application.
var x= moment(new Date()).format('DD/MM/YYYY hh:mm:ss')
Pass x
to codebehind function and accept it as a string parameter. Use the DateTime.ParseExact()
in c# to convert this string to DateTime as follows,
DateTime.ParseExact(YourString, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
I had a similar issue with the latest Git sources (2.12.2) built along with the latest sources of all its dependencies (Zlib, Bzip, cURL, PCRE, ReadLine, IDN2, iConv, Unistring, etc).
It turns out libreadline
was giving GnuPG problems:
$ gpg --version
gpg: symbol lookup error: /usr/local/lib/libreadline.so.7: undefined symbol: UP
And of course, trying to get useful information from Git with -vvv
failed, so the failure was a mystery.
To resolve the PGP failure due to ReadLine, follow the instructions at Can't update or use package manager -- gpg error:
In terminal:
ls /usr/local/lib
there was a bunch of readline libs in there (libreadline.so.BLAH-BLAH) so i:
su mkdir temp mv /usr/local/lib/libreadline* temp ldconfig
I guess it is possible. You just need to install a SSH server in each container and expose a port on the host. The main annoyance would be maintaining/remembering the mapping of port to container.
However, I have to question why you'd want to do this. SSH'ng into containers should be rare enough that it's not a hassle to ssh to the host then use docker exec to get into the container.
Odeds answer is almost complete. Just one thing to add.
having this password="'; this sould be a valid connection string:
connectionString='Server=dbsrv;User ID=myDbUser;Password='"&&;'
Eclipse Toolbar > Windows > Preferences > General (Right side) > Editors (Right side) > Text Editors (Right side) > Annotations (Right side)
For Occurrences and Write Occurrences, make sure you DO have the 'Text as highlighted' option checked for all of them. See screenshot below:
Make sure that there is Grading-aware Make in Run/Debugging configurations >> before launch section :
I found this suggestion useful in my case:
def product_params
params.require(:product).permit(:name).tap do |whitelisted|
whitelisted[:data] = params[:product][:data]
end
end
Check this link of Xavier's comment on github.
This approach whitelists the entire params[:measurement][:groundtruth] object.
Using the original questions attributes:
def product_params
params.require(:measurement).permit(:name, :groundtruth).tap do |whitelisted|
whitelisted[:groundtruth] = params[:measurement][:groundtruth]
end
end
I can't imagine everyone uses all 20 different keypresses to navigate text, 10 or so keys to start adding text, and 18 ways to visually select an inner block. Or do you!?
I do.
In theory, once I have that and start becoming as proficient in VIM as I am in Textmate, then I can start learning the thousands of other VIM commands that will make me more efficient.
That's the right way to do it. Start with basic commands and then pick up ones that improve your productivity. I like following this blog for tips on how to improve my productivity with vim.
Opening the file in binary mode "wb" will not work in Python 3+. Or rather, you'd have to convert your data to binary before writing it. That's just a hassle.
Instead, you should keep it in text mode, but override the newline as empty. Like so:
with open('/pythonwork/thefile_subset11.csv', 'w', newline='') as outfile:
There are basically two major pitfalls people stumble in with floating-point numbers.
The problem of scale. Each FP number has an exponent which determines the overall “scale” of the number so you can represent either really small values or really larges ones, though the number of digits you can devote for that is limited. Adding two numbers of different scale will sometimes result in the smaller one being “eaten” since there is no way to fit it into the larger scale.
PS> $a = 1; $b = 0.0000000000000000000000001
PS> Write-Host a=$a b=$b
a=1 b=1E-25
PS> $a + $b
1
As an analogy for this case you could picture a large swimming pool and a teaspoon of water. Both are of very different sizes, but individually you can easily grasp how much they roughly are. Pouring the teaspoon into the swimming pool, however, will leave you still with roughly a swimming pool full of water.
(If the people learning this have trouble with exponential notation, one can also use the values 1
and 100000000000000000000
or so.)
Then there is the problem of binary vs. decimal representation. A number like 0.1
can't be represented exactly with a limited amount of binary digits. Some languages mask this, though:
PS> "{0:N50}" -f 0.1
0.10000000000000000000000000000000000000000000000000
But you can “amplify” the representation error by repeatedly adding the numbers together:
PS> $sum = 0; for ($i = 0; $i -lt 100; $i++) { $sum += 0.1 }; $sum
9,99999999999998
I can't think of a nice analogy to properly explain this, though. It's basically the same problem why you can represent 1/3 only approximately in decimal because to get the exact value you need to repeat the 3 indefinitely at the end of the decimal fraction.
Similarly, binary fractions are good for representing halves, quarters, eighths, etc. but things like a tenth will yield an infinitely repeating stream of binary digits.
Then there is another problem, though most people don't stumble into that, unless they're doing huge amounts of numerical stuff. But then, those already know about the problem. Since many floating-point numbers are merely approximations of the exact value this means that for a given approximation f of a real number r there can be infinitely many more real numbers r1, r2, ... which map to exactly the same approximation. Those numbers lie in a certain interval. Let's say that rmin is the minimum possible value of r that results in f and rmax the maximum possible value of r for which this holds, then you got an interval [rmin, rmax] where any number in that interval can be your actual number r.
Now, if you perform calculations on that number—adding, subtracting, multiplying, etc.—you lose precision. Every number is just an approximation, therefore you're actually performing calculations with intervals. The result is an interval too and the approximation error only ever gets larger, thereby widening the interval. You may get back a single number from that calculation. But that's merely one number from the interval of possible results, taking into account precision of your original operands and the precision loss due to the calculation.
That sort of thing is called Interval arithmetic and at least for me it was part of our math course at the university.
If you are using laravel
5 or 6:
<link rel="stylesheet" href="/css/bootstrap.min.css">
<link src="/images/test.png">
<!-- / is important and dont write public folder-->
_x000D_
If you want to change settings in the launcher, change icon size, or grid size just hold down on an empty part of your home screen. Tap the three Dots and there you go.
From https://forums.oneplus.net/threads/how-to-change-icon-and-grid-size-trebuchet-settings.84820/
When configuring the phone for first time I saw something about a grid somewhere, but couldn't find it again. Luckily I found the answer on the link above.
That's all. You can see progression of build in left below corner.
Here's Microsoft's write up on using SET IDENTITY_INSERT, which might be helpful to others seeing this post if they, like me, found this post when trying to recreate deleted records while maintaining the original identity column value.
to recreate deleted records with original identity column value: http://msdn.microsoft.com/en-us/library/aa259221(v=sql.80).aspx
At first install necessary PDO parts by running the command
`sudo apt-get install php*-mysql`
where * is a version name of php like 5.6, 7.0, 7.1, 7.2
After installation you need to mention these two statements
extension=pdo.so
extension=pdo_mysql.so
in your .ini file (uncomment if it is already there) and restart server by command
sudo service apache2 restart
onChange will not call handleChange on mobile when using defaultChecked. As an alternative you can can use onClick and onTouchEnd.
<input onClick={this.handleChange} onTouchEnd={this.handleChange} type="checkbox" defaultChecked={!!this.state.complete} />;
No longer works for spreadsheets Protected with Excel 2013 or later -- they improved the pw hash. So now need to unzip .xlsx and hack the internals.
For-loop contains sub.length() / 2 - 1
. It has to be subtracted with 1 as the element in the middle of the string does not have to checked.
For example, if we have to check an string with 7 chars (1234567), then 7/2 => 3 and then we subtrack 1, and so the positions in the string will become (0123456). The chars checked with be the 0, 1, 2 element with the 6, 5, 4 respectively. We do not care about the element at the position 3 as it is in the exact middle of the string.
private boolean isPalindromic(String sub) {
for (int i = 0; i <= sub.length() / 2 - 1; i++) {
if (sub.charAt(i) != sub.charAt(sub.length() - 1 - i)) {
return false;
}
}
return true;
}
You can also access a column using the dot notation (also called attribute access) and then calculate its mean:
df.your_column_name.mean()
There's a great example in the AngularJS docs.
It's very well commented and should get you pointed in the right direction.
A simple example, maybe more so what you're looking for is below:
HTML
<div ng-app="myDirective" ng-controller="x">
<input type="text" ng-model="test" my-directive>
</div>
JavaScript
angular.module('myDirective', [])
.directive('myDirective', function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
scope.$watch(attrs.ngModel, function (v) {
console.log('value changed, new value is: ' + v);
});
}
};
});
function x($scope) {
$scope.test = 'value here';
}
Edit: Same thing, doesn't require ngModel
jsfiddle:
JavaScript
angular.module('myDirective', [])
.directive('myDirective', function () {
return {
restrict: 'A',
scope: {
myDirective: '='
},
link: function (scope, element, attrs) {
// set the initial value of the textbox
element.val(scope.myDirective);
element.data('old-value', scope.myDirective);
// detect outside changes and update our input
scope.$watch('myDirective', function (val) {
element.val(scope.myDirective);
});
// on blur, update the value in scope
element.bind('propertychange keyup paste', function (blurEvent) {
if (element.data('old-value') != element.val()) {
console.log('value changed, new value is: ' + element.val());
scope.$apply(function () {
scope.myDirective = element.val();
element.data('old-value', element.val());
});
}
});
}
};
});
function x($scope) {
$scope.test = 'value here';
}
In this particular case, the solution was the right proxy configuration of eclipse (Window -> Preferences -> Network Connection), the company possessed a strict security system. I will leave the question, because there are answers that can help the community. Thank you very much for the answers above.
Another options is Matteo Bicocchi's jQuery mb.extruder tabs plug-in: http://pupunzi.open-lab.com/mb-jquery-components/jquery-mb-extruder/
You can loop through the cells of any column in a table by knowing just its name and not its position. If the table is in sheet1 of the workbook:
Dim rngCol as Range
Dim cl as Range
Set rngCol = Sheet1.Range("TableName[ColumnName]")
For Each cl in rngCol
cl.Value = "PHEV"
Next cl
The code above will loop through the data values only, excluding the header row and the totals row. It is not necessary to specify the number of rows in the table.
Use this to find the location of any column in a table by its column name:
Dim colNum as Long
colNum = Range("TableName[Column name to search for]").Column
This returns the numeric position of a column in the table.
You can use the WebClient
Using System.Net;
WebClient client = new WebClient();
string downloadString = client.DownloadString("http://www.gooogle.com");
A solution combining find and replace methods in a single line if statement could be:
```python
my_var = "stackoverflaw"
my_new_var = my_var.replace('a', 'o', 1) if my_var.find('s') != -1 else my_var
print(f"my_var = {my_var}") # my_var = stackoverflaw
print(f"my_new_var = {my_new_var}") # my_new_var = stackoverflow
```
This solution worked for me:
Go to SQL Server Management Studio, Right click on the failing step and select Properties -> Logging -> Remove the Log Provider, and then re-add it
I have found when I am using a manifest that the listing of jars for the classpath need to have a space after the listing of each jar e.g. "required_lib/sun/pop3.jar required_lib/sun/smtp.jar ". Even if it is the last in the list.
This works:
var img = document.createElement('img');
img.src = 'img/eqp/' + this.apparel + '/' + this.facing + '_idle.png';
document.getElementById('gamediv').appendChild(img)
Or using jQuery:
$('<img/>')
.attr('src','img/eqp/' + this.apparel + '/' + this.facing + '_idle.png')
.appendTo('#gamediv');
You can use the "Test Connection" feature after creating the ODBC connection through Control Panel > Administrative Tools > Data Sources.
To test a SQL command itself you could try:
http://www.sqledit.com/odbc/runner.html
http://www.sqledit.com/sqlrun.zip
Or (perhaps easier and more useful in the long run) you can make a test ASP.NET or PHP page in a couple minutes to run SQL statement yourself through IIS.
I would always recommend going to the authoritative source when trying to understand the meaning and purpose of HTTP headers.
The "Host" header field in a request provides the host and port
information from the target URI, enabling the origin server to
distinguish among resources while servicing requests for multiple
host names on a single IP address.
This is not a bug in your code. It is coming from .Net's Socket implementation. If you use the overloaded implementation of EndReceive as below you will not get this exception.
SocketError errorCode;
int nBytesRec = socket.EndReceive(ar, out errorCode);
if (errorCode != SocketError.Success)
{
nBytesRec = 0;
}
For MacVim and Windows Gvim, simply add the following to your ~/.vimrc
:
set clipboard=unnamed
Now all operations such as yy
, D
, and P
work with the clipboard. No need to prefix them with "*
or "+
.
man wget: -O file --output-document=file
wget "url" -O /tmp/cron_test/<file>
I did it by putting
export JAVA_HOME=`/usr/libexec/java_home`
(backtics) in my .bashrc. See my comment on Adrian's answer.
Efran Cobisi's suggestion of using an Auto Mapper is a good one. I have used Auto Mapper for a while and it worked well, until I found the much faster alternative, Mapster.
Given a large list or IEnumerable, Mapster outperforms Auto Mapper. I found a benchmark somewhere that showed Mapster being 6 times as fast, but I could not find it again. You could look it up and then, if it is suits you, use Mapster.
You need to SAVE your code file with the ".py" extension. Then, on the 'Tools/Build System' menu, make sure your build system is set to either 'auto' or 'Python'. What that message is telling you is there is no valid Python file to 'build' (or, in this case just run).
Assuming there is a column named business:
SELECT Business, COUNT(*) FROM eventsTable GROUP BY Business
5 options:
#pragma warning disable 1591
to disable the warning just for some bits of code (and #pragma warning restore 1591
afterwards)I have created an AsyncTask for saving bitmaps.
public class BitmapSaver extends AsyncTask<Void, Void, Void>
{
public static final String TAG ="BitmapSaver";
private Bitmap bmp;
private Context ctx;
private File pictureFile;
public BitmapSaver(Context paramContext , Bitmap paramBitmap)
{
ctx = paramContext;
bmp = paramBitmap;
}
/** Create a File for saving an image or video */
private File getOutputMediaFile()
{
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
+ "/Android/data/"
+ ctx.getPackageName()
+ "/Files");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
File mediaFile;
String mImageName="MI_"+ timeStamp +".jpg";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}
protected Void doInBackground(Void... paramVarArgs)
{
this.pictureFile = getOutputMediaFile();
if (this.pictureFile == null) { return null; }
try
{
FileOutputStream localFileOutputStream = new FileOutputStream(this.pictureFile);
this.bmp.compress(Bitmap.CompressFormat.PNG, 90, localFileOutputStream);
localFileOutputStream.close();
}
catch (FileNotFoundException localFileNotFoundException)
{
return null;
}
catch (IOException localIOException)
{
}
return null;
}
protected void onPostExecute(Void paramVoid)
{
super.onPostExecute(paramVoid);
try
{
//it will help you broadcast and view the saved bitmap in Gallery
this.ctx.sendBroadcast(new Intent("android.intent.action.MEDIA_MOUNTED", Uri
.parse("file://" + Environment.getExternalStorageDirectory())));
Toast.makeText(this.ctx, "File saved", 0).show();
return;
}
catch (Exception localException1)
{
try
{
Context localContext = this.ctx;
String[] arrayOfString = new String[1];
arrayOfString[0] = this.pictureFile.toString();
MediaScannerConnection.scanFile(localContext, arrayOfString, null,
new MediaScannerConnection.OnScanCompletedListener()
{
public void onScanCompleted(String paramAnonymousString ,
Uri paramAnonymousUri)
{
}
});
return;
}
catch (Exception localException2)
{
}
}
}
}
You want to take advantage of the inserted logical table that is available in the context of a trigger. It matches the schema for the table that is being inserted to and includes the row(s) that will be inserted (in an update trigger you have access to the inserted and deleted logical tables which represent the the new and original data respectively.)
So to insert Employee / Department pairs that do not currently exist you might try something like the following.
CREATE TRIGGER trig_Update_Employee
ON [EmployeeResult]
FOR INSERT
AS
Begin
Insert into Employee (Name, Department)
Select Distinct i.Name, i.Department
from Inserted i
Left Join Employee e
on i.Name = e.Name and i.Department = e.Department
where e.Name is null
End
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="35dp">
<TextView
android:id="@+id/lblExpenseCancel"
android:layout_width="0dp"
android:layout_weight="0.5"
android:layout_height="wrap_content"
android:text="@string/cancel"
android:textColor="#404040"
android:layout_marginLeft="10dp"
android:textSize="20sp"
android:layout_marginTop="9dp"/>
<Button
android:id="@+id/btnAddExpense"
android:layout_width="0dp"
android:layout_weight="0.5"
android:layout_height="wrap_content"
android:background="@drawable/stitch_button"
android:layout_marginLeft="10dp"
android:text="@string/add"
android:layout_gravity="right"
android:layout_marginRight="15dp"/>
</LinearLayout>
This will solve your problem
The default
condition can be anyplace within the switch that a case clause can exist. It is not required to be the last clause. I have seen code that put the default as the first clause. The case 2:
gets executed normally, even though the default clause is above it.
As a test, I put the sample code in a function, called test(int value){}
and ran:
printf("0=%d\n", test(0));
printf("1=%d\n", test(1));
printf("2=%d\n", test(2));
printf("3=%d\n", test(3));
printf("4=%d\n", test(4));
The output is:
0=2
1=1
2=4
3=8
4=10
#include <climits>
#include <iostream>
using namespace std;
int main() {
cout << INT_MAX << endl;
}
Check out angular-ui, specifically, route checking: http://angular-ui.github.io/ui-utils/
Unfortunately there is currently no designer support (unlike for SQL Server 2005) for building relationships between tables in SQL Server CE. To build relationships you need to use SQL commands such as:
ALTER TABLE Orders
ADD CONSTRAINT FK_Customer_Order
FOREIGN KEY (CustomerId) REFERENCES Customers(CustomerId)
If you are doing CE development, i would recomend this FAQ:
EDIT: In Visual Studio 2008 this is now possible to do in the GUI by right-clicking on your table.
You can use AlarmManager in coop with notification mechanism Something like this:
Intent intent = new Intent(ctx, ReminderBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(ctx, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) ctx.getSystemService(Activity.ALARM_SERVICE);
// time of of next reminder. Unix time.
long timeMs =...
if (Build.VERSION.SDK_INT < 19) {
am.set(AlarmManager.RTC_WAKEUP, timeMs, pendingIntent);
} else {
am.setExact(AlarmManager.RTC_WAKEUP, timeMs, pendingIntent);
}
It starts alarm.
public class ReminderBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setSmallIcon(...)
.setContentTitle(..)
.setContentText(..);
Intent intentToFire = new Intent(context, Activity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intentToFire, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
NotificationManagerCompat.from(this);.notify((int) System.currentTimeMillis(), builder.build());
}
}
None of the solutions worked for me since I didn't want to change the styling of the container/wrapper element. This code worked for me:
position: absolute;
left: 50%;
margin-left: -50px;
top: 50%;
margin-top: -50px;
To call the function you have to add ()
{this.renderIcon()}
UPDATE:
Upon learning flex recently, there is a cleaner way (no tables and less css). Set the wrapper as display: flex;
and to center it's children give it the properties align-items: center;
for (vertical) and justify-content: center;
(horizontal) centering.
See this updated JS Fiddle
Strange that nobody suggested this before.. I always use tables to do this.
Simply make a wrapper have display: table
and center stuff inside it with text-align: center
for horizontal and vertical-align: middle
for vertical alignment.
<div class='wrapper'>
<i class='icon fa fa-bars'></i>
</div>
and some sass like this
.wrapper{
display: table;
i{
display: table-cell;
vertical-align: middle;
text-align: center;
}
}
or see this JS Fiddle
Given the ease of use of Access, I don't see a compelling reason to use Excel at all other than to export data for number crunching. Access is designed to easily build data forms and, in my opinion, will be orders of magnitude easier and less time-consuming than using Excel. A few hours to learn the Access object model will pay for itself many times over in terms of time and effort.
I see a lot of answers here that have you subtracting from the width of the div and/or using box-sizing, but all you need to do is apply the padding the child elements of the div in question. So, for example, if you have some markup like this:
<div id="container">
<p id="text">Find Agents</p>
</div>
All you need to do is apply this CSS:
#text {
padding: 10px;
}
Here is a fiddle showing the difference: http://jsfiddle.net/CHCVF/2/
Or, better yet, if you have multiple elements and don't feel like giving them all the same class, you can do something like this:
.container * {
padding: 5px 10px;
}
Which will select all of the child elements and assign them the padding you want. Here is a fiddle of that in action: http://jsfiddle.net/CHCVF/3/
import org.springframework.core.io.ClassPathResource;
...
File folder = new ClassPathResource("sql").getFile();
File[] listOfFiles = folder.listFiles();
It is worth noting that this will limit your deployment options, ClassPathResource.getFile()
only works if the container has exploded (unzipped) your war file.
$location won't help you with external URLs, use the $window service instead:
$window.location.href = 'http://www.google.com';
Note that you could use the window object, but it is bad practice since $window is easily mockable whereas window is not.
I had a similar issue with Pandas, you need to use the iterrows() function to iterate through a Pandas dataset Pandas documentation for iterrows
data = pd.read_csv('foo.csv')
for index,item in data.iterrows():
print('{} {}'.format(item["gravatar_id"], item["position"]))
note that you need to handle the index in the dataset that is also returned by the function.
For future googlers (thousands have now googled this question):
To set your mind at ease, the onClick
event does work with divs in react, so double-check your code syntax.
These are right:
<div onClick={doThis}>
<div onClick={() => doThis()}>
These are wrong:
<div onClick={doThis()}>
<div onClick={() => doThis}>
(and don't forget to close your tags... Watch for this:
<div onClick={doThis}
missing closing tag on the div)
The actual information represented by a boolean value in Java is one bit: 1 for true, 0 for false. However, the actual size of a boolean variable in memory is not precisely defined by the Java specification. See Primitive Data Types in Java.
The boolean data type has only two possible values: true and false. Use this data type for simple flags that track true/false conditions. This data type represents one bit of information, but its "size" isn't something that's precisely defined.
In your main.xml include the following in your ListView:
android:drawSelectorOnTop="false"
android:listSelector="@android:color/darker_gray"
It depends on number of entities which are going to be updated, if you have large number of entities using JPA Query Update statement is better as you dont have to load all the entities from database, if you are going to update just one entity then using find and update is fine.
Why are you trying to use loops!? Iterating is such a waste of computing power here...
This can be done using math:
function isPrime(num) {
if ( num !=1 && num%3 != 0 && num%5 != 0 && num%7 != 0 && num%9 != 0 && num%11 != 0 && Math.sign(num) == 1 && Math.round(num) == num) {
if ( (num-1)%6 == 0 || (num+1)%6 == 0 ) {
return true;
}
} // no need for else statement since if true, then will do return
return num==11||x==9||num==5||num==3||num==2; // will return T/F;
}
Always try to do the mathematical way, rather than iterating over loops. Math is almost always the most efficient way to do something. Yes, this equation might be confusing... However, we don't need much readability when it comes to checking if something is prime or not... It likely isn't going to need to be maintained by future code editors.
EDIT:
Optimized code version:
function isPrime(x=0) {
const m = Math;
return (x%3!=0&&x%5!=0&&x%7!=0&&x%9!=0&&x%11!=0&&x!=1&&m.sign(x)*m.round(x)==x&&(!!!((x-1)%6)||!!!((x+1)%6)))||x==11||x==9||x==7||x==5||x==3||x==2;
}
EDIT:
As it turns out... there's more to do with false-positive detection, because they're randomly distributed (at least seemingly) so the +-1 %6 stuff really isn't going to work for everything... But I'm definitely on to something here...
Into Preferences > Settings - Users
File : Preferences.sublime-settings
Write this :
"show_encoding" : true,
It's explain on the release note date 17 December 2013. Build 3059. Official site Sublime Text 3
All file modes in Python
r
for readingr+
opens for reading and writing (cannot truncate a file)w
for writing w+
for writing and reading (can truncate a file) rb
for reading a binary file. The file pointer is placed at the beginning of the file.rb+
reading or writing a binary filewb+
writing a binary filea+
opens for appendingab+
Opens a file for both appending and reading in binary. The file pointer is at the end of the file if the file exists. The file opens in the append mode.x
open for exclusive creation, failing if the file already exists (Python 3)The skinny is that a CPU loads data from memory addresses, stores data to memory addresses, and execute instructions sequentially out of memory addresses, with some conditional jumps in the sequence of instructions processed. Each of these three categories of instructions involves computing an address to a memory cell to be used in the machine instruction. Because machine instructions are of a variable length depending on the particular instruction involved, and because we string a variable length of them together as we build our machine code, there is a two step process involved in calculating and building any addresses.
First we laying out the allocation of memory as best we can before we can know what exactly goes in each cell. We figure out the bytes, or words, or whatever that form the instructions and literals and any data. We just start allocating memory and building the values that will create the program as we go, and note down anyplace we need to go back and fix an address. In that place we put a dummy to just pad the location so we can continue to calculate memory size. For example our first machine code might take one cell. The next machine code might take 3 cells, involving one machine code cell and two address cells. Now our address pointer is 4. We know what goes in the machine cell, which is the op code, but we have to wait to calculate what goes in the address cells till we know where that data will be located, i.e. what will be the machine address of that data.
If there were just one source file a compiler could theoretically produce fully executable machine code without a linker. In a two pass process it could calculate all of the actual addresses to all of the data cells referenced by any machine load or store instructions. And it could calculate all of the absolute addresses referenced by any absolute jump instructions. This is how simpler compilers, like the one in Forth work, with no linker.
A linker is something that allows blocks of code to be compiled separately. This can speed up the overall process of building code, and allows some flexibility with how the blocks are later used, in other words they can be relocated in memory, for example adding 1000 to every address to scoot the block up by 1000 address cells.
So what the compiler outputs is rough machine code that is not yet fully built, but is laid out so we know the size of everything, in other words so we can start to calculate where all of the absolute addresses will be located. the compiler also outputs a list of symbols which are name/address pairs. The symbols relate a memory offset in the machine code in the module with a name. The offset being the absolute distance to the memory location of the symbol in the module.
That's where we get to the linker. The linker first slaps all of these blocks of machine code together end to end and notes down where each one starts. Then it calculates the addresses to be fixed by adding together the relative offset within a module and the absolute position of the module in the bigger layout.
Obviously I've oversimplified this so you can try to grasp it, and I have deliberately not used the jargon of object files, symbol tables, etc. which to me is part of the confusion.
For what it's worth, for Gecko-based browsers you can't condition this thing off of :visited
due to the resulting privacy leaks. See http://hacks.mozilla.org/2010/03/privacy-related-changes-coming-to-css-vistited/
/register-form.html
to signup-form.html
./register.php
, then now load (GET) /success.html
./register.php
, then this tells it to redo the POST at /signup.php
.RFC 7231 (from 2014) is very readable and not overly verbose. If you want to know the exact answer, it's a recommended read. Some other answers use RFC 2616 from 1999, but nothing changed.
RFC 7238 specifies the 308 status. It is considered experimental, but it was already supported by all major browsers in 2016.
Reinstall numpy-1.11.0_XXX.whl (for your Python) from www.lfd.uci.edu/~gohlke/pythonlibs. This file has the same name and version if compare with the variant downloaded by me earlier 29.03.2016, but its size and content differ from old variant. After re-installation error disappeared.
Second option - return back to scipy 0.17.0 from 0.17.1
P.S. I use Windows 64-bit version of Python 3.5.1, so can't guarantee that numpy for Python 2.7 is already corrected.
It has been almost 8 years since the question was asked, but I will venture an answer not previously given. The OP said this doesn't work:
action="javascript:simpleCart.checkout()"
And the OP said that this code continued to fail despite trying all the good advice he got. So I will venture a guess. The action is calling checkout()
as a static method of the simpleCart
class; but maybe checkout()
is actually an instance member, and not static. It depends how he defined checkout()
.
By the way, simpleCart
is presumably a class name, and by convention class names have an initial capital letter, so let's use that convention, here. Let's use the name SimpleCart
.
Here is some sample code that illustrates defining checkout()
as an instance member. This was the correct way to do it, prior to ECMA-6:
function SimpleCart() {
...
}
SimpleCart.prototype.checkout = function() { ... };
Many people have used a different technique, as illustrated in the following. This was popular, and it worked, but I advocate against it, because instances are supposed to be defined on the prototype
, just once, while the following technique defines the member on this
and does so repeatedly, with every instantiation.
function SimpleCart() {
...
this.checkout = function() { ... };
}
And here is an instance definition in ECMA-6, using an official class
:
class SimpleCart {
constructor() { ... }
...
checkout() { ... }
}
Compare to a static definition in ECMA-6. The difference is just one word:
class SimpleCart {
constructor() { ... }
...
static checkout() { ... }
}
And here is a static definition the old way, pre-ECMA-6. Note that the checkout()
method is defined outside of the function. It is a member of the function object, not the prototype object, and that's what makes it static.
function SimpleCart() {
...
}
SimpleCart.checkout = function() { ... };
Because of the way it is defined, a static function will have a different concept of what the keyword this
references. Note that instance member functions are called using the this
keyword:
this.checkout();
Static member functions are called using the class name:
SimpleCart.checkout();
The problem is that the OP wants to put the call into HTML, where it will be in global scope. He can't use the keyword this
because this
would refer to the global scope (which is window
).
action="javascript:this.checkout()" // not as intended
action="javascript:window.checkout()" // same thing
There is no easy way to use an instance member function in HTML. You can do stuff in combination with JavaScript, creating a registry in the static scope of the Class, and then calling a surrogate static method, while passing an argument to that surrogate that gives the index into the registry of your instance, and then having the surrogate call the actual instance member function. Something like this:
// In Javascript:
SimpleCart.registry[1234] = new SimpleCart();
// In HTML
action="javascript:SimpleCart.checkout(1234);"
// In Javascript
SimpleCart.checkout = function(myIndex) {
var myThis = SimpleCart.registry[myIndex];
myThis.checkout();
}
You could also store the index as an attribute on the element.
But usually it is easier to just do nothing in HTML and do everything in JavaScript with .addEventListener()
and use the .bind()
capability.
ORA-03113: end-of-file on communication channel
Is the database letting you know that the network connection is no more. This could be because:
For 1) (firewall) search tahiti.oracle.com for SQLNET.EXPIRE_TIME
. This is a sqlnet.ora parameter that will regularly send a network packet at a configurable interval ie: setting this will make the firewall believe that the connection is live.
For 1) (network) speak to your network admin (connection could be unreliable)
For 2) Check the alert.log
for errors. If the server process failed there will be an error message. Also a trace file will have been written to enable support to identify the issue. The error message will reference the trace file.
Support issues can be raised at metalink.oracle.com with a suitable Customer Service Identifier (CSI)
To convert UTC time to Local you have to use moment.local()
.
For more info see docs
var date = moment.utc().format('YYYY-MM-DD HH:mm:ss');
console.log(date); // 2015-09-13 03:39:27
var stillUtc = moment.utc(date).toDate();
var local = moment(stillUtc).local().format('YYYY-MM-DD HH:mm:ss');
console.log(local); // 2015-09-13 09:39:27
var date = moment.utc().format();_x000D_
console.log(date, "- now in UTC"); _x000D_
_x000D_
var local = moment.utc(date).local().format();_x000D_
console.log(local, "- UTC now to local");
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
_x000D_
The short answer is that you can't do it using JavaScript alone. You'd need a server-side handler to connect with the SMTP server to actually send the mail. There are many simple mail scripts online, such as this one for PHP:
Using a script like that, you'd POST the contents of your web form to the script, using a function like this:
And then the script would take those values, plus a username and password for the mail server, and connect to the server to send the mail.
Change
mAdapter = new RecordingsListAdapter(this, recordings);
to
mAdapter = new RecordingsListAdapter(getActivity(), recordings);
and also make sure that recordings!=null
at mAdapter = new RecordingsListAdapter(this, recordings);
Simplest way for me was just using a string/template litteral:
elementName.style.cssText = `
width:80%;
margin: 2vh auto;
background-color: rgba(5,5,5,0.9);
box-shadow: 15px 15px 200px black; `;
Great option cause you can use multiple line strings making life easy.
Check out string/template litterals here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
EDIT: I am maintaining a similar, but more in-depth answer at: https://stackoverflow.com/a/28380690/895245
To see exactly what is happening, use nc -l
or an ECHO server and an user agent like a browser or cURL.
Save the form to an .html
file:
<form action="http://localhost:8000" method="post" enctype="multipart/form-data">
<p><input type="text" name="text" value="text default">
<p><input type="file" name="file1">
<p><input type="file" name="file2">
<p><button type="submit">Submit</button>
</form>
Create files to upload:
echo 'Content of a.txt.' > a.txt
echo '<!DOCTYPE html><title>Content of a.html.</title>' > a.html
Run:
nc -l localhost 8000
Open the HTML on your browser, select the files and click on submit and check the terminal.
nc
prints the request received. Firefox sent:
POST / HTTP/1.1
Host: localhost:8000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:29.0) Gecko/20100101 Firefox/29.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: __atuvc=34%7C7; permanent=0; _gitlab_session=226ad8a0be43681acf38c2fab9497240; __profilin=p%3Dt; request_method=GET
Connection: keep-alive
Content-Type: multipart/form-data; boundary=---------------------------9051914041544843365972754266
Content-Length: 554
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="text"
text default
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file1"; filename="a.txt"
Content-Type: text/plain
Content of a.txt.
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file2"; filename="a.html"
Content-Type: text/html
<!DOCTYPE html><title>Content of a.html.</title>
-----------------------------9051914041544843365972754266--
Aternativelly, cURL should send the same POST request as your a browser form:
nc -l localhost 8000
curl -F "text=default" -F "[email protected]" -F "[email protected]" localhost:8000
You can do multiple tests with:
while true; do printf '' | nc -l localhost 8000; done
Please try after removing divs from formor try to use onclick method on submit button.
You may set the default file association of ps1
files to be powershell.exe
which will allow you to execute a powershell script by double clicking on it.
In Windows 10,
ps1
fileOpen with
Choose another app
More apps
Look for another app on this PC
. C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
. That will change the file association and ps1
files will execute by double-clicking them. You may change it back to its default behavior by setting notepad.exe
to the default app.
There are a couple of things you could look at. Based on your question, it looks like the function owner is different from the table owner.
1) Grants via a role : In order to create stored procedures and functions on another user's objects, you need direct access to the objects (instead of access through a role).
2)
By default, stored procedures and SQL methods execute with the privileges of their owner, not their current user.
If you created a table in Schema A and the function in Schema B, you should take a look at Oracle's Invoker/Definer Rights concepts to understand what might be causing the issue.
http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/subprograms.htm#LNPLS00809
We are using Response.SetCookie()
for update the old one cookies and Response.Cookies.Add()
are use to add the new cookies. Here below code CompanyId
is update in old cookie[OldCookieName]
.
HttpCookie cookie = Request.Cookies["OldCookieName"];//Get the existing cookie by cookie name.
cookie.Values["CompanyID"] = Convert.ToString(CompanyId);
Response.SetCookie(cookie); //SetCookie() is used for update the cookie.
Response.Cookies.Add(cookie); //The Cookie.Add() used for Add the cookie.
If anyone comes to this thread and has this issue when you remote to a VMware VM with windows 10 1903, disabling 3d in the graphics card worked for me.
Depends, Do you need the data to be loaded each time you open the view? or only once?
viewDidLoad:
Whatever processing you have that needs to be done once.
viewWilLAppear:
Whatever processing that needs to change every time the page is loaded.
Labels, icons, button titles or most dataInputedByDeveloper usually don't change. Names, photos, links, button status, lists (input Arrays for your tableViews or collectionView) or most dataInputedByUser usually do change.
Let me give some information on them:
quit()
simply raises the SystemExit
exception.
Furthermore, if you print it, it will give a message:
>>> print (quit)
Use quit() or Ctrl-Z plus Return to exit
>>>
This functionality was included to help people who do not know Python. After all, one of the most likely things a newbie will try to exit Python is typing in quit
.
Nevertheless, quit
should not be used in production code. This is because it only works if the site
module is loaded. Instead, this function should only be used in the interpreter.
exit()
is an alias for quit
(or vice-versa). They exist together simply to make Python more user-friendly.
Furthermore, it too gives a message when printed:
>>> print (exit)
Use exit() or Ctrl-Z plus Return to exit
>>>
However, like quit
, exit
is considered bad to use in production code and should be reserved for use in the interpreter. This is because it too relies on the site
module.
sys.exit()
also raises the SystemExit
exception. This means that it is the same as quit
and exit
in that respect.
Unlike those two however, sys.exit
is considered good to use in production code. This is because the sys
module will always be there.
os._exit()
exits the program without calling cleanup handlers, flushing stdio buffers, etc. Thus, it is not a standard way to exit and should only be used in special cases. The most common of these is in the child process(es) created by os.fork
.
Note that, of the four methods given, only this one is unique in what it does.
Summed up, all four methods exit the program. However, the first two are considered bad to use in production code and the last is a non-standard, dirty way that is only used in special scenarios. So, if you want to exit a program normally, go with the third method: sys.exit
.
Or, even better in my opinion, you can just do directly what sys.exit
does behind the scenes and run:
raise SystemExit
This way, you do not need to import sys
first.
However, this choice is simply one on style and is purely up to you.
In Android, How to use a Cursor with a raw query in sqlite:
Cursor c = sampleDB.rawQuery("SELECT FirstName, Age FROM mytable " +
"where Age > 10 LIMIT 5", null);
if (c != null ) {
if (c.moveToFirst()) {
do {
String firstName = c.getString(c.getColumnIndex("FirstName"));
int age = c.getInt(c.getColumnIndex("Age"));
results.add("" + firstName + ",Age: " + age);
}while (c.moveToNext());
}
}
c.close();
As per the PHP manual - parse_url should not be used to validate a URL.
Unfortunately, it seems that filter_var('example.com', FILTER_VALIDATE_URL)
does not perform any better.
Both parse_url()
and filter_var()
will pass malformed URLs such as http://...
Therefore in this case - regex is the better method.
/usr/bin/java_home
tool returns 1 if java not installed.
So you can check if java is installed by the next way:
/usr/libexec/java_home &> /dev/null && echo "installed" || echo "not installed"
Instead of using FileWriter
, create a FileOutputStream
. You can then wrap this in an OutputStreamWriter
, which allows you to pass an encoding in the constructor. Then you can write your data to that inside a try-with-resources Statement:
try (OutputStreamWriter writer =
new OutputStreamWriter(new FileOutputStream(PROPERTIES_FILE), StandardCharsets.UTF_8))
// do stuff
}
Using ==
might be dangerous.
Note, that it would cast the variable to another data type if the two differs.
Examples:
echo (1 == '1') ? 'true' : 'false';
echo (1 == true) ? 'true' : 'false';
As you can see, these two are from different types, but the result is true
, which might not be what your code will expect.
Using ===
, however, is recommended as test shows that it's a bit faster than strcmp()
and its case-insensitive alternative strcasecmp()
.
Quick googling yells this speed comparison: http://snipplr.com/view/758/
Exceptions bubble up the stack. If a caller calls a method that throws a checked exception, like IOException, it must also either catch the exception, or itself throw it.
In the case of the first block:
filecontent()
{
setGUI();
setRegister();
showfile();
setTitle("FileData");
setVisible(true);
setSize(300, 300);
/*
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
*/
}
You would have to include a try catch block:
filecontent()
{
setGUI();
setRegister();
try {
showfile();
}
catch (IOException e) {
// Do something here
}
setTitle("FileData");
setVisible(true);
setSize(300, 300);
/*
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
*/
}
In the case of the second:
public void actionPerformed(ActionEvent ae)
{
if (ae.getSource() == submit)
{
showfile();
}
}
You cannot throw IOException from this method as its signature is determined by the interface, so you must catch the exception within:
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==submit)
{
try {
showfile();
}
catch (IOException e) {
// Do something here
}
}
}
Remember, the showFile() method is throwing the exception; that's what the "throws" keyword indicates that the method may throw that exception. If the showFile() method is throwing, then whatever code calls that method must catch, or themselves throw the exception explicitly by including the same throws IOException addition to the method signature, if it's permitted.
If the method is overriding a method signature defined in an interface or superclass that does not also declare that the method may throw that exception, you cannot declare it to throw an exception.
Actually you have a code compiled targeting a higher JDK (JDK 1.8 in your case) but at runtime you are supplying a lower JRE(JRE 7 or below).
you can fix this problem by adding target parameter while compilation
e.g. if your runtime target is 1.7, you should use 1.7 or below
javac -target 1.7 *.java
if you are using eclipse, you can sent this parameter at Window -> Preferences -> Java -> Compiler -> set "Compiler compliance level" = choose your runtime jre version or lower.
I think Dreas' approach is ok. An alternative to this however is to have some static helper methods and implement IXmlSerializable on each of your methods e.g an XmlWriter extension method and the XmlReader one to read it back.
public static void SaveXmlSerialiableElement<T>(this XmlWriter writer, String elementName, T element) where T : IXmlSerializable
{
writer.WriteStartElement(elementName);
writer.WriteAttributeString("TYPE", element.GetType().AssemblyQualifiedName);
element.WriteXml(writer);
writer.WriteEndElement();
}
public static T ReadXmlSerializableElement<T>(this XmlReader reader, String elementName) where T : IXmlSerializable
{
reader.ReadToElement(elementName);
Type elementType = Type.GetType(reader.GetAttribute("TYPE"));
T element = (T)Activator.CreateInstance(elementType);
element.ReadXml(reader);
return element;
}
If you do go down the route of using the XmlSerializer class directly, create serialization assemblies before hand if possible, as you can take a large performance hit in constructing new XmlSerializers regularly.
For a collection you need something like this:
public static void SaveXmlSerialiazbleCollection<T>(this XmlWriter writer, String collectionName, String elementName, IEnumerable<T> items) where T : IXmlSerializable
{
writer.WriteStartElement(collectionName);
foreach (T item in items)
{
writer.WriteStartElement(elementName);
writer.WriteAttributeString("TYPE", item.GetType().AssemblyQualifiedName);
item.WriteXml(writer);
writer.WriteEndElement();
}
writer.WriteEndElement();
}
Unfortunately for MSForms list box looping through the list items and checking their Selected property is the only way. However, here is an alternative. I am storing/removing the selected item in a variable, you can do this in some remote cell and keep track of it :)
Dim StrSelection As String
Private Sub ListBox1_Change()
If ListBox1.Selected(ListBox1.ListIndex) Then
If StrSelection = "" Then
StrSelection = ListBox1.List(ListBox1.ListIndex)
Else
StrSelection = StrSelection & "," & ListBox1.List(ListBox1.ListIndex)
End If
Else
StrSelection = Replace(StrSelection, "," & ListBox1.List(ListBox1.ListIndex), "")
End If
End Sub
You can try with:
display: inline-table;
For me it works fine.
i know i am late but this is what i got after 1 hour of search
<?php
$file = 'file.pdf';
if (! file) {
die('file not found'); //Or do something
} else {
if(isset($_GET['file'])){
// Set headers
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
// Read the file from disk
readfile($file); }
}
?>
and for downloadable link i did this
<a href="index.php?file=file.pdf">Download PDF</a>
In my case, I just had to put the element one line down:
This throws an error:
export function DismissKeyboard(props: IProps) {
return <TouchableWithoutFeedback
onPress={() => Keyboard.dismiss()}> {props.children}
</TouchableWithoutFeedback>;
}
_x000D_
While this does not throw an error:
export function DismissKeyboard(props: IProps) {
return <TouchableWithoutFeedback
onPress={() => Keyboard.dismiss()}>
{props.children}
</TouchableWithoutFeedback>;
}
_x000D_
It is disappointing that many databases do not stick to the standard rules and add extra characters, or incorrectly enable ESCAPE with a default value of ‘\’ when it is missing. Like we don't already have enough trouble with ‘\’!
It's impossible to write DBMS-independent code here, because you don't know what characters you're going to have to escape, and the standard says you can't escape things that don't need to be escaped. (See section 8.5/General Rules/3.a.ii.)
Thank you SQL! gnnn
I think this is the best way to get the month name when you have the month number
Select DateName( month , DateAdd( month , @MonthNumber , 0 ) - 1 )
Or
Select DateName( month , DateAdd( month , @MonthNumber , -1 ) )
The real reason because set
does not work is the fact, that it uses the hash function to distinguish different values. This means that sets only allows hashable objects. Why a list is not hashable is already pointed out.
If you're using jQuery, it's as simple as this:
$('form').attr('action', 'myNewActionTarget.html');
#include <iostream.h>
#include<typeinfo.h>
template<class T>
void fun(T a)
{
if(typeid(T) == typeid(int))
{
//Do something
cout<<"int";
}
else if(typeid(T) == typeid(float))
{
//Do Something else
cout<<"float";
}
}
void main()
{
fun(23);
fun(90.67f);
}
If I understand your question correctly:
for elem in doc.findall('timeSeries/values/value'):
print elem.get('dateTime'), elem.text
or if you prefer (and if there is only one occurrence of timeSeries/values
:
values = doc.find('timeSeries/values')
for value in values:
print value.get('dateTime'), elem.text
The findall()
method returns a list of all matching elements, whereas find()
returns only the first matching element. The first example loops over all the found elements, the second loops over the child elements of the values
element, in this case leading to the same result.
I don't see where the problem with not finding timeSeries
comes from however. Maybe you just forgot the getroot()
call? (note that you don't really need it because you can work from the elementtree itself too, if you change the path expression to for example /timeSeriesResponse/timeSeries/values
or //timeSeries/values
)
To get the width and height of the viewport:
var viewportWidth = $(window).width();
var viewportHeight = $(window).height();
resize event of the page:
$(window).resize(function() {
});
I noticed something else about your coding.... look
INSERT INTO reports_services (id,title,description,cost) VALUES (0, 'test title', 'test decription ', '3.80')
in your "CREATE TABLE" code you have the id set to "AUTO_INCREMENT" which means it's automatically generating a result for that field.... but in your above code you include it as one of the insertions and in the "VALUES" you have a 0 there... idk if that's your way of telling us you left it blank because it's set to AUTO_INC. or if that's the actual code you have... if it's the code you have not only should you not be trying to send data to a field set to generate it automatically, but the RIGHT WAY to do it WRONG would be
'0',
you put
0,
lol....so that might be causing some of the problem... I also just noticed in the code after "test description" you have a space before the '.... that might be throwing something off too.... idk.. I hope this helps n maybe resolves some other problem you might be pulling your hair out about now.... speaking of which.... I need to figure out my problem before I tear all my hair out..... good luck.. :)
UPDATE.....
I almost forgot... if you have the 0 there to show that it's blank... you could be entering "test title" as the id and "test description" as the title then "3.whatever cents" for the description leaving "cost" empty...... which could be why it maxed out because if I'm not mistaking you have it set to NOT NULL.... and you left it null... so it forced something... maybe.... lol
Answer to 1: ArrayList uses an array under the hood. Accessing a member of an ArrayList object is as simple as accessing the array at the provided index, assuming the index is within the bounds of the backing array. A LinkedList has to iterate through its members to get to the nth element. That's O(n) for a LinkedList, versus O(1) for ArrayList.
First the mysqldump command is executed and the output generated is redirected using the pipe. The pipe is sending the standard output into the gzip command as standard input. Following the filename.gz, is the output redirection operator (>) which is going to continue redirecting the data until the last filename, which is where the data will be saved.
For example, this command will dump the database and run it through gzip and the data will finally land in three.gz
mysqldump -u user -pupasswd my-database | gzip > one.gz > two.gz > three.gz
$> ls -l
-rw-r--r-- 1 uname grp 0 Mar 9 00:37 one.gz
-rw-r--r-- 1 uname grp 1246 Mar 9 00:37 three.gz
-rw-r--r-- 1 uname grp 0 Mar 9 00:37 two.gz
My original answer is an example of redirecting the database dump to many compressed files (without double compressing). (Since I scanned the question and seriously missed - sorry about that)
This is an example of recompressing files:
mysqldump -u user -pupasswd my-database | gzip -c > one.gz; gzip -c one.gz > two.gz; gzip -c two.gz > three.gz
$> ls -l
-rw-r--r-- 1 uname grp 1246 Mar 9 00:44 one.gz
-rw-r--r-- 1 uname grp 1306 Mar 9 00:44 three.gz
-rw-r--r-- 1 uname grp 1276 Mar 9 00:44 two.gz
This is a good resource explaining I/O redirection: http://www.codecoffee.com/tipsforlinux/articles2/042.html
In my case I used below configuration at VM options in IntelliJ
, it was not picking the local configurations but after a restart of IntelliJ
it picked configuration details from IntelliJ
and service started running.
-Dspring.profiles.active=local
Make sure your AUTO_INCREMENT
is not out of range. In that case, set a new value for it with:
ALTER TABLE table_name AUTO_INCREMENT=100 -- Change 100 to the desired number
AUTO_INCREMENT
can contain a number that is bigger than the maximum value allowed by the datatype. This can happen if you filled up a table that you emptied afterward but the AUTO_INCREMENT
stayed the same, but there might be different reasons as well. In this case a new entry's id would be out of range.
If this is the cause of your problem, you can fix it by setting AUTO_INCREMENT
to one bigger than the latest row's id. So if your latest row's id is 100 then:
ALTER TABLE table_name AUTO_INCREMENT=101
If you would like to check AUTO_INCREMENT
's current value, use this command:
SELECT `AUTO_INCREMENT`
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'DatabaseName'
AND TABLE_NAME = 'TableName';
This is very useful to avoid errors when accessing properties of null or undefined objects.
null to undefined object
const obj = null;
const newObj = obj || undefined;
// newObj = undefined
undefined to empty object
const obj;
const newObj = obj || {};
// newObj = {}
// newObj.prop = undefined, but no error here
null to empty object
const obj = null;
const newObj = obj || {};
// newObj = {}
// newObj.prop = undefined, but no error here
After you change PATH
with the GUI, close and re-open the console window.
This works because only programs started after the change will see the new PATH
.
Execute this command in the command window you have open:
set PATH=%PATH%;C:\your\path\here\
This command appends C:\your\path\here\
to the current PATH
.
Breaking it down:
set
– A command that changes cmd's environment variables only for the current cmd session; other programs and the system are unaffected.PATH=
– Signifies that PATH
is the environment variable to be temporarily changed.%PATH%;C:\your\path\here\
– The %PATH%
part expands to the current value of PATH
, and ;C:\your\path\here\
is then concatenated to it. This becomes the new PATH
.No, you would need to create a seperate query for each update.
function getTime(offset)
{
var d = new Date();
localTime = d.getTime();
localOffset = d.getTimezoneOffset() * 60000;
// obtain UTC time in msec
utc = localTime + localOffset;
// create new Date object for different city
// using supplied offset
var nd = new Date(utc + (3600000*offset));
//nd = 3600000 + nd;
utc = new Date(utc);
// return time as a string
$("#local").html(nd.toLocaleString());
$("#utc").html(utc.toLocaleString());
}
In my case, the 'Microsoft.ReportViewer.Common.dll' assembly is not required for my project, so I simply removed all references (Project -> Add Reference... -> ...) (all requirements from Publish tab the VS2013 removed automatically) and all works properly.
This worked for me
PHP 7.2
AddHandler application/x-httpd-ea-php72 .php .php7 .phtml
PHP 7.3
AddHandler application/x-httpd-ea-php73 .php
This is not the correct usage of the System.Threading.Timer. When you instantiate the Timer, you should almost always do the following:
_timer = new Timer( Callback, null, TIME_INTERVAL_IN_MILLISECONDS, Timeout.Infinite );
This will instruct the timer to tick only once when the interval has elapsed. Then in your Callback function you Change the timer once the work has completed, not before. Example:
private void Callback( Object state )
{
// Long running operation
_timer.Change( TIME_INTERVAL_IN_MILLISECONDS, Timeout.Infinite );
}
Thus there is no need for locking mechanisms because there is no concurrency. The timer will fire the next callback after the next interval has elapsed + the time of the long running operation.
If you need to run your timer at exactly N milliseconds, then I suggest you measure the time of the long running operation using Stopwatch and then call the Change method appropriately:
private void Callback( Object state )
{
Stopwatch watch = new Stopwatch();
watch.Start();
// Long running operation
_timer.Change( Math.Max( 0, TIME_INTERVAL_IN_MILLISECONDS - watch.ElapsedMilliseconds ), Timeout.Infinite );
}
I strongly encourage anyone doing .NET and is using the CLR who hasn't read Jeffrey Richter's book - CLR via C#, to read is as soon as possible. Timers and thread pools are explained in great details there.
This should do the trick:
$('#some_select_box').click(function() {
$('option:selected', this ).remove();
});
from cmd run: SVN List URL you will be provided with 3 options (r)eject, (a)ccept, (p)ermanently. enter p. This resolved issue for me
I made another variant with dropdown menu (perhaps for advanced search etc).. Here is how it looks like:
<div class="input-group my-4 col-6 mx-auto">
<input class="form-control py-2 border-right-0 border" type="search" placeholder="Type something..." id="example-search-input">
<span class="input-group-append">
<button type="button" class="btn btn-outline-primary dropdown-toggle dropdown-toggle-split border border-left-0 border-right-0 rounded-0" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span class="sr-only">Toggle Dropdown</span>
</button>
<button class="btn btn-outline-primary rounded-right" type="button">
<i class="fas fa-search"></i>
</button>
<div class="dropdown-menu dropdown-menu-right">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<a class="dropdown-item" href="#">Something else here</a>
<div role="separator" class="dropdown-divider"></div>
<a class="dropdown-item" href="#">Separated link</a>
</div>
</span>
</div>
Note: It appears green in the screenshot because my site main theme is green.
ssh -v -L 8783:localhost:8783 [email protected]
...
channel 3: open failed: connect failed: Connection refused
When you connect to port 8783 on your local system, that connection is tunneled through your ssh link to the ssh server on server.com. From there, the ssh server makes TCP connection to localhost port 8783 and relays data between the tunneled connection and the connection to target of the tunnel.
The "connection refused" error is coming from the ssh server on server.com when it tries to make the TCP connection to the target of the tunnel. "Connection refused" means that a connection attempt was rejected. The simplest explanation for the rejection is that, on server.com, there's nothing listening for connections on localhost port 8783. In other words, the server software that you were trying to tunnel to isn't running, or else it is running but it's not listening on that port.
With ES 6 arrow function
let someArray = [
{name:"Kristian", lines:"2,5,10"},
{name:"John", lines:"1,19,26,96"}
];
let arrayToRemove={name:"Kristian", lines:"2,5,10"};
someArray=someArray.filter((e)=>e.name !=arrayToRemove.name && e.lines!= arrayToRemove.lines)
Just to extend the answer above you can also index your columns rather than specifying the column names which can also be useful depending on what you're doing. Given that your location is the first field it would look like this:
bar <- foo[foo[ ,1] == "there", ]
This is useful because you can perform operations on your column value, like looping over specific columns (and you can do the same by indexing row numbers too).
This is also useful if you need to perform some operation on more than one column because you can then specify a range of columns:
foo[foo[ ,c(1:N)], ]
Or specific columns, as you would expect.
foo[foo[ ,c(1,5,9)], ]
Here is elegant solution using Kotlin
extensions:
data class ApiError(val code: Int, val message: String?) {
companion object {
val EMPTY_API_ERROR = ApiError(-1, null)
}
}
fun Throwable.getApiError(): ApiError? {
if (this is HttpException) {
try {
val errorJsonString = this.response()?.errorBody()?.string()
return Gson().fromJson(errorJsonString, ApiError::class.java)
} catch (exception: Exception) {
// Ignore
}
}
return EMPTY_API_ERROR
}
and usage:
showError(retrofitThrowable.getApiError()?.message)
The Subject, in security, is the thing being secured. In this case it could be a persons email or a website or a machine.
If we take the example of an email, say my email, then the subject key container would be the protected location containing my private key.
The certificate store usually refers to Microsoft certificate store which contains certificates form trusted roots, machines on the network, people etc. In my case the subjects certificate store would be the place, within this store, holding my certificates.
If you are working within a microsoft domain then the subject name will invariably hold the Distinguished Name, of the subject, which is how the domain references the subject and holds it in its directory. e.g. CN=Mark Sutton, OU=Developers, O=Mycompany C=UK
To look at your certificates on a microsoft machine:-
Log in as you run>mmc Select File>add/remove snap-in and select certificates then select my user account click Finish then close then ok. Look in the personal area of the store.
In the other areas of the store you will see the other trusted certificates used to validate signatures etc.
Have a look at the documentation. You made the following mistakes.
Firstly, ps.executeQuery()
doesn't have any parameters. Instead you passed the SQL query into it.
Secondly, regarding the prepared statement, you have to use the ?
symbol if want to pass any parameters. And later bind it using
setXXX(index, value)
Here xxx stands for the data type.
use reversed()
function:
reversed(range(10))
It's much more meaningful.
Update:
If you want it to be a list (as btk pointed out):
list(reversed(range(10)))
Update:
If you want to use only range
to achieve the same result, you can use all its parameters. range(start, stop, step)
For example, to generate a list [5,4,3,2,1,0]
, you can use the following:
range(5, -1, -1)
It may be less intuitive but as the comments mention, this is more efficient and the right usage of range for reversed list.
To reset the height of the div, just try
$("#someDiv").height('auto');
In order to find the location of a script, use Split-Path $MyInvocation.MyCommand.Path
(make sure you use this in the script context).
The reason you should use that and not anything else can be illustrated with this example script.
## ScriptTest.ps1
Write-Host "InvocationName:" $MyInvocation.InvocationName
Write-Host "Path:" $MyInvocation.MyCommand.Path
Here are some results.
PS C:\Users\JasonAr> .\ScriptTest.ps1 InvocationName: .\ScriptTest.ps1 Path: C:\Users\JasonAr\ScriptTest.ps1 PS C:\Users\JasonAr> . .\ScriptTest.ps1 InvocationName: . Path: C:\Users\JasonAr\ScriptTest.ps1 PS C:\Users\JasonAr> & ".\ScriptTest.ps1" InvocationName: & Path: C:\Users\JasonAr\ScriptTest.ps1
In PowerShell 3.0 and later you can use the automatic variable $PSScriptRoot
:
## ScriptTest.ps1
Write-Host "Script:" $PSCommandPath
Write-Host "Path:" $PSScriptRoot
PS C:\Users\jarcher> .\ScriptTest.ps1 Script: C:\Users\jarcher\ScriptTest.ps1 Path: C:\Users\jarcher