I have experienced this same problem under CentOS 7
In may case, the problem went off after installation of libcurl-devel
(libcurl
was already installed on this machine)
It could be dependent upon what is supported by the module you are trying to compile. If your makefile is generated by using autotools, use:
--prefix=<myinstalldir>
when running the ./configure
some packages allow you to also override when running:
make prefix=<myinstalldir>
however, if your not using ./configure, only way to know for sure is to open up the makefile and check. It should be one of the first few variables at the top.
Makefile.am -- a user input file to automake
configure.in -- a user input file to autoconf
autoconf generates configure from configure.in
automake gererates Makefile.in from Makefile.am
configure generates Makefile from Makefile.in
For ex:
$]
configure.in Makefile.in
$] sudo autoconf
configure configure.in Makefile.in ...
$] sudo ./configure
Makefile Makefile.in
For folks who ended up here and are using CYGWIN
, install following packages in cygwin and re-run:
To add to those who have mentioned the implicit rules, it's best to see what make has defined implicitly and for your env using:
make -p
For instance:
%.o: %.c
$(COMPILE.c) $(OUTPUT_OPTION) $<
which expands
COMPILE.c = $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c
This will also print # environment
data. Here, you will find GCC's include path among other useful info.
C_INCLUDE_PATH=/usr/include
In make, when it comes to search, the paths are many, the light is one... or something to that effect.
C_INCLUDE_PATH
is system-wide, set it in your shell's *.rc
.$(CPPFLAGS)
is for the preprocessor include path.VPATH = my_dir_to_search
... or even more specific
vpath %.c src
vpath %.h include
make uses VPATH as a general search path so use cautiously. If a file exists in more than one location listed in VPATH, make will take the first occurrence in the list.
I was getting the error “gcc: error: x86_64-linux-gnu-gcc: No such file or directory” as I was trying to build a simple c-extension module to run in Python. I tried all the things above to no avail, and finally realized that I had an error in my module.c code! So I thought it would be helpful to add that, if you are getting this error message but you have python-dev and everything correctly installed, you should look for issues in your code.
About this, java declares that on Windows 10, Edge browser does not support plugins, so it will NOT run java. (see https://www.java.com/it/download/win10.jsp --> only visible with edge in win10) It also reports a notice: java is not officially supported yet in Windows 10. (see https://www.java.com/it/download/faq/win10_faq.xml)
Add your code to the onload event. The accepted answer shows this correctly, however that answer as well as all the others at the time of writing also suggest putting the script tag after the closing body tag, .
This is not valid html. However it will cause your code to work, because browsers are too kind ;)
See this answer for more info Is it wrong to place the <script> tag after the </body> tag?
Downvoted other answers for this reason.
I just want to add that I was getting this error, and nothing would fix it until I changed the Output
destination parameter from F
to FI
.
In other words, I have to output to both file and inline.
Output('doc.pdf', 'I')
to
Output('doc.pdf', 'FI')
I have no idea why this made the difference, but it fixed the error for me...
IMHO it's bad practice to have unit tests create or wait on threads, etc. You'd like these tests to run in split seconds. That's why I'd like to propose a 2-step approach to testing async processes.
Angular only points to src/assets
folder, nothing else is public to access via url so you should use full path
this.fullImagePath = '/assets/images/therealdealportfoliohero.jpg'
Or
this.fullImagePath = 'assets/images/therealdealportfoliohero.jpg'
This will only work if the base href tag is set with /
You can also add other folders for data in angular/cli
.
All you need to modify is angular-cli.json
"assets": [
"assets",
"img",
"favicon.ico",
".htaccess"
]
Note in edit : Dist command will try to find all attachments from assets so it is also important to keep the images and any files you want to access via url inside assets, like mock json data files should also be in assets.
If you have ReSharper installed clicking Shift+Alt+L will move focus to the current file in Solution Explorer.
Active Item Tracking will also need to be enabled as described in the accepted answer
Tools->Options->Projects and Solutions->Track Active Item in Solution Explorer
I had the same problem and just solved it. I had posted my own question on stackoverflow:
Can't PUT to my IHttpHandler, GET works fine
The solution was to set runManagedModulesForWebDavRequests to true in the modules element. My guess is that once you install WebDAV then all PUT requests are associated with it. If you need the PUT to go to your handler, you need to remove the WebDAV module and set this attribute to true.
<modules runManagedModulesForWebDavRequests="true">
...
</modules>
So if you're running into the problem when you use the PUT verb and you have installed WebDAV then hopefully this solution will fix your problem.
You need to set index=False
in to_excel
in order for it to not write the index column out, this semantic is followed in other Pandas IO tools, see http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html and http://pandas.pydata.org/pandas-docs/stable/io.html
The best solution is not to use the same element for column and panel:
<div class="row">
<div class="col-md-3">
<div class="panel" id="gameplay-away-team">Away Team</div>
</div>
<div class="col-md-6">
<div class="panel" id="gameplay-baseball-field">Baseball Field</div>
</div>
<div class="col-md-3">
<div class="panel" id="gameplay-home-team">Home Team</div>
</div>
</div>
and some more styles:
#gameplay-baseball-field {
padding-right: 10px;
padding-left: 10px;
}
You don't really need jQuery for this as there is a Media API that provides you with all you need.
var video = document.getElementById('myVideo');
video.src = 'my_video_' + value + '.ogg';
video.load();
The Media API also contains a load()
method which: "Causes the element to reset and start selecting and loading a new media resource from scratch."
(Ogg isn't the best format to use, as it's only supported by a limited number of browsers. I'd suggest using WebM and MP4 to cover all major browsers - you can use the canPlayType()
function to decide on which one to play).
You can then wait for either the loadedmetadata
or loadeddata
(depending on what you want) events to fire:
video.addEventListener('loadeddata', function() {
// Video is loaded and can be played
}, false);
Here's a snippet to get you going:
theParent = document.getElementById("theParent");
theKid = document.createElement("div");
theKid.innerHTML = 'Are we there yet?';
// append theKid to the end of theParent
theParent.appendChild(theKid);
// prepend theKid to the beginning of theParent
theParent.insertBefore(theKid, theParent.firstChild);
theParent.firstChild
will give us a reference to the first element within theParent
and put theKid
before it.
In Python 3.4 PEP-0443. Single-dispatch generic functions was added.
Here is a short API description from PEP.
To define a generic function, decorate it with the @singledispatch
decorator. Note that the dispatch happens on the type of the first argument. Create your function accordingly:
from functools import singledispatch
@singledispatch
def fun(arg, verbose=False):
if verbose:
print("Let me just say,", end=" ")
print(arg)
To add overloaded implementations to the function, use the register() attribute of the generic function. This is a decorator, taking a type parameter and decorating a function implementing the operation for that type:
@fun.register(int)
def _(arg, verbose=False):
if verbose:
print("Strength in numbers, eh?", end=" ")
print(arg)
@fun.register(list)
def _(arg, verbose=False):
if verbose:
print("Enumerate this:")
for i, elem in enumerate(arg):
print(i, elem)
There's a Windows Explorer extension made by the dude who makes tools for SVN that will at least open a command prompt window.
I haven't tried it yet, so I don't know if it'll do PowerShell, but I wanted to share the love with my Stack Overflow brethren:
In Powershell 3.0 and above there is both a Invoke-WebRequest and Invoke-RestMethod. Curl is actually an alias of Invoke-WebRequest in PoSH. I think using native Powershell would be much more appropriate than curl, but it's up to you :).
Invoke-WebRequest MSDN docs are here: https://technet.microsoft.com/en-us/library/hh849901.aspx?f=255&MSPPError=-2147217396
Invoke-RestMethod MSDN docs are here: https://technet.microsoft.com/en-us/library/hh849971.aspx?f=255&MSPPError=-2147217396
Add a hash change event listener!
window.addEventListener('hashchange', function(e){console.log('hash changed')});
Or, to listen to all URL changes:
window.addEventListener('popstate', function(e){console.log('url changed')});
This is better than something like the code below because only one thing can exist in window.onhashchange and you'll possibly be overwriting someone else's code.
// Bad code example
window.onhashchange = function() {
// Code that overwrites whatever was previously in window.onhashchange
}
This works for me:
pandas.factorize( ['B', 'C', 'D', 'B'] )[0]
Output:
[0, 1, 2, 0]
Yes. Empty or incomplete headers or response body typically caused by broken connections or server side crash can cause 502 errors if accessed via a gateway or proxy.
For more information about the network errors
To fix/install Android USB driver on Windows 7/8 32bit/64bit:
<sdk>\extras\google\usb_driver\
.)If it still doesn't work try changing from MTP to PTP.
The best answer here:
https://www.git-tower.com/learn/git/glossary/origin
In Git, "origin" is a shorthand name for the remote repository that a project was originally cloned from. More precisely, it is used instead of that original repository's URL - and thereby makes referencing much easier.
Other solution: Set initial after creating the form:
form.fields['tank'].initial = 123
$(".first").addClass("second");
If you'd like to add it on an event, you can do so easily as well. An example with the click event:
$(".first").click(function() {
$(this).addClass("second");
});
This question has not enough information to answer. A general solution (depending on your GUI framework): add a mouse event handler that will catch clicks and mouse movements. This will give you your (x, y) coordinates. Next use these coordinates to crop your image.
Instead of creating selector, Best way to create a style.
<style name="AppTheme.BottomBar">
<item name="colorPrimary">@color/colorAccent</item>
</style>
and to change the text size, selected or non selected.
<dimen name="design_bottom_navigation_text_size" tools:override="true">11sp</dimen>
<dimen name="design_bottom_navigation_active_text_size" tools:override="true">12sp</dimen>
Enjoy Android!
A very important place where it is REQUIRED to use the key => value
pair in foreach
loop is to be mentioned. Suppose you would want to add a new/sub-element to an existing item (in another key) in the $features
array. You should do the following:
foreach($features as $key => $feature) {
$features[$key]['new_key'] = 'new value';
}
Instead of this:
foreach($features as $feature) {
$feature['new_key'] = 'new value';
}
The big difference here is that, in the first case you are accessing the array's sub-value via the main array itself with a key to the element which is currently being pointed to by the array pointer.
While in the second (which doesn't work for this purpose) you are assigning the sub-value in the array to a temporary variable $feature
which is unset after each loop iteration.
If not all of your document scrolls, say, when you have a scrolling div
within the document, then the above solutions won't work without adaptations. Here's how to check whether the div's scrollbar has hit the bottom:
$('#someScrollingDiv').on('scroll', function() {
let div = $(this).get(0);
if(div.scrollTop + div.clientHeight >= div.scrollHeight) {
// do the lazy loading here
}
});
Fix for iPhone X/XS screen rotation issue
On iPhone X/XS, a screen rotation will cause the header bar height to use an incorrect value, because the calculation of safe-area-inset-* was not reflecting the new values in time for UI refresh. This bug exists in UIWebView even in the latest iOS 12. A workaround is inserting a 1px top margin and then quickly reversing it, which will trigger safe-area-inset-* to be re-calculated immediately. A somewhat ugly fix but it works if you have to stay with UIWebView for one reason or another.
window.addEventListener("orientationchange", function() {_x000D_
var originalMarginTop = document.body.style.marginTop;_x000D_
document.body.style.marginTop = "1px";_x000D_
setTimeout(function () {_x000D_
document.body.style.marginTop = originalMarginTop;_x000D_
}, 100);_x000D_
}, false);
_x000D_
The purpose of the code is to cause the document.body.style.marginTop to change slightly and then reverse it. It doesn't necessarily have to be "1px". You can pick a value that doesn't cause your UI to flicker but achieves its purpose.
You are getting AttributeError
because you're calling groups
on None
, which hasn't any methods.
regex.search
returning None
means the regex couldn't find anything matching the pattern from supplied string.
when using regex, it is nice to check whether a match has been made:
Result = re.search(SearchStr, htmlString)
if Result:
print Result.groups()
Actually the default value of byte is 0.
I've not looked into this but shooting from the hip I'd say that they dropped command line support in the portable. The reason people don't do much command line stuff in portable applications is that the OS (windows in your case) requires that executables be added to the %path% inclusion list.
If that requirement is not met using command line utilities is rather tedious.
7z -a .
would be
d:\portable\z7\z7 -a c:\to\archive\folder*.*
Typing that out for everything is why GUI's make sense with things like portable apps it (the app) can remember it's own location and handle that stuff for you and if you can't run it you know it's not attached.
If you really want the portable app to contain that though you can always install the full version and pull the required 7z.exe out and put it into the portable folder making sure it's in with the required dll's.
You'll have to set your path when you hit the shell after making sure it's attached.
http://www.redfernplace.com/software-projects/patheditor/ -- a good path editor (down) usefull if you have lots of path information 20+ get's hard to read.
http://www.softpedia.com/get/System/System-Miscellaneous/Path-Editor.shtml -- alternet source for path editor
It's not advisable to modify your system path for temproary "portable" drives though manualy do that by:
set path=%path%;"d:\portable\z7\";
when you run dos cmd.exe or http://sourceforge.net/p/conemu/home/Home/
The other answers address other problems better I'm not going to try..
http://www.codejacked.com/zip-up-files-from-the-command-line/ -- good reference for command line usage of z7 and z7a.
PS: sorry for the necro but I figured it needed a more direct answer to why (even if it's just speculative).
The correct default choice is add InterruptedException to your throws list. An Interrupt indicates that another thread wishes your thread to end. The reason for this request is not made evident and is entirely contextual, so if you don't have any additional knowledge you should assume it's just a friendly shutdown, and anything that avoids that shutdown is a non-friendly response.
Java will not randomly throw InterruptedException's, all advice will not affect your application but I have run into a case where developer's following the "swallow" strategy became very inconvenient. A team had developed a large set of tests and used Thread.Sleep a lot. Now we started to run the tests in our CI server, and sometimes due to defects in the code would get stuck into permanent waits. To make the situation worse, when attempting to cancel the CI job it never closed because the Thread.Interrupt that was intended to abort the test did not abort the job. We had to login to the box and manually kill the processes.
So long story short, if you simply throw the InterruptedException you are matching the default intent that your thread should end. If you can't add InterruptedException to your throw list, I'd wrap it in a RuntimeException.
There is a very rational argument to be made that InterruptedException should be a RuntimeException itself, since that would encourage a better "default" handling. It's not a RuntimeException only because the designers stuck to a categorical rule that a RuntimeException should represent an error in your code. Since an InterruptedException does not arise directly from an error in your code, it's not. But the reality is that often an InterruptedException arises because there is an error in your code, (i.e. endless loop, dead-lock), and the Interrupt is some other thread's method for dealing with that error.
If you know there is rational cleanup to be done, then do it. If you know a deeper cause for the Interrupt, you can take on more comprehensive handling.
So in summary your choices for handling should follow this list:
Here is how to build a function that returns a result set that can be queried as if it were a table:
SQL> create type emp_obj is object (empno number, ename varchar2(10));
2 /
Type created.
SQL> create type emp_tab is table of emp_obj;
2 /
Type created.
SQL> create or replace function all_emps return emp_tab
2 is
3 l_emp_tab emp_tab := emp_tab();
4 n integer := 0;
5 begin
6 for r in (select empno, ename from emp)
7 loop
8 l_emp_tab.extend;
9 n := n + 1;
10 l_emp_tab(n) := emp_obj(r.empno, r.ename);
11 end loop;
12 return l_emp_tab;
13 end;
14 /
Function created.
SQL> select * from table (all_emps);
EMPNO ENAME
---------- ----------
7369 SMITH
7499 ALLEN
7521 WARD
7566 JONES
7654 MARTIN
7698 BLAKE
7782 CLARK
7788 SCOTT
7839 KING
7844 TURNER
7902 FORD
7934 MILLER
There is a rule in Python programming called "it is Easier to Ask for Forgiveness than for Permission" (in short: EAFP). It means that you should catch exceptions instead of checking values for validity.
Thus, try the following:
try:
qByUser = byUsrUrlObj.read()
qUserData = json.loads(qByUser).decode('utf-8')
questionSubjs = qUserData["all"]["questions"]
except ValueError: # includes simplejson.decoder.JSONDecodeError
print 'Decoding JSON has failed'
EDIT: Since simplejson.decoder.JSONDecodeError
actually inherits from ValueError
(proof here), I simplified the catch statement by just using ValueError
.
I had a similar issue and based on above suggestions I first added "super.setIntegerProperty("loadUrlTimeoutValue", 70000);" but that did not help. So I tried Project -> Clean, that worked and I can launch the app now !
Avinash...
You need to get the total contents size of each directory recursively to output. Also, you need to specify that the contents you're grabbing to measure are not directories, or you risk errors (as directories do not have a Length
parameter).
Here's your script modified for the output you're looking for:
$colItems = Get-ChildItem $startFolder | Where-Object {$_.PSIsContainer -eq $true} | Sort-Object
foreach ($i in $colItems)
{
$subFolderItems = Get-ChildItem $i.FullName -recurse -force | Where-Object {$_.PSIsContainer -eq $false} | Measure-Object -property Length -sum | Select-Object Sum
$i.FullName + " -- " + "{0:N2}" -f ($subFolderItems.sum / 1MB) + " MB"
}
C++17 (All references are from the final working draft of CPP17 - n4659)
Sequence Containers
vector
: The functions insert
, emplace_back
, emplace
, push_back
cause reallocation if the new size is greater than the old capacity. Reallocation invalidates all the references, pointers, and iterators referring to the elements in the sequence. If no reallocation
happens, all the iterators and references before the insertion point remain valid. [26.3.11.5/1]
With respect to the reserve
function, reallocation invalidates all the references, pointers, and iterators referring to the elements in the sequence. No reallocation shall take place during insertions that happen after a call to reserve()
until the time when an insertion would make the size of the vector greater than the value of capacity()
. [26.3.11.3/6]
deque
: An insertion in the middle of the deque invalidates all the iterators and references to elements of the deque. An insertion at either end of the deque invalidates all the iterators to the deque, but has no effect on the validity of references to elements of the deque. [26.3.8.4/1]
list
: Does not affect the validity of iterators and references. If an exception is thrown there are no effects. [26.3.10.4/1].
The insert
, emplace_front
, emplace_back
, emplace
, push_front
, push_back
functions are covered under this rule.
forward_list
: None of the overloads of insert_after
shall affect the validity of iterators and references [26.3.9.5/1]
array
: As a rule, iterators to an array are never invalidated throughout the lifetime of the array. One should take note, however, that during swap, the iterator will continue to point to the same array element, and will thus change its value.
Associative Containers
All Associative Containers
: The insert
and emplace
members shall not affect the validity of iterators and references to the container [26.2.6/9]Unordered Associative Containers
All Unordered Associative Containers
: Rehashing invalidates iterators, changes ordering between elements, and changes which buckets elements appear in, but does not invalidate pointers or references to elements. [26.2.7/9]
The insert
and emplace
members shall not affect the validity of references to container elements, but may invalidate all iterators to the container. [26.2.7/14]
The insert
and emplace
members shall not affect the validity of iterators if (N+n) <= z * B
, where N
is the number of elements in the container prior to the insert operation, n
is the number of elements inserted, B
is the container’s bucket count, and z
is the container’s maximum load factor. [26.2.7/15]
All Unordered Associative Containers
: In case of a merge operation (e.g., a.merge(a2)
), iterators referring to the transferred elements and all iterators referring to a
will be invalidated, but iterators to elements remaining in a2
will remain valid. (Table 91 — Unordered associative container requirements)
Container Adaptors
stack
: inherited from underlying containerqueue
: inherited from underlying containerpriority_queue
: inherited from underlying containerSequence Containers
vector
: The functions erase
and pop_back
invalidate iterators and references at or after the point of the erase. [26.3.11.5/3]
deque
: An erase operation that erases the last element of a deque
invalidates only the past-the-end iterator and all iterators and references to the erased elements. An erase operation that erases the first element of a deque
but not the last element invalidates only iterators and references to the erased elements. An erase operation that erases neither the first element nor the last element of a deque
invalidates the past-the-end iterator and all iterators and references to all the elements of the deque
.
[ Note: pop_front
and pop_back
are erase operations. —end note ] [26.3.8.4/4]
list
: Invalidates only the iterators and references to the erased elements. [26.3.10.4/3]. This applies to erase
, pop_front
, pop_back
, clear
functions.
remove
and remove_if
member functions: Erases all the elements in the list referred by a list iterator i
for which the following conditions hold: *i == value
, pred(*i) != false
. Invalidates only the iterators and references to the erased elements [26.3.10.5/15].
unique
member function - Erases all but the first element from every consecutive group of equal elements referred to by the iterator i
in the range [first + 1, last)
for which *i == *(i-1)
(for the version of unique with no arguments) or pred(*i, *(i - 1))
(for the version of unique with a predicate argument) holds. Invalidates only the iterators and references to the erased elements. [26.3.10.5/19]
forward_list
: erase_after
shall invalidate only iterators and references to the erased elements. [26.3.9.5/1].
remove
and remove_if
member functions - Erases all the elements in the list referred by a list iterator i for which the following conditions hold: *i == value
(for remove()
), pred(*i)
is true (for remove_if()
). Invalidates only the iterators and references to the erased elements. [26.3.9.6/12].
unique
member function - Erases all but the first element from every consecutive group of equal elements referred to by the iterator i in the range [first + 1, last) for which *i == *(i-1)
(for the version with no arguments) or pred(*i, *(i - 1))
(for the version with a predicate argument) holds. Invalidates only the iterators and references to the erased elements. [26.3.9.6/16]
All Sequence Containers
: clear
invalidates all references, pointers, and iterators referring to the elements of a and may invalidate the past-the-end iterator (Table 87 — Sequence container requirements). But for forward_list
, clear
does not invalidate past-the-end iterators. [26.3.9.5/32]
All Sequence Containers
: assign
invalidates all references, pointers and
iterators referring to the elements of the container. For vector
and deque
, also invalidates the past-the-end iterator. (Table 87 — Sequence container requirements)
Associative Containers
All Associative Containers
: The erase
members shall invalidate only iterators and references to the erased elements [26.2.6/9]
All Associative Containers
: The extract
members invalidate only iterators to the removed element; pointers and references to the removed element remain valid [26.2.6/10]
Container Adaptors
stack
: inherited from underlying containerqueue
: inherited from underlying containerpriority_queue
: inherited from underlying containerGeneral container requirements relating to iterator invalidation:
Unless otherwise specified (either explicitly or by defining a function in terms of other functions), invoking a container member function or passing a container as an argument to a library function shall not invalidate iterators to, or change the values of, objects within that container. [26.2.1/12]
no swap()
function invalidates any references, pointers, or iterators referring to the elements of the containers being swapped. [ Note: The end() iterator does not refer to any element, so it may be invalidated. —end note ] [26.2.1/(11.6)]
As examples of the above requirements:
transform
algorithm: The op
and binary_op
functions shall not invalidate iterators or subranges, or modify elements in the ranges [28.6.4/1]
accumulate
algorithm: In the range [first, last], binary_op
shall neither modify elements nor invalidate iterators or subranges [29.8.2/1]
reduce
algorithm: binary_op shall neither invalidate iterators or subranges, nor modify elements in the range [first, last]. [29.8.3/5]
and so on...
if you don't want to use break you just increase value of I in such a way that it make iteration condition false and loop will not execute on next iteration.
for(int i = 0; i < list.Count; i++){
if(i == 5)
i = list.Count; //it will make "i<list.Count" false and loop will exit
}
There are two ways to sum of a column
dataset = pd.read_csv("data.csv")
1: sum(dataset.Column_name)
2: dataset['Column_Name'].sum()
If there is any issue in this the please correct me..
Your code was compiled with Java 8.
Either compile your code with an older JDK (compliance level) or run it on a Java 8 JRE.
Hope this helps...
String.toCharArray()
creates new char array, means allocation of memory of string length, then copies original char array of string using System.arraycopy()
and then returns this copy to caller.
String.charAt() returns character at position i
from original copy, that's why String.charAt()
will be faster than String.toCharArray()
.
Although, String.toCharArray()
returns copy and not char from original String array, where String.charAt()
returns character from original char array.
Code below returns value at the specified index of this string.
public char charAt(int index) {
if ((index < 0) || (index >= value.length)) {
throw new StringIndexOutOfBoundsException(index);
}
return value[index];
}
code below returns a newly allocated character array whose length is the length of this string
public char[] toCharArray() {
// Cannot use Arrays.copyOf because of class initialization order issues
char result[] = new char[value.length];
System.arraycopy(value, 0, result, 0, value.length);
return result;
}
userIdeaUC = userIdea.substring(0, 1).toUpperCase() + userIdea.length() > 1 ? userIdea.substring(1) : "";
or
userIdeaUC = userIdea.substring(0, 1).toUpperCase();
if(userIdea.length() > 1)
userIdeaUC += userIdea.substring(1);
Here is a method using a lookup table of thresholds and associated colours to map the colours to the variable of interest.
# make a grid 'Grd' of points and number points for side of square 'GrdD'
Grd <- expand.grid(seq(0.5,400.5,10),seq(0.5,400.5,10))
GrdD <- length(unique(Grd$Var1))
# Add z-values to the grid points
Grd$z <- rnorm(length(Grd$Var1), mean = 10, sd =2)
# Make a vector of thresholds 'Brks' to colour code z
Brks <- c(seq(0,18,3),Inf)
# Make a vector of labels 'Lbls' for the colour threhsolds
Lbls <- Lbls <- c('0-3','3-6','6-9','9-12','12-15','15-18','>18')
# Make a vector of colours 'Clrs' for to match each range
Clrs <- c("grey50","dodgerblue","forestgreen","orange","red","purple","magenta")
# Make up lookup dataframe 'LkUp' of the lables and colours
LkUp <- data.frame(cbind(Lbls,Clrs),stringsAsFactors = FALSE)
# Add a new variable 'Lbls' the grid dataframe mapping the labels based on z-value
Grd$Lbls <- as.character(cut(Grd$z, breaks = Brks, labels = Lbls))
# Add a new variable 'Clrs' to the grid dataframe based on the Lbls field in the grid and lookup table
Grd <- merge(Grd,LkUp, by.x = 'Lbls')
# Plot the grid using the 'Clrs' field for the colour of each point
plot(Grd$Var1,
Grd$Var2,
xlim = c(0,400),
ylim = c(0,400),
cex = 1.0,
col = Grd$Clrs,
pch = 20,
xlab = 'mX',
ylab = 'mY',
main = 'My Grid',
axes = FALSE,
labels = FALSE,
las = 1
)
axis(1,seq(0,400,100))
axis(2,seq(0,400,100),las = 1)
box(col = 'black')
legend("topleft", legend = Lbls, fill = Clrs, title = 'Z')
In my case one of my settings, 'CORS_ORIGIN_WHITELIST' was set in the settings.py file but was not available in my .env file. So I'll suggest that you check your settings, especially those linked to .env
Try this simple solution to convert file to base64 string
String base64String = imageFileToByte(file);
public String imageFileToByte(File file){
Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
byte[] b = baos.toByteArray();
return Base64.encodeToString(b, Base64.DEFAULT);
}
typeperf
gives me issues when it randomly doesn't work on some computers (Error: No valid counters.
) or if the account has insufficient rights. Otherwise, here is a way to extract just the value from its output. It still needs rounding though:
@for /f "delims=, tokens=2" %p in ('typeperf "\Processor(_Total)\% Processor Time" -sc 3 ^| find ":"') do @echo %~p%
Powershell has two cmdlets to get the percent utilization for all CPUs: Get-Counter
(preferred) or Get-WmiObject
:
Powershell "Get-Counter '\Processor(*)\% Processor Time' | Select -Expand Countersamples | Select InstanceName, CookedValue"
Or,
Powershell "Get-WmiObject Win32_PerfFormattedData_PerfOS_Processor | Select Name, PercentProcessorTime"
To get the overall CPU load with formatted output exactly like the question:
Powershell "[string][int](Get-Counter '\Processor(*)\% Processor Time').Countersamples[0].CookedValue + '%'"
Or,
Powershell "gwmi Win32_PerfFormattedData_PerfOS_Processor | Select -First 1 | %{'{0}%' -f $_.PercentProcessorTime}"
Extract the jar, and put it somewhere in your Java project (usually under a "lib" subdirectory).
Right click the project, open its preferences, go for Java build path, and then the Libraries tab. You can add the library there with "add a jar".
If your jar is not open source, you may want to store it elsewhere and connect to it as an external jar.
The following code works:
find /tmp | perl -ne 'print if /[^[:ascii:]]/'
Replace /tmp
with the name of the directory you want to search through.
In my case there were some vstest processes running (with various names but all containing the string vstest). I had to terminate them in taskmgr.
Java is supposed to clear the heap space for you when all of the objects are no longer referenced. It won't generally release it back to the OS though, it will keep that memory for it's own internal reuse. Maybe check to see if you have some arrays which are not being cleared or something.
You can use TimerTask for Cronjobs.
Main.java
public class Main{
public static void main(String[] args){
Timer t = new Timer();
MyTask mTask = new MyTask();
// This task is scheduled to run every 10 seconds
t.scheduleAtFixedRate(mTask, 0, 10000);
}
}
MyTask.java
class MyTask extends TimerTask{
public MyTask(){
//Some stuffs
}
@Override
public void run() {
System.out.println("Hi see you after 10 seconds");
}
}
Alternative You can also use ScheduledExecutorService.
I go with Mark Longair's solution and comments and recommend anyone reads those before acting, but I'd suggest the emphasis should be on
git branch -f <branchname> <commit>
Here is a scenario where I have needed to do this.
Develop on the wrong branch and hence need to reset it.
Cleanly develop and release some software.
Mistake: Accidentally stay on the release branch while developing further.
"OH NO! I accidentally developed on the release branch." The workspace is maybe cluttered with half changed files that represent work-in-progress and we really don't want to touch and mess with. We'd just like git to flip a few pointers to keep track of the current state and put that release branch back how it should be.
Create a branch for the development that is up to date holding the work committed so far and switch to it.
git branch development
git checkout development
Now we are in the problem situation and need its solution! Rectify the mistake (of taking the release branch forward with the development) and put the release branch back how it should be.
Correct the release branch to point back to the last real release.
git branch -f release release2
The release branch is now correct again, like this ...
git push -f <remote> <branch>
is well described in another thread, though the word "overwrite" in the title is misleading.
Force "git push" to overwrite remote files
This works both ways and it is simple and clean
JavaScript
var app = angular.module("app");
app.controller("SamePaswordController", function () {
this.password;
this.confirm;
this.save = function () {
alert("Saved!");
};
}
app.directive("match", function () {
return {
restrict:"A",
require:"ngModel",
link: function(scope, element, attrs, ctrl) {
function matchValidator(value) {
scope.$watch(attrs.match, function(newValue, oldValue) {
var isValid = value === scope.$eval(attrs.match);
ctrl.$setValidity('match', isValid);
});
return value;
}
ctrl.$parsers.push(matchValidator);
}
};
});
HTML: note the match directive
<form name="regForm" ng-controller="SamePaswordController as regCtrl"
ng-submit="regForm.$valid && regCtrl.save()" novalidate>
<input name="password" ng-model="regCtrl.password"
type="password" required placeholder="Password"/>
<input name="confirm" ng-model="regCtrl.confirm" match="regCtrl.password"
type="password" required placeholder="Confirm password"/>
<div> regForm is valid:{{regForm.$valid}}</div>
<input type="submit" value="Save"/>
</form>
You can clone the repo with this example https://github.com/rogithub/roangularjs
NOT SUPPORTED BY IE
More info here: Can I Use?
.container {_x000D_
overflow: hidden;_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
}_x000D_
_x000D_
.container img {_x000D_
object-fit: cover;_x000D_
width: 100%;_x000D_
min-height: 100%;_x000D_
}
_x000D_
<div class='container'>_x000D_
<img src='http://i.imgur.com/H9lpVkZ.jpg' />_x000D_
</div>
_x000D_
Since you didn't specify what server-side scripting method you're using, I'll give you an example that works for Python, using CherryPy (although it may be useful for other contexts, too):
<button type="submit" name="register">Create a new account</button>
<button type="submit" name="login">Log into your account</button>
Rather than using the value to determine which button was pressed, you can use the name (with the <button>
tag instead of <input>
). That way, if your buttons happen to have the same text, it won't cause problems. The names of all form items, including buttons, are sent as part of the URL. In CherryPy, each of those is an argument for a method that does the server-side code. So, if your method just has **kwargs
for its parameter list (instead of tediously typing out every single name of each form item) then you can check to see which button was pressed like this:
if "register" in kwargs:
pass #Do the register code
elif "login" in kwargs:
pass #Do the login code
Just a notice for a sharing hosting server or added on domains =
For your settings to work you must have a different save session dir for added domain by using php_value session.save_path folderA/sessionsA
.
So create a folder to your root server, not into the public_html
and not to be publicity accessed from outside. For my cpanel/server worked fine the folder permissions 0700
. Give a try...
# Session timeout, 2628000 sec = 1 month, 604800 = 1 week, 57600 = 16 hours, 86400 = 1 day
ini_set('session.save_path', '/home/server/.folderA_sessionsA');
ini_set('session.gc_maxlifetime', 57600);
ini_set('session.cookie_lifetime', 57600);
# session.cache_expire is in minutes unlike the other settings above
ini_set('session.cache_expire', 960);
ini_set('session.name', 'MyDomainA');
before session_start();
or put this in your .htaccess
file.
php_value session.save_path /home/server/.folderA_sessionsA
php_value session.gc_maxlifetime 57600
php_value session.cookie_lifetime 57600
php_value session.cache_expire 57600
php_value session.name MyDomainA
After many researching and testing this worked fine for shared cpanel/php7 server. Many thanks to: NoiS
try os.path.exists
this will check for the path and return True
if exists and False
if not.
Because Python is dynamically typed, the types of the objects don't matter in many cases. It's a better idea to accept anything.
To demonstrate what I mean, this tree class will accept anything for its two branches:
class BinaryTree:
def __init__(self, left, right):
self.left, self.right = left, right
And it could be used like this:
branch1 = BinaryTree(1,2)
myitem = MyClass()
branch2 = BinaryTree(myitem, None)
tree = BinaryTree(branch1, branch2)
There's an inflection library in the package index that can handle these things for you. In this case, you'd be looking for inflection.underscore()
:
>>> inflection.underscore('CamelCase')
'camel_case'
The Servlet 3.0 spec doesn't seem to provide a hint on how a container should order filters that have been declared via annotations. It is clear how about how to order filters via their declaration in the web.xml file, though.
Be safe. Use the web.xml file order filters that have interdependencies. Try to make your filters all order independent to minimize the need to use a web.xml file.
IBAction and IBOutlets are used to hook up your interface made in Interface Builder with your controller. If you wouldn't use Interface Builder and build your interface completely in code, you could make a program without using them. But in reality most of us use Interface Builder, once you want to get some interactivity going in your interface, you will have to use IBActions and IBoutlets.
I had almost precisely the same error, and was able to completely fix it simply by running:
gem install bundler
It's possible your bundler installation is corrupt or missing - that's what happened in my case. Note that if the above fails you can try:
sudo gem install bundler
...but generally you can do it without sudo.
Use elevation
instead of zIndex
for android devices
elevatedElement: {
zIndex: 3, // works on ios
elevation: 3, // works on android
}
This worked fine for me!
I read all the comments and suggestions. 500 - HTTP ERROR CODE represents internal server error.
Reasons for this error:
.env
file not found on your root directoryFix:
find /path/to/your/root/dir/ -type f -exec chmod 644 {} \;
find /path/to/your/root/dir/ -type d -exec chmod 755 {} \;
chown -R www-data:www-data /path/to/your/root/dir/
chgrp -R www-data storage bootstrap/cache
chmod -R ug+rwx storage bootstrap/cache
touch .env
and paste your environment variables and then run php artisan key:generate
php artisan cache:clear
php artisan config:clear
composer dump-autoload
apt-get install php7.2-[extension-name]
.env
file. And grant permissions to the database user for that database.These are some common problem you likely going to face when deploying your laravel app and once you start getting all these commands, I suggest you to make a script which will save your time.
http://www.kanzaki.com/docs/ical/ has a slightly more readable version of the older spec. It helps as a starting point - many things are still the same.
Also on my site, I have
.ics
over the last few years. In particular, you may find this repeating events 'cheatsheet' to be useful..ics
areas that need careful handling:
For me, best and simplest way, Bootply http://www.bootply.com/lxa0FF9yhw#
First include Bootstrap to your project
Then include javascript file in which you write this code:
$.fn.pageMe = function(opts){
var $this = this,
defaults = {
perPage: 7,
showPrevNext: false,
hidePageNumbers: false
},
settings = $.extend(defaults, opts);
var listElement = $this;
var perPage = settings.perPage;
var children = listElement.children();
var pager = $('.pager');
if (typeof settings.childSelector!="undefined") {
children = listElement.find(settings.childSelector);
}
if (typeof settings.pagerSelector!="undefined") {
pager = $(settings.pagerSelector);
}
var numItems = children.size();
var numPages = Math.ceil(numItems/perPage);
pager.data("curr",0);
if (settings.showPrevNext){
$('<li><a href="#" class="prev_link">«</a></li>').appendTo(pager);
}
var curr = 0;
while(numPages > curr && (settings.hidePageNumbers==false)){
$('<li><a href="#" class="page_link">'+(curr+1)+'</a></li>').appendTo(pager);
curr++;
}
if (settings.showPrevNext){
$('<li><a href="#" class="next_link">»</a></li>').appendTo(pager);
}
pager.find('.page_link:first').addClass('active');
pager.find('.prev_link').hide();
if (numPages<=1) {
pager.find('.next_link').hide();
}
pager.children().eq(1).addClass("active");
children.hide();
children.slice(0, perPage).show();
pager.find('li .page_link').click(function(){
var clickedPage = $(this).html().valueOf()-1;
goTo(clickedPage,perPage);
return false;
});
pager.find('li .prev_link').click(function(){
previous();
return false;
});
pager.find('li .next_link').click(function(){
next();
return false;
});
function previous(){
var goToPage = parseInt(pager.data("curr")) - 1;
goTo(goToPage);
}
function next(){
goToPage = parseInt(pager.data("curr")) + 1;
goTo(goToPage);
}
function goTo(page){
var startAt = page * perPage,
endOn = startAt + perPage;
children.css('display','none').slice(startAt, endOn).show();
if (page>=1) {
pager.find('.prev_link').show();
}
else {
pager.find('.prev_link').hide();
}
if (page<(numPages-1)) {
pager.find('.next_link').show();
}
else {
pager.find('.next_link').hide();
}
pager.data("curr",page);
pager.children().removeClass("active");
pager.children().eq(page+1).addClass("active");
}
};
You need to give an id to the tbody of your table and to add a 'div' after the table for the pagination
<table class="table" id="myTable">
<thead>
<tr>
<th>...</th>
</tr>
</thead>
<tbody id="myTableBody">
</tbody>
</table>
<div class="col-md-12 text-center">
<ul class="pagination pagination-lg pager" id="myPager"></ul>
</div>
When your table's data is loaded, just call this
$('#myTableBody').pageMe({pagerSelector:'#myPager',showPrevNext:true,hidePageNumbers:false,perPage:4});
where the 'perPage' value is to set how many elements per page you want to have.
Have you noticed that you don't get the error if you run
python ./script.py
instead of
python script.py
This is because sys.argv[0]
will read ./script.py
in the former case, which gives os.path.dirname
something to work with. When you don't specify a path, sys.argv[0]
reads simply script.py
, and os.path.dirname
cannot determine a path.
STATEMENT:
A Statement is a action or a command that does something. Ex: If-Else,Loops..etc
val a: Int = 5
If(a>5) print("Hey!") else print("Hi!")
EXPRESSION:
A Expression is a combination of values, operators and literals which yields something.
val a: Int = 5 + 5 #yields 10
Thanks RBarry. I'm putting together an IP block allocation system and storing as binary is the only way to go.
I'm storing the CIDR representation (ex: 192.168.1.0/24) of the IP block in a varchar field, and using 2 calculated fields to hold the binary form of the start and end of the block. From there, I can run fast queries to see if a given block as already been allocated or is free to assign.
I modified your function to calculate the ending IP Address like so:
CREATE FUNCTION dbo.fnDisplayIPv4End(@block AS VARCHAR(18)) RETURNS BINARY(4)
AS
BEGIN
DECLARE @bin AS BINARY(4)
DECLARE @ip AS VARCHAR(15)
DECLARE @size AS INT
SELECT @ip = Left(@block, Len(@block)-3)
SELECT @size = Right(@block, 2)
SELECT @bin = CAST( CAST( PARSENAME( @ip, 4 ) AS INTEGER) AS BINARY(1))
+ CAST( CAST( PARSENAME( @ip, 3 ) AS INTEGER) AS BINARY(1))
+ CAST( CAST( PARSENAME( @ip, 2 ) AS INTEGER) AS BINARY(1))
+ CAST( CAST( PARSENAME( @ip, 1 ) AS INTEGER) AS BINARY(1))
SELECT @bin = CAST(@bin + POWER(2, 32-@size) AS BINARY(4))
RETURN @bin
END;
go
An easy, loop-free alternative is to use the horizontalalignment
Text property as a keyword argument to xticks
[1]. In the below, at the commented line, I've forced the xticks
alignment to be "right".
n=5
x = np.arange(n)
y = np.sin(np.linspace(-3,3,n))
xlabels = ['Long ticklabel %i' % i for i in range(n)]
fig, ax = plt.subplots()
ax.plot(x,y, 'o-')
plt.xticks(
[0,1,2,3,4],
["this label extends way past the figure's left boundary",
"bad motorfinger", "green", "in the age of octopus diplomacy", "x"],
rotation=45,
horizontalalignment="right") # here
plt.show()
(yticks
already aligns the right edge with the tick by default, but for xticks
the default appears to be "center".)
[1] You find that described in the xticks documentation if you search for the phrase "Text properties".
why dont you try something very simple?
use psexec with command 'shutdown /r /f /t 0' and a PC list from CMD.
Don't forget the padding and margins...
jQuery.fn.slideLeftHide = function(speed, callback) {
this.animate({
width: "hide",
paddingLeft: "hide",
paddingRight: "hide",
marginLeft: "hide",
marginRight: "hide"
}, speed, callback);
}
jQuery.fn.slideLeftShow = function(speed, callback) {
this.animate({
width: "show",
paddingLeft: "show",
paddingRight: "show",
marginLeft: "show",
marginRight: "show"
}, speed, callback);
}
With the speed/callback arguments added, it's a complete drop-in replacement for slideUp()
and slideDown()
.
Keystore name: "debug.keystore"
Keystore password: "android"
Key alias: "androiddebugkey"
Key password: "android"
I use this information and successfully generate Signed APK.
@andresh For me locationChangeSuccess worked instead of routeChangeSuccess.
//Go back to the previous stage with this back() call
var history = [];
$rootScope.$on('$locationChangeSuccess', function() {
history.push($location.$$path);
});
$rootScope.back = function () {
var prevUrl = history.length > 1 ? history.splice(-2)[0] : "/";
$location.path(prevUrl);
history = []; //Delete history array after going back
};
In React Native , This worked for me
name = "hi \n\ruser"
name.replace( /[\r\n]+/gm, ""); // hi user
There are a few solutions to your problem.
The way with MySQLi would be like this:
<?php
$connection = mysqli_connect('localhost', 'username', 'password', 'database');
To run database queries is also simple and nearly identical with the old way:
<?php
// Old way
mysql_query('CREATE TEMPORARY TABLE `table`', $connection);
// New way
mysqli_query($connection, 'CREATE TEMPORARY TABLE `table`');
Turn off all deprecated warnings including them from mysql_*:
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
The Exact file and line location which needs to be replaced is "/System/Startup.php > line: 2 " error_reporting(E_All); replace with error_reporting(E_ALL ^ E_DEPRECATED);
You could go a step further and break into the puppet code using a breakpoint.
http://logicminds.github.io/blog/2017/04/25/break-into-your-puppet-code/
This would only work with puppet apply or using a rspec test. Or you can manually type your code into the debugger console. Note: puppet still needs to know where your module code is at if you haven't set already.
gem install puppet puppet-debugger
puppet module install nwops/debug
cat > test.pp <<'EOF'
$var1 = 'test'
debug::break()
EOF
Should show something like.
puppet apply test.pp
From file: test.pp
1: $var1 = 'test'
2: # add 'debug::break()' where you want to stop in your code
=> 3: debug::break()
1:>> $var1
=> "test"
2:>>
This should be fairly straightforward in the gimp http://gimp.org/
First make sure your image is RGB (not indexed color) then use the "color to alpha" feature to turn the clubs/diamonds clear, then fill or set the background or whatever to get the color you want.
This will re-size any image using the best quality with support for 32bpp with alpha. The new image will have the original image centered inside the new one at the original aspect ratio.
#Region " ResizeImage "
Public Overloads Shared Function ResizeImage(SourceImage As Drawing.Image, TargetWidth As Int32, TargetHeight As Int32) As Drawing.Bitmap
Dim bmSource = New Drawing.Bitmap(SourceImage)
Return ResizeImage(bmSource, TargetWidth, TargetHeight)
End Function
Public Overloads Shared Function ResizeImage(bmSource As Drawing.Bitmap, TargetWidth As Int32, TargetHeight As Int32) As Drawing.Bitmap
Dim bmDest As New Drawing.Bitmap(TargetWidth, TargetHeight, Drawing.Imaging.PixelFormat.Format32bppArgb)
Dim nSourceAspectRatio = bmSource.Width / bmSource.Height
Dim nDestAspectRatio = bmDest.Width / bmDest.Height
Dim NewX = 0
Dim NewY = 0
Dim NewWidth = bmDest.Width
Dim NewHeight = bmDest.Height
If nDestAspectRatio = nSourceAspectRatio Then
'same ratio
ElseIf nDestAspectRatio > nSourceAspectRatio Then
'Source is taller
NewWidth = Convert.ToInt32(Math.Floor(nSourceAspectRatio * NewHeight))
NewX = Convert.ToInt32(Math.Floor((bmDest.Width - NewWidth) / 2))
Else
'Source is wider
NewHeight = Convert.ToInt32(Math.Floor((1 / nSourceAspectRatio) * NewWidth))
NewY = Convert.ToInt32(Math.Floor((bmDest.Height - NewHeight) / 2))
End If
Using grDest = Drawing.Graphics.FromImage(bmDest)
With grDest
.CompositingQuality = Drawing.Drawing2D.CompositingQuality.HighQuality
.InterpolationMode = Drawing.Drawing2D.InterpolationMode.HighQualityBicubic
.PixelOffsetMode = Drawing.Drawing2D.PixelOffsetMode.HighQuality
.SmoothingMode = Drawing.Drawing2D.SmoothingMode.AntiAlias
.CompositingMode = Drawing.Drawing2D.CompositingMode.SourceOver
.DrawImage(bmSource, NewX, NewY, NewWidth, NewHeight)
End With
End Using
Return bmDest
End Function
#End Region
Here's a workaround for Binding Columns in the DataGrid. Since the Columns property is ReadOnly, like everyone noticed, I made an Attached Property called BindableColumns which updates the Columns in the DataGrid everytime the collection changes through the CollectionChanged event.
If we have this Collection of DataGridColumn's
public ObservableCollection<DataGridColumn> ColumnCollection
{
get;
private set;
}
Then we can bind BindableColumns to the ColumnCollection like this
<DataGrid Name="dataGrid"
local:DataGridColumnsBehavior.BindableColumns="{Binding ColumnCollection}"
AutoGenerateColumns="False"
...>
The Attached Property BindableColumns
public class DataGridColumnsBehavior
{
public static readonly DependencyProperty BindableColumnsProperty =
DependencyProperty.RegisterAttached("BindableColumns",
typeof(ObservableCollection<DataGridColumn>),
typeof(DataGridColumnsBehavior),
new UIPropertyMetadata(null, BindableColumnsPropertyChanged));
private static void BindableColumnsPropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)
{
DataGrid dataGrid = source as DataGrid;
ObservableCollection<DataGridColumn> columns = e.NewValue as ObservableCollection<DataGridColumn>;
dataGrid.Columns.Clear();
if (columns == null)
{
return;
}
foreach (DataGridColumn column in columns)
{
dataGrid.Columns.Add(column);
}
columns.CollectionChanged += (sender, e2) =>
{
NotifyCollectionChangedEventArgs ne = e2 as NotifyCollectionChangedEventArgs;
if (ne.Action == NotifyCollectionChangedAction.Reset)
{
dataGrid.Columns.Clear();
foreach (DataGridColumn column in ne.NewItems)
{
dataGrid.Columns.Add(column);
}
}
else if (ne.Action == NotifyCollectionChangedAction.Add)
{
foreach (DataGridColumn column in ne.NewItems)
{
dataGrid.Columns.Add(column);
}
}
else if (ne.Action == NotifyCollectionChangedAction.Move)
{
dataGrid.Columns.Move(ne.OldStartingIndex, ne.NewStartingIndex);
}
else if (ne.Action == NotifyCollectionChangedAction.Remove)
{
foreach (DataGridColumn column in ne.OldItems)
{
dataGrid.Columns.Remove(column);
}
}
else if (ne.Action == NotifyCollectionChangedAction.Replace)
{
dataGrid.Columns[ne.NewStartingIndex] = ne.NewItems[0] as DataGridColumn;
}
};
}
public static void SetBindableColumns(DependencyObject element, ObservableCollection<DataGridColumn> value)
{
element.SetValue(BindableColumnsProperty, value);
}
public static ObservableCollection<DataGridColumn> GetBindableColumns(DependencyObject element)
{
return (ObservableCollection<DataGridColumn>)element.GetValue(BindableColumnsProperty);
}
}
This method helped me doing this task
document.forms['YourFormNameHere'].elements['NameofFormField'].value = "YourValue"
document.forms['YourFormNameHere'].submit();
They are both going to have the same effect.
However, as pointed out in the comments: $(window).scrollTop()
is supported by more web browsers than $('html').scrollTop()
.
If you know in advance which fields to use to make the comparison, then other people gave right answers.
What you may be interested in is to sort your collection in case you don't know at compile-time which criteria to apply.
Imagine you have a program dealing with cities:
protected Set<City> cities;
(...)
Field temperatureField = City.class.getDeclaredField("temperature");
Field numberOfInhabitantsField = City.class.getDeclaredField("numberOfInhabitants");
Field rainfallField = City.class.getDeclaredField("rainfall");
program.showCitiesSortBy(temperatureField, numberOfInhabitantsField, rainfallField);
(...)
public void showCitiesSortBy(Field... fields) {
List<City> sortedCities = new ArrayList<City>(cities);
Collections.sort(sortedCities, new City.CityMultiComparator(fields));
for (City city : sortedCities) {
System.out.println(city.toString());
}
}
where you can replace hard-coded field names by field names deduced from a user request in your program.
In this example, City.CityMultiComparator<City>
is a static nested class of class City
implementing Comparator
:
public static class CityMultiComparator implements Comparator<City> {
protected List<Field> fields;
public CityMultiComparator(Field... orderedFields) {
fields = new ArrayList<Field>();
for (Field field : orderedFields) {
fields.add(field);
}
}
@Override
public int compare(City cityA, City cityB) {
Integer score = 0;
Boolean continueComparison = true;
Iterator itFields = fields.iterator();
while (itFields.hasNext() && continueComparison) {
Field field = itFields.next();
Integer currentScore = 0;
if (field.getName().equalsIgnoreCase("temperature")) {
currentScore = cityA.getTemperature().compareTo(cityB.getTemperature());
} else if (field.getName().equalsIgnoreCase("numberOfInhabitants")) {
currentScore = cityA.getNumberOfInhabitants().compareTo(cityB.getNumberOfInhabitants());
} else if (field.getName().equalsIgnoreCase("rainfall")) {
currentScore = cityA.getRainfall().compareTo(cityB.getRainfall());
}
if (currentScore != 0) {
continueComparison = false;
}
score = currentScore;
}
return score;
}
}
You may want to add an extra layer of precision, to specify, for each field, whether sorting should be ascendant or descendant. I guess a solution is to replace Field
objects by objects of a class you could call SortedField
, containing a Field
object, plus another field meaning ascendant or descendant.
Short answer is: You don't have any choice other than:
arr[4] = 5;
You can apply more than one transform like this:
li:nth-of-type(2){
transform : translate(-20px, 0px) rotate(15deg);
}
Just adding the #include <math.h>
in c source file and -lm in Makefile at the end will work for me.
gcc -pthread -o p3 p3.c -lm
You can also do it in a three line method:
public static int gcd(int x, int y){
return (y == 0) ? x : gcd(y, x % y);
}
Here, if y = 0
, x is returned. Otherwise, the gcd
method is called again, with different parameter values.
You can use different types of redirect method in laravel -
return redirect()->intended('http://heera.it');
OR
return redirect()->to('http://heera.it');
OR
use Illuminate\Support\Facades\Redirect;
return Redirect::to('/')->with(['type' => 'error','message' => 'Your message'])->withInput(Input::except('password'));
OR
return redirect('/')->with(Auth::logout());
OR
return redirect()->route('user.profile', ['step' => $step, 'id' => $id]);
No value is considered false, only the absence of the attribute. There are plenty of invalid values though, and some implementations might consider certain invalid values as false.
HTML5 spec
http://www.w3.org/TR/html5/forms.html#attr-input-checked :
The disabled content attribute is a boolean attribute.
http://www.w3.org/TR/html5/infrastructure.html#boolean-attributes :
The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.
If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace.
Conclusion
The following are valid, equivalent and true:
<input type="checkbox" checked />
<input type="checkbox" checked="" />
<input type="checkbox" checked="checked" />
<input type="checkbox" checked="ChEcKeD" />
The following are invalid:
<input type="checkbox" checked="0" />
<input type="checkbox" checked="1" />
<input type="checkbox" checked="false" />
<input type="checkbox" checked="true" />
The absence of the attribute is the only valid syntax for false:
<input type="checkbox" />
Recommendation
If you care about writing valid XHTML, use checked="checked"
, since <input checked>
is invalid and other alternatives are less readable. Else, just use <input checked>
as it is shorter.
For most it is a breeze, however like you I had a difficult time installing jq
The best resources I found are: https://stedolan.github.io/jq/download/ and http://macappstore.org/jq/
However neither worked for me. I run python 2 & 3, and use brew in addition to pip, as well as Jupyter. I was only successful after brew uninstall jq then updating brew and rebooting my system
What worked for me was removing all previous installs then pip install jq
If PowerShell is open in a directory other than the target file, e.g.:
If someScript.ps1
is located here: C:\SlowLearner\some_missing_path\someScript.ps1
, then C:\SlowLearner>. ./someScript.ps1
wont work.
In that case, navigate to the path: cd some_missing_path
then this would work:
C:\SlowLearner\some_missing_path>. ./someScript.ps1
On my Mac r is installed in /usr/local/bin/r
, add line below in .bash_profile
solved the same problem:
alias r="LANG=en_US.UTF-8 LC_ALL=en_US.UTF-8 r"
Query:
select ord_num, agent_code, ord_date, ord_amount
from orders
where (agent_code, ord_amount) IN
(SELECT agent_code, MIN(ord_amount)
FROM orders
GROUP BY agent_code);
above query worked for me in mysql. refer following link -->
https://www.w3resource.com/sql/subqueries/multiplee-row-column-subqueries.php
I believe this is what you're looking for:
var press = jQuery.Event("keypress");
press.ctrlKey = false;
press.which = 40;
$("whatever").trigger(press);
From here.
def datetime_to_epoch(d1):
# create 1,1,1970 in same timezone as d1
d2 = datetime(1970, 1, 1, tzinfo=d1.tzinfo)
time_delta = d1 - d2
ts = int(time_delta.total_seconds())
return ts
def epoch_to_datetime_string(ts, tz_name="UTC"):
x_timezone = timezone(tz_name)
d1 = datetime.fromtimestamp(ts, x_timezone)
x = d1.strftime("%d %B %Y %H:%M:%S")
return x
Sample 1: This works and produces Exit code = 0. That is Good. Note the "." , directly after echo.
C:\Users\phife.dog\gitrepos\1\repo_abc\scripts #
@echo.| set /p JUNK_VAR=This is a message displayed like Linux echo -n would display it ... & echo %ERRORLEVEL%
This is a message displayed like Linux echo -n would display it ... 0
Sample 2: This works but produces Exit code = 1. That is Bad. Please note the lack of ".", after echo. That appears to be the difference.
C:\Users\phife.dog\gitrepos\1\repo_abc\scripts #
@echo | set /p JUNK_VAR=This is a message displayed like Linux echo -n would display it ... & echo %ERRORLEVEL%
This is a message displayed like Linux echo -n would display it ... 1
The general form of the syntax is
<protocol>://[<user>[:<password>]@]<hostname>[:<port>][:][/]<path>[#<commit-ish> | #semver:<semver>]
which means for your case it will be
npm install git+ssh://[email protected]/visionmedia/express.git
From npmjs docs:
npm install :
Installs the package from the hosted git provider, cloning it with git. For a full git remote url, only that URL will be attempted.
<protocol>://[<user>[:<password>]@]<hostname>[:<port>][:][/]<path>[#<commit-ish>
| #semver:] is one of git, git+ssh, git+http, git+https, or git+file.
If # is provided, it will be used to clone exactly that commit. If the commit-ish has the format #semver:, can be any valid semver range or exact version, and npm will look for any tags or refs matching that range in the remote repository, much as it would for a registry dependency. If neither # or
semver: is specified, then master is used.
If the repository makes use of submodules, those submodules will be cloned as well.
If the package being installed contains a prepare script, its dependencies and devDependencies will be installed, and the prepare script will be run, before the package is packaged and installed.
The following git environment variables are recognized by npm and will be added to the environment when running git:
- GIT_ASKPASS
- GIT_EXEC_PATH
- GIT_PROXY_COMMAND
- GIT_SSH
- GIT_SSH_COMMAND
- GIT_SSL_CAINFO GIT_SSL_NO_VERIFY
See the git man page for details.
Examples:
npm install git+ssh://[email protected]:npm/npm.git#v1.0.27 npm install git+ssh://[email protected]:npm/npm#semver:^5.0 npm install git+https://[email protected]/npm/npm.git npm install git://github.com/npm/npm.git#v1.0.27 GIT_SSH_COMMAND='ssh -i ~/.ssh/custom_ident' npm install git+ssh://[email protected]:npm/npm.git npm install
the return statement exits from the current function and exit() exits from the program
they are the same when used in main() function
also return is a statement while exit() is a function which requires stdlb.h header file
Don't enter the password with command. Just enter,
mysqldump -u <username> -p <db_name> > <backup_file>.sql
Then you will get a prompt to enter password.
I'd start by completely filling in the Notification
. Here is a sample project demonstrating the use of startForeground()
.
What might be easier, is to have two buttons and show/hide them in your functions. (ie. display:none|block;
) Each button could then have it's own onclick with whatever code you need.
So, at first button1
would be display:block
and button2
would be display:none
. Then when you click button1
it would switch button2
to be display:block
and button1
to be display:none
.
This setting works well under angular 8:
Package.json:
...
"dependencies": {
"@angular/animations": "^8.2.14",
"@angular/cdk": "8.2.3",
"@angular/common": "^8.2.14",
"@angular/compiler": "^8.2.14",
"@angular/core": "^8.2.14",
...
"devDependencies": {
"@angular-devkit/build-angular": "~0.803.29",
"@angular/cli": "~8.3.29",
"@angular/compiler-cli": "^8.2.14"
I had a similar problem and wrote a detailed article about it. If anyone has the same problem, feel free to read my article.
https://developer-blog.net/administration/ssl-zertifikat-installieren/
It is a detailed problem description in German language.
Easy.. Try this
$("table td img.delete").click(function () {
$(this).parent().parent().parent().fadeTo(400, 0, function () {
$(this).remove();
});
return false;
});
From here:
The
versionKey
is a property set on each document when first created by Mongoose. This keys value contains the internal revision of the document. The name of this document property is configurable. The default is__v
.If this conflicts with your application you can configure as such:
new Schema({..}, { versionKey: '_somethingElse' })
Api Call using Model Class
let urlString = "http://--.154.--.78/------/index.php?route=api/coupon/all"
let url = URL(string: urlString)
var request = URLRequest(url: url!)
request.httpMethod = "GET"
URLSession.shared.dataTask(with:request) { (data, response, error) in
if error != nil {
print(error)
} else {
do {
let parsedDictionaryArray = try JSONSerialization.jsonObject(with: data!) as! [String:AnyObject]
print(parsedDictionaryArray)
if let arry = parsedDictionaryArray["data"] as? [[String:AnyObject]] {
for dic in arry {
let name = dic["name"]
let descriptionData = dic["description"]
self.modelReference.append(model(name: name as! String, descriptionStr: descriptionData as! String))
print(name!)
}
}
} catch let error as NSError {
print(error)
}
}
}.resume()
create a variable and connect with model class
var modelReference = [model]()
create a model class New -> swift class
import Foundation
class model : NSObject{
var name : String
var descriptionStr: String
init(name : String, descriptionStr: String)
{
self.name = name
self.descriptionStr = descriptionStr
}
}
then we can connect with our table view objects
let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCellID")as! TableViewCell
cell.listName.text = modelReference[indexPath.row].name
const foo = 'bar';
console.log(!!foo); // Boolean: true
_x000D_
! negates (inverts) a value AND always returns/ produces a boolean. So !'bar' would yield false (because 'bar' is truthy => negated + boolean = false). With the additional ! operator, the value is negated again, so false becomes true.
According to the discussion here you can directly compare two vectors using
==
if (vector1 == vector2){
//true
}
else{
//false
}
This is most likely not an answer to the issue itself but this question pops up as first result when searching for Sql declare scalar variable
hence i share a possible solution to this error.
In my case this error was caused by the use of ;
after a SQL statement. Just remove it and the error will be gone.
I guess the cause is the same as @IronSean already posted in an comment above:
it's worth noting that using GO (or in this case ;) causes a new branch where declared variables aren't visible past the statement.
For example:
DECLARE @id int
SET @id = 78
SELECT * FROM MyTable WHERE Id = @var; <-- remove this character to avoid the error message
SELECT * FROM AnotherTable WHERE MyTableId = @var
Example example;
Here example is an object on the stack.
Example* example=new Example();
This could be broken into:
Example* example;
....
example=new Example();
Here the first statement creates a variable example which is a "pointer to Example". When the constructor is called, memory is allocated for it on the heap (dynamic allocation). It is the programmer's responsibility to free this memory when it is no longer needed. (C++ does not have garbage collection like java).
Just have a line added to your crontab..
Make sure the file is executable:
chmod +x /path_to_you_file/your_file
To edit crontab file:
crontab -e
Line you have to add:
@reboot /path_to_you_file/your_file
That simple!
$('div').removeAttr('style');
A very simple way of doing this is to use reset_index() method.For a data frame df use the code below:
df.reset_index(inplace=True)
This way, the index will become a column, and by using inplace as True,this become permanent change.
This can be done with tables:
<table cellpadding="0" cellspacing="0" width="100%" height="100%">
<tr height="0%"><td>
<div id="full">
<!--contents of 1 -->
</div>
</td></tr>
<tr><td>
<div id="someid">
<!--contents of 2 -->
</div>
</td></tr>
</table>
Then apply css to make someid fill the remaining space:
#someid {
height: 100%;
}
Now, I can just hear the angry shouts from the crowd, "Oh noes, he's using tables! Feed him to the lions!" Please hear me out.
Unlike the accepted answer which accomplishes nothing aside from making the container div the full height of the page, this solution makes div #2 fill the remaining space as requested in the question. If you need that second div to fill the full height allotted to it, this is currently the only way to do it.
But feel free to prove me wrong, of course! CSS is always better.
The use
operator is for giving aliases to names of classes, interfaces or other namespaces. Most use
statements refer to a namespace or class that you'd like to shorten:
use My\Full\Namespace;
is equivalent to:
use My\Full\Namespace as Namespace;
// Namespace\Foo is now shorthand for My\Full\Namespace\Foo
If the use
operator is used with a class or interface name, it has the following uses:
// after this, "new DifferentName();" would instantiate a My\Full\Classname
use My\Full\Classname as DifferentName;
// global class - making "new ArrayObject()" and "new \ArrayObject()" equivalent
use ArrayObject;
The use
operator is not to be confused with autoloading. A class is autoloaded (negating the need for include
) by registering an autoloader (e.g. with spl_autoload_register
). You might want to read PSR-4 to see a suitable autoloader implementation.
I've built a fairly simple, reusable and functional Angular2 autocomplete component based on some of the ideas in this answer/other tutorials around on this subject and others. It's by no means comprehensive but may be helpful if you decide to build your own.
The component:
import { Component, Input, Output, OnInit, ContentChild, EventEmitter, HostListener } from '@angular/core';
import { Observable } from "rxjs/Observable";
import { AutoCompleteRefDirective } from "./autocomplete.directive";
@Component({
selector: 'autocomplete',
template: `
<ng-content></ng-content>
<div class="autocomplete-wrapper" (click)="clickedInside($event)">
<div class="list-group autocomplete" *ngIf="results">
<a [routerLink]="" class="list-group-item" (click)="selectResult(result)" *ngFor="let result of results; let i = index" [innerHTML]="dataMapping(result) | highlight: query" [ngClass]="{'active': i == selectedIndex}"></a>
</div>
</div>
`,
styleUrls: ['./autocomplete.component.css']
})
export class AutoCompleteComponent implements OnInit {
@ContentChild(AutoCompleteRefDirective)
public input: AutoCompleteRefDirective;
@Input() data: (searchTerm: string) => Observable<any[]>;
@Input() dataMapping: (obj: any) => string;
@Output() onChange = new EventEmitter<any>();
@HostListener('document:click', ['$event'])
clickedOutside($event: any): void {
this.clearResults();
}
public results: any[];
public query: string;
public selectedIndex: number = 0;
private searchCounter: number = 0;
ngOnInit(): void {
this.input.change
.subscribe((query: string) => {
this.query = query;
this.onChange.emit();
this.searchCounter++;
let counter = this.searchCounter;
if (query) {
this.data(query)
.subscribe(data => {
if (counter == this.searchCounter) {
this.results = data;
this.input.hasResults = data.length > 0;
this.selectedIndex = 0;
}
});
}
else this.clearResults();
});
this.input.cancel
.subscribe(() => {
this.clearResults();
});
this.input.select
.subscribe(() => {
if (this.results && this.results.length > 0)
{
this.selectResult(this.results[this.selectedIndex]);
}
});
this.input.up
.subscribe(() => {
if (this.results && this.selectedIndex > 0) this.selectedIndex--;
});
this.input.down
.subscribe(() => {
if (this.results && this.selectedIndex + 1 < this.results.length) this.selectedIndex++;
});
}
selectResult(result: any): void {
this.onChange.emit(result);
this.clearResults();
}
clickedInside($event: any): void {
$event.preventDefault();
$event.stopPropagation();
}
private clearResults(): void {
this.results = [];
this.selectedIndex = 0;
this.searchCounter = 0;
this.input.hasResults = false;
}
}
The component CSS:
.autocomplete-wrapper {
position: relative;
}
.autocomplete {
position: absolute;
z-index: 100;
width: 100%;
}
The directive:
import { Directive, Input, Output, HostListener, EventEmitter } from '@angular/core';
@Directive({
selector: '[autocompleteRef]'
})
export class AutoCompleteRefDirective {
@Input() hasResults: boolean = false;
@Output() change = new EventEmitter<string>();
@Output() cancel = new EventEmitter();
@Output() select = new EventEmitter();
@Output() up = new EventEmitter();
@Output() down = new EventEmitter();
@HostListener('input', ['$event'])
oninput(event: any) {
this.change.emit(event.target.value);
}
@HostListener('keydown', ['$event'])
onkeydown(event: any)
{
switch (event.keyCode) {
case 27:
this.cancel.emit();
return false;
case 13:
var hasResults = this.hasResults;
this.select.emit();
return !hasResults;
case 38:
this.up.emit();
return false;
case 40:
this.down.emit();
return false;
default:
}
}
}
The highlight pipe:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'highlight'
})
export class HighlightPipe implements PipeTransform {
transform(value: string, args: any): any {
var re = new RegExp(args, 'gi');
return value.replace(re, function (match) {
return "<strong>" + match + "</strong>";
})
}
}
The implementation:
import { Component } from '@angular/core';
import { Observable } from "rxjs/Observable";
import { Subscriber } from "rxjs/Subscriber";
@Component({
selector: 'home',
template: `
<autocomplete [data]="getData" [dataMapping]="dataMapping" (onChange)="change($event)">
<input type="text" class="form-control" name="AutoComplete" placeholder="Search..." autocomplete="off" autocompleteRef />
</autocomplete>
`
})
export class HomeComponent {
getData = (query: string) => this.search(query);
// The dataMapping property controls the mapping of an object returned via getData.
// to a string that can be displayed to the use as an option to select.
dataMapping = (obj: any) => obj;
// This function is called any time a change is made in the autocomplete.
// When the text is changed manually, no object is passed.
// When a selection is made the object is passed.
change(obj: any): void {
if (obj) {
// You can do pretty much anything here as the entire object is passed if it's been selected.
// Navigate to another page, update a model etc.
alert(obj);
}
}
private searchData = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'];
// This function mimics an Observable http service call.
// In reality it's probably calling your API, but today it's looking at mock static data.
private search(query: string): Observable<any>
{
return new Observable<any>((subscriber: Subscriber<any>) => subscriber
.next())
.map(o => this.searchData.filter(d => d.indexOf(query) > -1));
}
}
maybe
var re = /^https?:\/\/[^/]+/i;
window.location.href = re.exec(window.location.href)[0];
is what you're looking for?
if (!secondaryPassword.equals(initialPassword))
I went with a modification of @user1097431 's answer:
function menuPosition(){
// distance from top of footer to top of document
var footertotop = ($('.footer').position().top);
// distance user has scrolled from top, adjusted to take in height of bar (42 pixels inc. padding)
var scrolltop = $(document).scrollTop() + window.innerHeight;
// difference between the two
var difference = scrolltop-footertotop;
// if user has scrolled further than footer,
// pull sidebar up using a negative margin
if (scrolltop > footertotop) {
$('#categories-wrapper').css({
'bottom' : difference
});
}else{
$('#categories-wrapper').css({
'bottom' : 0
});
};
};
This may also tangentially help, to understand if a logging request (from the code) at a certain level will result in it actually being logged given the effective logging level that a deployment is configured with. Decide what effective level you want to configure you deployment with from the other Answers here, and then refer to this to see if a particular logging request from your code will actually be logged then...
For examples:
from logback documentation:
In a more graphic way, here is how the selection rule works. In the following table, the vertical header shows the level of the logging request, designated by p, while the horizontal header shows effective level of the logger, designated by q. The intersection of the rows (level request) and columns (effective level) is the boolean resulting from the basic selection rule.
So a code line that requests logging will only actually get logged if the effective logging level of its deployment is less than or equal to that code line's requested level of severity.
You can very easily use this to re-use the value of the variable in another function.
// Use this in source window.var1= oEvent.getSource().getBindingContext();
// Get value of var1 in destination var var2= window.var1;
To extract the real part of a complex-valued expression z
, use the notation as __real__ z
.
Similarly, use __imag__
attribute on the z
to extract the imaginary part.
For example;
__complex__ float z;
float r;
float i;
r = __real__ z;
i = __imag__ z;
r is the real part of the complex number "z" i is the imaginary part of the complex number "z"
You are not providing the correct address for the file. You need to provide an address such as C:/Users/xyz/Desktop/myfile.xml
I hope this answer is still useful, despite problem seems to be quite old.
If you have Anaconda installed, and your OpenCV does not support GTK+ (as in this case), you can simply type
conda install -c menpo opencv=2.4.11
It will install suitable OpenCV version that does not produce a mentioned error. Besides, it will reinstall previously installed OpenCV if there was one as a part of Anaconda.
It's fairly simple. You write values using keys and expiry times. You get values using keys. You can expire keys from the system.
Most clients follow the same rules. You can read the generic instructions and best practices on the memcached homepage.
If you really want to dig into it, I'd look at the source. Here's the header comment:
"""
client module for memcached (memory cache daemon)
Overview
========
See U{the MemCached homepage<http://www.danga.com/memcached>} for more about memcached.
Usage summary
=============
This should give you a feel for how this module operates::
import memcache
mc = memcache.Client(['127.0.0.1:11211'], debug=0)
mc.set("some_key", "Some value")
value = mc.get("some_key")
mc.set("another_key", 3)
mc.delete("another_key")
mc.set("key", "1") # note that the key used for incr/decr must be a string.
mc.incr("key")
mc.decr("key")
The standard way to use memcache with a database is like this::
key = derive_key(obj)
obj = mc.get(key)
if not obj:
obj = backend_api.get(...)
mc.set(key, obj)
# we now have obj, and future passes through this code
# will use the object from the cache.
Detailed Documentation
======================
More detailed documentation is available in the L{Client} class.
"""
Only checked
and checked="checked"
are valid. Your other options depend on error recovery in browsers.
checked="yes"
and checked="true"
are particularly bad as they imply that checked="no"
and checked="false"
will set the default state to be unchecked … which they will not.
Visual Studio : Right Bottom : Look for OVR label. Double Click on it.
Bingo...
The solution to "Cannot Get /" can usually be determined if you do an "ng build" in the command line. You will find most often that one of your "imports" does not have the correct path.
You can realize this layout using CSS table-cells.
Modify your HTML slightly as follows:
<div id="header">
<div class="container">
<div class="logoBar">
<img src="http://placehold.it/50x40" />
</div>
<div id="searchBar">
<input type="text" />
</div>
<div class="button orange" id="myAccount">My Account</div>
<div class="button red" id="basket">Basket (2)</div>
</div>
</div>
Just remove the wrapper element around the two .button
elements.
Apply the following CSS:
#header {
background-color: #323C3E;
width:100%;
}
.container {
display: table;
width: 100%;
}
.logoBar, #searchBar, .button {
display: table-cell;
vertical-align: middle;
width: auto;
}
.logoBar img {
display: block;
}
#searchBar {
background-color: #FFF2BC;
width: 90%;
padding: 0 50px 0 10px;
}
#searchBar input {
width: 100%;
}
.button {
white-space: nowrap;
padding:22px;
}
Apply display: table
to .container
and give it 100% width.
For .logoBar
, #searchBar
, .button
, apply display: table-cell
.
For the #searchBar
, set the width to 90%, which force all the other elements to compute a shrink-to-fit width and the search bar will expand to fill in the rest of the space.
Use text-align and vertical-align in the table cells as needed.
See demo at: http://jsfiddle.net/audetwebdesign/zWXQt/
Use my_map.count( key )
; it can only return 0 or 1, which is essentially the Boolean result you want.
Alternately my_map.find( key ) != my_map.end()
works too.
You could take this next instruction and would do the work with lack of perfomance. If you want to see the effect of that, put one of the 2 next instructions (Technically similars) where you need to clear the DataGridView into a try{} catch(...){} finally block and wait what occurs.
while (dataGridView1.Rows.Count > 1)
{
dataGridView1.Rows.RemoveAt(0);
}
foreach (object _Cols in dataGridView1.Columns)
{
dataGridView1.Columns.RemoveAt(0);
}
You improve this task but its not enough, there is a problem to reset a DataGridView, because of the colums that remains in the DataGridView object. Finally I suggest, the best way i've implemented in my home practice is to handle this gridView as a file with rows, columns: a record collection based on the match between rows and columns. If you can improve, then take your own choice a) or b): foreach or while.
//(a): With foreach
foreach (object _Cols in dataGridView1.Columns)
{
dataGridView1.Columns.RemoveAt(0);
}
foreach(object _row in dataGridView1.Rows){
dataGridView1.Rows.RemoveAt(0);
}
//(b): With foreach
while (dataGridView1.Rows.Count > 1)
{
dataGridView1.Rows.RemoveAt(0);
}
while (dataGridView1.Columns.Count > 0)
{
dataGridView1.Columns.RemoveAt(0);
}
Well, as a recomendation Never in your life delete the columns first, the order is before the rows after the cols, because logically the columns where created first and then the rows.It would be a penalty in terms of correct analisys.
foreach (object _Cols in dataGridView1.Columns)
{
dataGridView1.Columns.RemoveAt(0);
}
foreach (object _row in dataGridView1.Rows)
{
dataGridView1.Rows.RemoveAt(0);
}
while (dataGridView1.Rows.Count > 1)
{
dataGridView1.Rows.RemoveAt(0);
}
while (dataGridView1.Columns.Count > 0)
{
dataGridView1.Columns.RemoveAt(0);
}
Then, Put it inside a function or method.
private void ClearDataGridViewLoopWhile()
{
while (dataGridView1.Rows.Count > 1)
{
dataGridView1.Rows.RemoveAt(0);
}
while (dataGridView1.Columns.Count > 0)
{
dataGridView1.Columns.RemoveAt(0);
}
}
private void ClearDataGridViewForEach()
{
foreach (object _Cols in dataGridView1.Columns)
{
dataGridView1.Columns.RemoveAt(0);
}
foreach (object _row in dataGridView1.Rows)
{
dataGridView1.Rows.RemoveAt(0);
}
}
Finally, call your new function ClearDataGridViewLoopWhile(); or ClearDataGridViewForEach(); where you need to use it, but its recomended when you are making queries and changing over severall tables that will load with diferents header names in the grieView. But if you want preserve headers here there is a solution given.
I have always found Exceptions are much slower to be handled.
Perhaps a less intensive way would yeild a better, faster, result?
public bool IsValidUri(Uri uri)
{
using (HttpClient Client = new HttpClient())
{
HttpResponseMessage result = Client.GetAsync(uri).Result;
HttpStatusCode StatusCode = result.StatusCode;
switch (StatusCode)
{
case HttpStatusCode.Accepted:
return true;
case HttpStatusCode.OK:
return true;
default:
return false;
}
}
}
Then just use:
IsValidUri(new Uri("http://www.google.com/censorship_algorithm"));
Regarding #2, according to the JSR-330 spec:
This package provides dependency injection annotations that enable portable classes, but it leaves external dependency configuration up to the injector implementation.
So it's up to the provider to determine which objects are available for injection. In the case of Spring it is all Spring beans. And any class annotated with JSR-330 annotations are automatically added as Spring beans when using an AnnotationConfigApplicationContext.
Two different approaches:
I think that #1 is a little more obvious about what's going on, although it can get tedious if you have too many return values. In that case, option #2 works fairly well, although there's some mental overhead involved in making specialized structs for this purpose.
Unless you're trying to upload the file using ajax, just submit the form to /upload/image
.
<form enctype="multipart/form-data" action="/upload/image" method="post">
<input id="image-file" type="file" />
</form>
If you do want to upload the image in the background (e.g. without submitting the whole form), you can use ajax:
Use Google CDN for fast loading:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
The difference between respectively || and OR and && and AND is operator precedence :
$bool = FALSE || TRUE;
($bool = (FALSE || TRUE))
$bool
is TRUE
$bool = FALSE OR TRUE;
(($bool = FALSE) OR TRUE)
$bool
is FALSE
$bool = TRUE && FALSE;
($bool = (TRUE && FALSE))
$bool
is FALSE
$bool = TRUE AND FALSE;
(($bool = TRUE) AND FALSE)
$bool
is TRUE
Take a look at jfxmessagebox (http://en.sourceforge.jp/projects/jfxmessagebox/) if you are looking for very simple dialog popups.
In case you'd like to paste windows path from other source (say, File Explorer) - you can do so via input()
call in python console:
>>> input()
D:\EP\stuff\1111\this_is_a_long_path\you_dont_want\to_type\or_edit_by_hand
'D:\\EP\\stuff\\1111\\this_is_a_long_path\\you_dont_want\\to_type\\or_edit_by_hand'
Then just copy the result
Download https://github.com/douglascrockford/JSON-js/blob/master/json2.js
, include it and do
var json_data = JSON.stringify(obj);
It isn't giving any errors?
Try
SET @tmpType = 'premium
'
and
SET @tmpType = 'basic'
Use ng-bind-html this is only proper and simplest way
You can log all uncaught exceptions on the main thread by assigning a handler to sys.excepthook
, perhaps using the exc_info
parameter of Python's logging functions:
import sys
import logging
logging.basicConfig(filename='/tmp/foobar.log')
def exception_hook(exc_type, exc_value, exc_traceback):
logging.error(
"Uncaught exception",
exc_info=(exc_type, exc_value, exc_traceback)
)
sys.excepthook = exception_hook
raise Exception('Boom')
If your program uses threads, however, then note that threads created using threading.Thread
will not trigger sys.excepthook
when an uncaught exception occurs inside them, as noted in Issue 1230540 on Python's issue tracker. Some hacks have been suggested there to work around this limitation, like monkey-patching Thread.__init__
to overwrite self.run
with an alternative run
method that wraps the original in a try
block and calls sys.excepthook
from inside the except
block. Alternatively, you could just manually wrap the entry point for each of your threads in try
/except
yourself.
You remove the original image here:
newImg.animate(css, SPEED, function() {
img.remove();
newImg.removeClass('morpher');
(callback || function() {})();
});
And all that's left behind is newImg
. Then you reset link references the image using #rocket
:
$("#rocket").attr('src', ...
But your newImg
doesn't have an id
attribute let alone an id
of rocket
.
To fix this, you need to remove img
and then set the id
attribute of newImg
to rocket
:
newImg.animate(css, SPEED, function() {
var old_id = img.attr('id');
img.remove();
newImg.attr('id', old_id);
newImg.removeClass('morpher');
(callback || function() {})();
});
And then you'll get the shiny black rocket back again: http://jsfiddle.net/ambiguous/W2K9D/
UPDATE: A better approach (as noted by mellamokb) would be to hide the original image and then show it again when you hit the reset button. First, change the reset action to something like this:
$("#resetlink").click(function(){
clearInterval(timerRocket);
$("#wrapper").css('top', '250px');
$('.throbber, .morpher').remove(); // Clear out the new stuff.
$("#rocket").show(); // Bring the original back.
});
And in the newImg.load
function, grab the images original size:
var orig = {
width: img.width(),
height: img.height()
};
And finally, the callback for finishing the morphing animation becomes this:
newImg.animate(css, SPEED, function() {
img.css(orig).hide();
(callback || function() {})();
});
New and improved: http://jsfiddle.net/ambiguous/W2K9D/1/
The leaking of $('.throbber, .morpher')
outside the plugin isn't the best thing ever but it isn't a big deal as long as it is documented.
When I have a lot of files I've deleted that are unstaged for commit, you can git rm
them all in one show with:
for i in `git status | grep deleted | awk '{print $3}'`; do git rm $i; done
As question answerer mentioned, be careful with git rm
.
As far as I understand, it is going to drop your database and re-create it based on your db/schema.rb
file. That is why you need to make sure that your schema.rb
file is always up to date and under version control.
If you don't want to use the optgroup element, put the dashes in an option element instead and give it the disabled attribute. It will be visible, but greyed out.
<option disabled>----------</option>
Even simpler, use _.values
from underscore.js
https://underscorejs.org/#values
Restartable mode (/Z) has to do with a partially-copied file. With this option, should the copy be interrupted while any particular file is partially copied, the next execution of robocopy can pick up where it left off rather than re-copying the entire file.
That option could be useful when copying very large files over a potentially unstable connection.
Backup mode (/B) has to do with how robocopy reads files from the source system. It allows the copying of files on which you might otherwise get an access denied error on either the file itself or while trying to copy the file's attributes/permissions. You do need to be running in an Administrator context or otherwise have backup rights to use this flag.
Hi all i have created two overload methods for finding nth occurrence of char and for text with less complexity without navigating through loop ,which increase performance of your application.
public static int NthIndexOf(string text, char searchChar, int nthindex)
{
int index = -1;
try
{
var takeCount = text.TakeWhile(x => (nthindex -= (x == searchChar ? 1 : 0)) > 0).Count();
if (takeCount < text.Length) index = takeCount;
}
catch { }
return index;
}
public static int NthIndexOf(string text, string searchText, int nthindex)
{
int index = -1;
try
{
Match m = Regex.Match(text, "((" + searchText + ").*?){" + nthindex + "}");
if (m.Success) index = m.Groups[2].Captures[nthindex - 1].Index;
}
catch { }
return index;
}
a shorter one-liner fwiw:
my_hash.inject({}){|h,(k,v)| h.merge({ k.to_sym => v}) }
First of all, there are cases when object construction is a task complex enough to justify its extraction to another class.
I believe this point is incorrect. The complexity doesn't really matter. The relevance is what does. If an object can be constructed in one step (not like in the builder pattern), the constructor is the right place to do it. If you really need another class to perform the job, then it should be a helper class that is used from the constructor anyway.
Vec2(float x, float y);
Vec2(float angle, float magnitude); // not a valid overload!
There is an easy workaround for this:
struct Cartesian {
inline Cartesian(float x, float y): x(x), y(y) {}
float x, y;
};
struct Polar {
inline Polar(float angle, float magnitude): angle(angle), magnitude(magnitude) {}
float angle, magnitude;
};
Vec2(const Cartesian &cartesian);
Vec2(const Polar &polar);
The only disadvantage is that it looks a bit verbose:
Vec2 v2(Vec2::Cartesian(3.0f, 4.0f));
But the good thing is that you can immediately see what coordinate type you're using, and at the same time you don't have to worry about copying. If you want copying, and it's expensive (as proven by profiling, of course), you may wish to use something like Qt's shared classes to avoid copying overhead.
As for the allocation type, the main reason to use the factory pattern is usually polymorphism. Constructors can't be virtual, and even if they could, it wouldn't make much sense. When using static or stack allocation, you can't create objects in a polymorphic way because the compiler needs to know the exact size. So it works only with pointers and references. And returning a reference from a factory doesn't work too, because while an object technically can be deleted by reference, it could be rather confusing and bug-prone, see Is the practice of returning a C++ reference variable, evil? for example. So pointers are the only thing that's left, and that includes smart pointers too. In other words, factories are most useful when used with dynamic allocation, so you can do things like this:
class Abstract {
public:
virtual void do() = 0;
};
class Factory {
public:
Abstract *create();
};
Factory f;
Abstract *a = f.create();
a->do();
In other cases, factories just help to solve minor problems like those with overloads you have mentioned. It would be nice if it was possible to use them in a uniform way, but it doesn't hurt much that it is probably impossible.
Recursive php rename keys function:
function replaceKeys($oldKey, $newKey, array $input){
$return = array();
foreach ($input as $key => $value) {
if ($key===$oldKey)
$key = $newKey;
if (is_array($value))
$value = replaceKeys( $oldKey, $newKey, $value);
$return[$key] = $value;
}
return $return;
}
Actually, there are four forms of this operator:
<>
!=
^=
and even
¬= -- worked on some obscure platforms in the dark ages
which are the same, but treated differently when a verbatim match is required (stored outlines or cached queries).
You can play with your array
$daysArray = array('Monday', 'Tuesday', 'Sunday');
$day = current($transport); // $day = 'Monday';
$day = next($transport); // $day = 'Tuesday';
$day = current($transport); // $day = 'Tuesday';
$day = prev($transport); // $day = 'Monday';
$day = end($transport); // $day = 'Sunday';
$day = current($transport); // $day = 'Sunday';
To get the first element of array you can use current
and for last element you can use end
Edit
Just for the sake for not getting any more down votes for the answer you can convert you key to value using array_keys
and use as shown above.
You should set property file name without .properties
extension,
it works correctly for me:)
I see this is old but I needed the code from SingleNegationElimination however I had issue with the data containing non utf-8 characters. These appeared in fields I was not overly concerned with so I chose to ignore them. However that took some effort. I am new to python so with some trial and error I got it to work. The code is a copy of SingleNegationElimination with the extra handling of utf-8. I tried to do it with https://docs.python.org/2.7/library/csv.html but in the end gave up. The below code worked.
import csv, json
csvfile = open('file.csv', 'r')
jsonfile = open('file.json', 'w')
fieldnames = ("Scope","Comment","OOS Code","In RMF","Code","Status","Name","Sub Code","CAT","LOB","Description","Owner","Manager","Platform Owner")
reader = csv.DictReader(csvfile , fieldnames)
code = ''
for row in reader:
try:
print('+' + row['Code'])
for key in row:
row[key] = row[key].decode('utf-8', 'ignore').encode('utf-8')
json.dump(row, jsonfile)
jsonfile.write('\n')
except:
print('-' + row['Code'])
raise
git diff branch_1..branch_2
That will produce the diff between the tips of the two branches. If you'd prefer to find the diff from their common ancestor to test, you can use three dots instead of two:
git diff branch_1...branch_2
MessageBox.Show also returns a DialogResult, which if you put some buttons on there, means you can have it returned what the user clicked. Most of the time I write something like
if (MessageBox.Show("Do you want to continue?", "Question", MessageBoxButtons.YesNo) == MessageBoxResult.Yes) {
//some interesting behaviour here
}
which I guess is a bit unwieldy but it gets the job done.
See https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.dialogresult for additional enum options you can use here.
I found the solution.
As said in the EDIT of my answer, a <div>
is misfunctioning in a <table>
.
So I wrote this code instead :
<tr id="hidden" style="display:none;">
<td class="depot_table_left">
<label for="sexe">Sexe</label>
</td>
<td>
<select type="text" name="sexe">
<option value="1">Sexe</option>
<option value="2">Joueur</option>
<option value="3">Joueuse</option>
</select>
</td>
</tr>
And this is working fine.
Thanks everybody ;)
In my case I found duplicate paths in Servers/Tomcat5.5 at localhost-config/server.xml under tag. Removing the duplicates solved the problem.
Structured programming says you should only ever have one return statement per function. This is to limit the complexity. Many people such as Martin Fowler argue that it is simpler to write functions with multiple return statements. He presents this argument in the classic refactoring book he wrote. This works well if you follow his other advice and write small functions. I agree with this point of view and only strict structured programming purists adhere to single return statements per function.
We tried several things before arriving at an acceptable solution:
xxd -u /usr/bin/xxd | grep 'DF'
00017b0: 4010 8D05 0DFF FF0A 0300 53E3 0610 A003 @.........S.....
root# grep -ibH "df" /usr/bin/xxd
Binary file /usr/bin/xxd matches
xxd -u /usr/bin/xxd | grep -H 'DF'
(standard input):00017b0: 4010 8D05 0DFF FF0A 0300 53E3 0610 A003 @.........S.....
Then found we could get usable results with
xxd -u /usr/bin/xxd > /tmp/xxd.hex ; grep -H 'DF' /tmp/xxd
Note that using a simple search target like 'DF' will incorrectly match characters that span across byte boundaries, i.e.
xxd -u /usr/bin/xxd | grep 'DF'
00017b0: 4010 8D05 0DFF FF0A 0300 53E3 0610 A003 @.........S.....
--------------------^^
So we use an ORed regexp to search for ' DF' OR 'DF ' (the searchTarget preceded or followed by a space char).
The final result seems to be
xxd -u -ps -c 10000000000 DumpFile > DumpFile.hex
egrep ' DF|DF ' Dumpfile.hex
0001020: 0089 0424 8D95 D8F5 FFFF 89F0 E8DF F6FF ...$............
-----------------------------------------^^
0001220: 0C24 E871 0B00 0083 F8FF 89C3 0F84 DF03 .$.q............
--------------------------------------------^^
function doSomthing() {
...
}
Use it like so:
Array.from(Array(length).keys()).forEach(doSomthing);
Or
Array.from({ length }, (v, i) => i).forEach(doSomthing);
Or
// array start counting from 1
Array.from({ length }, (v, i) => ++i).forEach(doSomthing);
If you need to handle multiple currencies, various number formats etc. I can recommend autoNumeric. Works a treat. Have been using it successfully for several years now.
Try using setAttribute on the result:
result.setAttribute("class","red");
if your "import { MatTableModule } from '@angular/material';" is on a shared module, make sure you export it.
sharedmodule.ts:
import { MatTableModule } from '@angular/material'
@NgModule({
imports: [
// ...
MatTableModule
// ...
],
exports:[ MatTableModule ]
})
then on your custom module where you define the component that use material table:
custommodule.ts:
@NgModule({
imports: [ sharedmodule ]
})
instead of below Code
BEGIN
INSERT INTO EmailsRecebidos (De, Assunto, Data)
VALUES (@_DE, @_ASSUNTO, @_DATA)
WHERE NOT EXISTS ( SELECT * FROM EmailsRecebidos
WHERE De = @_DE
AND Assunto = @_ASSUNTO
AND Data = @_DATA);
END
replace with
BEGIN
IF NOT EXISTS (SELECT * FROM EmailsRecebidos
WHERE De = @_DE
AND Assunto = @_ASSUNTO
AND Data = @_DATA)
BEGIN
INSERT INTO EmailsRecebidos (De, Assunto, Data)
VALUES (@_DE, @_ASSUNTO, @_DATA)
END
END
Updated : (thanks to @Marc Durdin for pointing)
Note that under high load, this will still sometimes fail, because a second connection can pass the IF NOT EXISTS test before the first connection executes the INSERT, i.e. a race condition. See stackoverflow.com/a/3791506/1836776 for a good answer on why even wrapping in a transaction doesn't solve this.
public class TransferMarket extends Activity {
float x1,x2;
float y1, y2;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transfer_market);
}
// onTouchEvent () method gets called when User performs any touch event on screen
// Method to handle touch event like left to right swap and right to left swap
public boolean onTouchEvent(MotionEvent touchevent)
{
switch (touchevent.getAction())
{
// when user first touches the screen we get x and y coordinate
case MotionEvent.ACTION_DOWN:
{
x1 = touchevent.getX();
y1 = touchevent.getY();
break;
}
case MotionEvent.ACTION_UP:
{
x2 = touchevent.getX();
y2 = touchevent.getY();
//if left to right sweep event on screen
if (x1 < x2)
{
Toast.makeText(this, "Left to Right Swap Performed", Toast.LENGTH_LONG).show();
}
// if right to left sweep event on screen
if (x1 > x2)
{
Toast.makeText(this, "Right to Left Swap Performed", Toast.LENGTH_LONG).show();
}
// if UP to Down sweep event on screen
if (y1 < y2)
{
Toast.makeText(this, "UP to Down Swap Performed", Toast.LENGTH_LONG).show();
}
//if Down to UP sweep event on screen
if (y1 > y2)
{
Toast.makeText(this, "Down to UP Swap Performed", Toast.LENGTH_LONG).show();
}
break;
}
}
return false;
}
Custom Comparator
should help
Collections.sort(list, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return s1.compareToIgnoreCase(s2);
}
});
Or if you are using Java 8:
list.sort(String::compareToIgnoreCase);
As @Psyonity mentioned, you can use the conditionalWeakTable to add properties to existing objects. Combined with the dynamic ExpandoObject, you could implement dynamic extension properties in a few lines:
using System.Dynamic;
using System.Runtime.CompilerServices;
namespace ExtensionProperties
{
/// <summary>
/// Dynamically associates properies to a random object instance
/// </summary>
/// <example>
/// var jan = new Person("Jan");
///
/// jan.Age = 24; // regular property of the person object;
/// jan.DynamicProperties().NumberOfDrinkingBuddies = 27; // not originally scoped to the person object;
///
/// if (jan.Age < jan.DynamicProperties().NumberOfDrinkingBuddies)
/// Console.WriteLine("Jan drinks too much");
/// </example>
/// <remarks>
/// If you get 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create' you should reference Microsoft.CSharp
/// </remarks>
public static class ObjectExtensions
{
///<summary>Stores extended data for objects</summary>
private static ConditionalWeakTable<object, object> extendedData = new ConditionalWeakTable<object, object>();
/// <summary>
/// Gets a dynamic collection of properties associated with an object instance,
/// with a lifetime scoped to the lifetime of the object
/// </summary>
/// <param name="obj">The object the properties are associated with</param>
/// <returns>A dynamic collection of properties associated with an object instance.</returns>
public static dynamic DynamicProperties(this object obj) => extendedData.GetValue(obj, _ => new ExpandoObject());
}
}
A usage example is in the xml comments:
var jan = new Person("Jan");
jan.Age = 24; // regular property of the person object;
jan.DynamicProperties().NumberOfDrinkingBuddies = 27; // not originally scoped to the person object;
if (jan.Age < jan.DynamicProperties().NumberOfDrinkingBuddies)
{
Console.WriteLine("Jan drinks too much");
}
jan = null; // NumberOfDrinkingBuddies will also be erased during garbage collection
In addition to Telmo Marques answer: I use Virtual Router for this.
Like connectify it creates an accesspoint on your Windows 8, Windows 7 or 2008 R2 machine, but it's open-source.
Intel® VTune™ Performance Analyzer for quick sampling
I've tried both these and still get failure due to conflicts. At the end of my patience, I cloned master in another location, copied everything into the other branch and committed it. which let me continue. The "-X theirs" option should have done this for me, but it did not.
git merge -s recursive -X theirs master
error: 'merge' is not possible because you have unmerged files. hint: Fix them up in the work tree, hint: and then use 'git add/rm ' as hint: appropriate to mark resolution and make a commit, hint: or use 'git commit -a'. fatal: Exiting because of an unresolved conflict.
System.currentTimeMillis()
does give you the number of milliseconds since January 1, 1970 00:00:00 UTC. The reason you see local times might be because you convert a Date
instance to a string before using it. You can use DateFormat
s to convert Date
s to String
s in any timezone:
DateFormat df = DateFormat.getTimeInstance();
df.setTimeZone(TimeZone.getTimeZone("gmt"));
String gmtTime = df.format(new Date());
Before actually answering your question:
Parameters in a URL (e.g. key=listOfUsers/user1
) are GET
parameters and you shouldn't be using them for POST
requests. A quick explanation of the difference between GET and POST can be found here.
In your case, to make use of REST principles, you should probably have:
http://ip:5000/users
http://ip:5000/users/<user_id>
Then, on each URL, you can define the behaviour of different HTTP methods (GET
, POST
, PUT
, DELETE
). For example, on /users/<user_id>
, you want the following:
GET /users/<user_id> - return the information for <user_id>
POST /users/<user_id> - modify/update the information for <user_id> by providing the data
PUT - I will omit this for now as it is similar enough to `POST` at this level of depth
DELETE /users/<user_id> - delete user with ID <user_id>
So, in your example, you want do a POST
to /users/user_1
with the POST data being "John"
. Then the XPath expression or whatever other way you want to access your data should be hidden from the user and not tightly couple to the URL. This way, if you decide to change the way you store and access data, instead of all your URL's changing, you will simply have to change the code on the server-side.
Now, the answer to your question: Below is a basic semi-pseudocode of how you can achieve what I mentioned above:
from flask import Flask
from flask import request
app = Flask(__name__)
@app.route('/users/<user_id>', methods = ['GET', 'POST', 'DELETE'])
def user(user_id):
if request.method == 'GET':
"""return the information for <user_id>"""
.
.
.
if request.method == 'POST':
"""modify/update the information for <user_id>"""
# you can use <user_id>, which is a str but could
# changed to be int or whatever you want, along
# with your lxml knowledge to make the required
# changes
data = request.form # a multidict containing POST data
.
.
.
if request.method == 'DELETE':
"""delete user with ID <user_id>"""
.
.
.
else:
# POST Error 405 Method Not Allowed
.
.
.
There are a lot of other things to consider like the POST
request content-type but I think what I've said so far should be a reasonable starting point. I know I haven't directly answered the exact question you were asking but I hope this helps you. I will make some edits/additions later as well.
Thanks and I hope this is helpful. Please do let me know if I have gotten something wrong.
The List
interface already has this solved.
int temp = 2;
if(bankAccNos.contains(bakAccNo)) temp=1;
More can be found in the documentation about List.
I guess your code relates to Windows Forms.
You call BeginInvoke
if you need something to be executed asynchronously in the UI thread: change control's properties in most of the cases.
Roughly speaking this is accomplished be passing the delegate to some procedure which is being periodically executed. (message loop processing and the stuff like that)
If BeginInvoke
is called for Delegate
type the delegate is just invoked asynchronously.
(Invoke
for the sync version.)
If you want more universal code which works perfectly for WPF and WinForms you can consider Task Parallel Library and running the Task
with the according context. (TaskScheduler.FromCurrentSynchronizationContext()
)
And to add a little to already said by others:
Lambdas can be treated either as anonymous methods or expressions.
And that is why you cannot just use var
with lambdas: compiler needs a hint.
UPDATE:
this requires .Net v4.0 and higher
// This line must be called in UI thread to get correct scheduler
var scheduler = System.Threading.Tasks.TaskScheduler.FromCurrentSynchronizationContext();
// this can be called anywhere
var task = new System.Threading.Tasks.Task( () => someformobj.listBox1.SelectedIndex = 0);
// also can be called anywhere. Task will be scheduled for execution.
// And *IF I'm not mistaken* can be (or even will be executed synchronously)
// if this call is made from GUI thread. (to be checked)
task.Start(scheduler);
If you started the task from other thread and need to wait for its completition task.Wait()
will block calling thread till the end of the task.
Read more about tasks here.
I have a little hack for this one. JSON.parse('false')
will return false
and JSON.parse('true')
will return true. But this doesn't work with JSON.parse(true || false)
. So, if you use something like JSON.parse(your_value.to_s)
it should achieve your goal in a simple but hacky way.
As per the W3C:
Since the initial value of the border styles is 'none', no borders will be visible unless the border style is set.
In other words, you need to set a border style (e.g. solid
) for the border to show up. border:thin
only sets the width. Also, the color will by default be the same as the text color (which normally doesn't look good).
I recommend setting all three styles:
style="border: thin solid black"
First of all, there is no difference between View.OnClickListener
and OnClickListener
. If you just use View.OnClickListener
directly, then you don't need to write-
import android.view.View.OnClickListener
You set an OnClickListener instance (e.g. myListener
named object)as the listener to a view via setOnclickListener()
. When a click
event is fired, that myListener
gets notified and it's onClick(View view)
method is called. Thats where we do our own task.
Hope this helps you.
You could create a db wrapper then require it. node's require returns the same instance of a module every time, so you can perform your connection and return a handler. From the Node.js docs:
every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.
You could create db.js
:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '127.0.0.1',
user : 'root',
password : '',
database : 'chat'
});
connection.connect(function(err) {
if (err) throw err;
});
module.exports = connection;
Then in your app.js
, you would simply require it.
var express = require('express');
var app = express();
var db = require('./db');
app.get('/save',function(req,res){
var post = {from:'me', to:'you', msg:'hi'};
db.query('INSERT INTO messages SET ?', post, function(err, result) {
if (err) throw err;
});
});
server.listen(3000);
This approach allows you to abstract any connection details, wrap anything else you want to expose and require db
throughout your application while maintaining one connection to your db thanks to how node require works :)
What I think you may want is an ArrayList<Integer>
instead of an array. This will allow you do to:
ArrayList<Integer> arr = new ArrayList<Integer>(20);
System.out.println(arr.size());
The output will be 0
.
Then, you can add things to the list, and it will keep track of the count for you. (It will also grow the size of the backing storage as you need as well.)
Use the following JS:
$(document).ready(function () {
$("#btnsubmit").click(function () {
$.ajax({
type: "POST",
url: '/Plan/PlanManage', //your action
data: $('#PlanForm').serialize(), //your form name.it takes all the values of model
dataType: 'json',
success: function (result) {
console.log(result);
}
})
return false;
});
});
and the following code on your controller:
[HttpPost]
public string PlanManage(Plan objplan) //model plan
{
}
Here's another way to do it, using a LINQ lambda:
C#:
SomeObject.GetType().GetProperties().ToList().ForEach(x => Console.WriteLine($"{x.Name} = {x.GetValue(SomeObject, null)}"));
VB.NET:
SomeObject.GetType.GetProperties.ToList.ForEach(Sub(x) Console.WriteLine($"{x.Name} = {x.GetValue(SomeObject, Nothing)}"))
I took another approach inspired by @john-rees above - especially when his approach started to fail for me at some point. Basically recurse the subtree and sort files by their path-length - delete from longest to the shortest
Get-ChildItem $tfsLocalPath -Recurse | #Find all children
Select-Object FullName,@{Name='PathLength';Expression={($_.FullName.Length)}} | #Calculate the length of their path
Sort-Object PathLength -Descending | #sort by path length descending
%{ Get-Item -LiteralPath $_.FullName } |
Remove-Item -Force
Regarding the -LiteralPath magic, here's another gotchya that may be hitting you: https://superuser.com/q/212808
void
means it returns nothing. It does not return a string, you write a string to System.out
but you're not returning one.
You must specify what a method returns, even if you're just saying that it returns nothing.
Technically speaking they could have designed the language such that if you don't write a return type then it's assumed to return nothing, however making you explicitly write out void
helps to ensure that the lack of a returned value is intentional and not accidental.
With dplyr
package, Use
nrow(filter(mydata, sCode == "CA")),
All the solutions provided here gave me same error as multi-sam but that one worked.
...you do not need to import any library. Just use the delete character:
BS=u'\0008' # the unicode for "delete" character
for i in range(10):print(BS+"."),
this removes the newline and the space (^_^)*
Do you mean?
long millis = System.currentTimeMillis() % 1000;
BTW Windows doesn't allow timetravel to 1969
C:\> date
Enter the new date: (dd-mm-yy) 2/8/1969
The system cannot accept the date entered.
You may want to use:
SELECT Name, 'Unpaid' AS Status FROM table;
The SELECT
clause syntax, as defined in MSDN: SELECT Clause (Transact-SQL), is as follows:
SELECT [ ALL | DISTINCT ]
[ TOP ( expression ) [ PERCENT ] [ WITH TIES ] ]
<select_list>
Where the expression
can be a constant, function, any combination of column names, constants, and functions connected by an operator or operators, or a subquery.
Double importing jquery can cause Error
<script src="static/public/js/jquery/jquery.min.js"></script>
OR
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="" crossorigin="anonymous"></script>
Just to keep this subject complete, I found a solution not explored Here using Fixed position.
html, body, .wrapper, .parent, .child {_x000D_
position: fixed;_x000D_
top: 0; _x000D_
bottom: 0;_x000D_
left: 0;_x000D_
right: 0;_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
.child {_x000D_
overflow: auto;_x000D_
background: gray;_x000D_
}_x000D_
_x000D_
.height-50 {_x000D_
height: 50%;_x000D_
width: 5em;_x000D_
margin: 10px auto;_x000D_
background: cyan;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="parent">_x000D_
<div class="child">_x000D_
_x000D_
<div class="height-50"></div>_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
html, body, .wrapper, .parent, .child {_x000D_
position: fixed;_x000D_
top: 0; _x000D_
bottom: 0;_x000D_
left: 0;_x000D_
right: 0;_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
.child {_x000D_
overflow: auto;_x000D_
background: gray;_x000D_
}_x000D_
_x000D_
.height-150 {_x000D_
height: 150%;_x000D_
width: 5em;_x000D_
margin: 10px auto;_x000D_
background: cyan;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="parent">_x000D_
<div class="child">_x000D_
_x000D_
<div class="height-150"></div>_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
$(this).parent().siblings(":first").text()
parent
gives you the <td>
around the link,
siblings
gives all the <td>
tags in that <tr>
,
:first
gives the first matched element in the set.
text()
gives the contents of the tag.
Another easy method to solve this issue adding the style attribute:
$('.selector').attr('style', 'width:500px !important');
I just tried all of these, and for IE11, the only thing that seems to work is disabled="true". Values of disabled or no value given didnt work. As a matter of fact, the jsp got an error that equal is required for all fields, so I had to specify disabled="true" for this to work.
Use:
:wq!
The exclamation mark is used for overriding read-only mode.
Well, you're going to want document.location
. Do some sort of string manipulation on it (unless jQuery has a way to avoid that work for you) and then
$(body).addClass(foo);
I know this isn't the complete answer, but I assume you can work the rest out :)
If the solution above doesn't work for anyone. Give this a try as well
a {
box-shadow: none;
}
If I were lazy, I could say that binary search on a sorted array is O(n2), O(n3), and O(2n), and I would be technically correct in every case.
We can use o-notation ("little-oh") to denote an upper bound that is not asymptotically tight. Both big-oh and little-oh are similar. But, big-oh is likely used to define asymptotically tight upper bound.
Here's my solution, loads from .json to allow changes without rebuilding
import { Injectable, Inject } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Location } from '@angular/common';
@Injectable()
export class ConfigService {
private config: any;
constructor(private location: Location, private http: Http) {
}
async apiUrl(): Promise<string> {
let conf = await this.getConfig();
return Promise.resolve(conf.apiUrl);
}
private async getConfig(): Promise<any> {
if (!this.config) {
this.config = (await this.http.get(this.location.prepareExternalUrl('/assets/config.json')).toPromise()).json();
}
return Promise.resolve(this.config);
}
}
and config.json
{
"apiUrl": "http://localhost:3000/api"
}