Here's an alternative regular expression:
^(?=(.{4})*$)[A-Za-z0-9+/]*={0,2}$
It satisfies the following conditions:
(?=^(.{4})*$)
[A-Za-z0-9+/]*
={0,2}
Nope. Extension method definitions require an instance of the type you're extending. It's unfortunate; I'm not sure why it's required...
If you don't want to use list comprehension by some reasons, you can use map and operator.itemgetter:
>>> from operator import itemgetter
>>> rows = [(1, 2), (3, 4), (5, 6)]
>>> map(itemgetter(1), rows)
[2, 4, 6]
>>>
You wrote asp.net - are you looking to upload a file?
if so you can use the html
<input type="file" ...
I've had the same issue. For me at one point in time the div's elements were not loaded entirely and the scrollTop property was initialized with the current value of scrollHeight, which was not the correct end value of scrollHeight.
My project is in Angular 8 and what I did was:
The AfterViewChecked event fires a few times and it gets in the end the proper value from scrollHeight.
I solved similar problem just by backing out of the project directory, then cd back into the project directory and bundle install.
SP is the stack register a shortcut for typing r13. LR is the link register a shortcut for r14. And PC is the program counter a shortcut for typing r15.
When you perform a call, called a branch link instruction, bl, the return address is placed in r14, the link register. the program counter pc is changed to the address you are branching to.
There are a few stack pointers in the traditional ARM cores (the cortex-m series being an exception) when you hit an interrupt for example you are using a different stack than when running in the foreground, you dont have to change your code just use sp or r13 as normal the hardware has done the switch for you and uses the correct one when it decodes the instructions.
The traditional ARM instruction set (not thumb) gives you the freedom to use the stack in a grows up from lower addresses to higher addresses or grows down from high address to low addresses. the compilers and most folks set the stack pointer high and have it grow down from high addresses to lower addresses. For example maybe you have ram from 0x20000000 to 0x20008000 you set your linker script to build your program to run/use 0x20000000 and set your stack pointer to 0x20008000 in your startup code, at least the system/user stack pointer, you have to divide up the memory for other stacks if you need/use them.
Stack is just memory. Processors normally have special memory read/write instructions that are PC based and some that are stack based. The stack ones at a minimum are usually named push and pop but dont have to be (as with the traditional arm instructions).
If you go to http://github.com/lsasim I created a teaching processor and have an assembly language tutorial. Somewhere in there I go through a discussion about stacks. It is NOT an arm processor but the story is the same it should translate directly to what you are trying to understand on the arm or most other processors.
Say for example you have 20 variables you need in your program but only 16 registers minus at least three of them (sp, lr, pc) that are special purpose. You are going to have to keep some of your variables in ram. Lets say that r5 holds a variable that you use often enough that you dont want to keep it in ram, but there is one section of code where you really need another register to do something and r5 is not being used, you can save r5 on the stack with minimal effort while you reuse r5 for something else, then later, easily, restore it.
Traditional (well not all the way back to the beginning) arm syntax:
...
stmdb r13!,{r5}
...temporarily use r5 for something else...
ldmia r13!,{r5}
...
stm is store multiple you can save more than one register at a time, up to all of them in one instruction.
db means decrement before, this is a downward moving stack from high addresses to lower addresses.
You can use r13 or sp here to indicate the stack pointer. This particular instruction is not limited to stack operations, can be used for other things.
The ! means update the r13 register with the new address after it completes, here again stm can be used for non-stack operations so you might not want to change the base address register, leave the ! off in that case.
Then in the brackets { } list the registers you want to save, comma separated.
ldmia is the reverse, ldm means load multiple. ia means increment after and the rest is the same as stm
So if your stack pointer were at 0x20008000 when you hit the stmdb instruction seeing as there is one 32 bit register in the list it will decrement before it uses it the value in r13 so 0x20007FFC then it writes r5 to 0x20007FFC in memory and saves the value 0x20007FFC in r13. Later, assuming you have no bugs when you get to the ldmia instruction r13 has 0x20007FFC in it there is a single register in the list r5. So it reads memory at 0x20007FFC puts that value in r5, ia means increment after so 0x20007FFC increments one register size to 0x20008000 and the ! means write that number to r13 to complete the instruction.
Why would you use the stack instead of just a fixed memory location? Well the beauty of the above is that r13 can be anywhere it could be 0x20007654 when you run that code or 0x20002000 or whatever and the code still functions, even better if you use that code in a loop or with recursion it works and for each level of recursion you go you save a new copy of r5, you might have 30 saved copies depending on where you are in that loop. and as it unrolls it puts all the copies back as desired. with a single fixed memory location that doesnt work. This translates directly to C code as an example:
void myfun ( void )
{
int somedata;
}
In a C program like that the variable somedata lives on the stack, if you called myfun recursively you would have multiple copies of the value for somedata depending on how deep in the recursion. Also since that variable is only used within the function and is not needed elsewhere then you perhaps dont want to burn an amount of system memory for that variable for the life of the program you only want those bytes when in that function and free that memory when not in that function. that is what a stack is used for.
A global variable would not be found on the stack.
Going back...
Say you wanted to implement and call that function you would have some code/function you are in when you call the myfun function. The myfun function wants to use r5 and r6 when it is operating on something but it doesnt want to trash whatever someone called it was using r5 and r6 for so for the duration of myfun() you would want to save those registers on the stack. Likewise if you look into the branch link instruction (bl) and the link register lr (r14) there is only one link register, if you call a function from a function you will need to save the link register on each call otherwise you cant return.
...
bl myfun
<--- the return from my fun returns here
...
myfun:
stmdb sp!,{r5,r6,lr}
sub sp,#4 <--- make room for the somedata variable
...
some code here that uses r5 and r6
bl more_fun <-- this modifies lr, if we didnt save lr we wouldnt be able to return from myfun
<---- more_fun() returns here
...
add sp,#4 <-- take back the stack memory we allocated for the somedata variable
ldmia sp!,{r5,r6,lr}
mov pc,lr <---- return to whomever called myfun.
So hopefully you can see both the stack usage and link register. Other processors do the same kinds of things in a different way. for example some will put the return value on the stack and when you execute the return function it knows where to return to by pulling a value off of the stack. Compilers C/C++, etc will normally have a "calling convention" or application interface (ABI and EABI are names for the ones ARM has defined). if every function follows the calling convention, puts parameters it is passing to functions being called in the right registers or on the stack per the convention. And each function follows the rules as to what registers it does not have to preserve the contents of and what registers it has to preserve the contents of then you can have functions call functions call functions and do recursion and all kinds of things, so long as the stack does not go so deep that it runs into the memory used for globals and the heap and such, you can call functions and return from them all day long. The above implementation of myfun is very similar to what you would see a compiler produce.
ARM has many cores now and a few instruction sets the cortex-m series works a little differently as far as not having a bunch of modes and different stack pointers. And when executing thumb instructions in thumb mode you use the push and pop instructions which do not give you the freedom to use any register like stm it only uses r13 (sp) and you cannot save all the registers only a specific subset of them. the popular arm assemblers allow you to use
push {r5,r6}
...
pop {r5,r6}
in arm code as well as thumb code. For the arm code it encodes the proper stmdb and ldmia. (in thumb mode you also dont have the choice as to when and where you use db, decrement before, and ia, increment after).
No you absolutly do not have to use the same registers and you dont have to pair up the same number of registers.
push {r5,r6,r7}
...
pop {r2,r3}
...
pop {r1}
assuming there is no other stack pointer modifications in between those instructions if you remember the sp is going to be decremented 12 bytes for the push lets say from 0x1000 to 0x0FF4, r5 will be written to 0xFF4, r6 to 0xFF8 and r7 to 0xFFC the stack pointer will change to 0x0FF4. the first pop will take the value at 0x0FF4 and put that in r2 then the value at 0x0FF8 and put that in r3 the stack pointer gets the value 0x0FFC. later the last pop, the sp is 0x0FFC that is read and the value placed in r1, the stack pointer then gets the value 0x1000, where it started.
The ARM ARM, ARM Architectural Reference Manual (infocenter.arm.com, reference manuals, find the one for ARMv5 and download it, this is the traditional ARM ARM with ARM and thumb instructions) contains pseudo code for the ldm and stm ARM istructions for the complete picture as to how these are used. Likewise well the whole book is about the arm and how to program it. Up front the programmers model chapter walks you through all of the registers in all of the modes, etc.
If you are programming an ARM processor you should start by determining (the chip vendor should tell you, ARM does not make chips it makes cores that chip vendors put in their chips) exactly which core you have. Then go to the arm website and find the ARM ARM for that family and find the TRM (technical reference manual) for the specific core including revision if the vendor has supplied that (r2p0 means revision 2.0 (two point zero, 2p0)), even if there is a newer rev, use the manual that goes with the one the vendor used in their design. Not every core supports every instruction or mode the TRM tells you the modes and instructions supported the ARM ARM throws a blanket over the features for the whole family of processors that that core lives in. Note that the ARM7TDMI is an ARMv4 NOT an ARMv7 likewise the ARM9 is not an ARMv9. ARMvNUMBER is the family name ARM7, ARM11 without a v is the core name. The newer cores have names like Cortex and mpcore instead of the ARMNUMBER thing, which reduces confusion. Of course they had to add the confusion back by making an ARMv7-m (cortex-MNUMBER) and the ARMv7-a (Cortex-ANUMBER) which are very different families, one is for heavy loads, desktops, laptops, etc the other is for microcontrollers, clocks and blinking lights on a coffee maker and things like that. google beagleboard (Cortex-A) and the stm32 value line discovery board (Cortex-M) to get a feel for the differences. Or even the open-rd.org board which uses multiple cores at more than a gigahertz or the newer tegra 2 from nvidia, same deal super scaler, muti core, multi gigahertz. A cortex-m barely brakes the 100MHz barrier and has memory measured in kbytes although it probably runs of a battery for months if you wanted it to where a cortex-a not so much.
sorry for the very long post, hope it is useful.
The .cc extension is necessary for using implicit rules within makefiles. Look through these links to get a better understanding of makefiles, but look mainly the second one, as it clearly says the usefulness of the .cc extension:
ftp://ftp.gnu.org/old-gnu/Manuals/make-3.79.1/html_chapter/make_2.html
https://ftp.gnu.org/old-gnu/Manuals/make-3.79.1/html_chapter/make_10.html
I just learned of this now.
I am in the process of figuring it out now but it seems as though the math depends on where you and your target are on the earth relative to true and magnetic North. For example:
float thetaMeThem = 0.0;
if (myLocation.bearingTo(targetLocation) > myLocation.getBearing()){
thetaMeThem = myLocation.bearingTo(targetLocation) - azimuth + declination;}
See Sensor.TYPE_ORIENTATION for azimuth.
See getDeclination() for declination
This assumes declination is negative (west of true north) and theirBearing > yourBearing.
If declination is positive and yourBearing > theirBearing another option:
float thetaMeThem = 0.0;
if (myLocation.bearingTo(targetLocation) < myLocation.getBearing()){
thetaMeThem = azimuth - (myLocation.bearingTo(targetLocation) - declination);}
I haven't tested this fully but playing with the angles on paper got me here.
Better way is just to add "save action" so when you save the project it will clear the unused import's and format the code as well if you like .
Go to Window > Preferences > Java > Editor > Save Actions
and pick what ever you want .
If you are using InnoDB or any row-level transactional RDBMS, then it is possible that any write transaction can cause a deadlock, even in perfectly normal situations. Larger tables, larger writes, and long transaction blocks will often increase the likelihood of deadlocks occurring. In your situation, it's probably a combination of these.
The only way to truly handle deadlocks is to write your code to expect them. This generally isn't very difficult if your database code is well written. Often you can just put a try/catch
around the query execution logic and look for a deadlock when errors occur. If you catch one, the normal thing to do is just attempt to execute the failed query again.
I highly recommend you read this page in the MySQL manual. It has a list of things to do to help cope with deadlocks and reduce their frequency.
You want rows where that condition is true so you need a comma:
data[data$Ozone > 14, ]
Yes, ng-hide (or ng-show) directive won't create child scope.
Here is my practice:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular.min.js"></script>
<script>
function main($scope) {
$scope.testa = false;
$scope.testb = false;
$scope.testc = false;
$scope.testd = false;
}
</script>
<div ng-app >
<div ng-controller="main">
Test A: {{testa}}<br />
Test B: {{testb}}<br />
Test C: {{testc}}<br />
Test D: {{testd}}<br />
<div>
testa (without ng-if): <input type="checkbox" ng-model="testa" />
</div>
<div ng-if="!testa">
testb (with ng-if): <input type="checkbox" ng-model="$parent.testb" />
</div>
<div ng-show="!testa">
testc (with ng-show): <input type="checkbox" ng-model="testc" />
</div>
<div ng-hide="testa">
testd (with ng-hide): <input type="checkbox" ng-model="testd" />
</div>
</div>
</div>
Sure, try:
input[value="United States"]{ color: red; }
You can select a child like
TextView tv = (TextView)lv.getChildAt(0);
tv.setTextColor(Color.RED);
tv.setTextSize(12);
You've misunderstood how character classes are used:
$varTemp =~ s/[\$#@~!&*()\[\];.,:?^ `\\\/]+//g;
does the same as your regex (assuming you didn't mean to remove '
characters from your strings).
Edit: The +
allows several of those "special characters" to match at once, so it should also be faster.
Getting Full File Paths From a Directory and All Its Subdirectories
import os
def get_filepaths(directory):
"""
This function will generate the file names in a directory
tree by walking the tree either top-down or bottom-up. For each
directory in the tree rooted at directory top (including top itself),
it yields a 3-tuple (dirpath, dirnames, filenames).
"""
file_paths = [] # List which will store all of the full filepaths.
# Walk the tree.
for root, directories, files in os.walk(directory):
for filename in files:
# Join the two strings in order to form the full filepath.
filepath = os.path.join(root, filename)
file_paths.append(filepath) # Add it to the list.
return file_paths # Self-explanatory.
# Run the above function and store its results in a variable.
full_file_paths = get_filepaths("/Users/johnny/Desktop/TEST")
print full_file_paths
which will print the list:
['/Users/johnny/Desktop/TEST/file1.txt', '/Users/johnny/Desktop/TEST/file2.txt', '/Users/johnny/Desktop/TEST/SUBFOLDER/file3.dat']
If you'd like, you can open and read the contents, or focus only on files with the extension ".dat" like in the code below:
for f in full_file_paths:
if f.endswith(".dat"):
print f
/Users/johnny/Desktop/TEST/SUBFOLDER/file3.dat
I used the url as above: http://translate.google.com/translate_tts?tl=en&q=Hello%20World
And requested with python library..however I'm getting HTTP 403 FORBIDDEN
In the end I had to mock the User-Agent
header with the browser's one to succeed.
Just gotta read the docs son!
$query->num_rows();
Here is another approach. Instead of propagating the first event of a quick succession of events and suppressing all that follow, now all are suppressed except from the last one. I think that the scenarios that can benefit from this approach are more common.
To make this happen we must use a sliding delay. Every incoming event cancels the timer that would fire the previous event, and restarts the timer. This opens the possibility that a never-ending series of events will delay the propagation forever. To keep things simple, there is no provision for this abnormal case in the extension methods below.
public static class FileSystemWatcherExtensions
{
public static IDisposable OnAnyEvent(this FileSystemWatcher source,
WatcherChangeTypes changeTypes, FileSystemEventHandler handler, int delay)
{
var cancellations = new Dictionary<string, CancellationTokenSource>(
StringComparer.OrdinalIgnoreCase);
var locker = new object();
if (changeTypes.HasFlag(WatcherChangeTypes.Created))
source.Created += FileSystemWatcher_Event;
if (changeTypes.HasFlag(WatcherChangeTypes.Deleted))
source.Deleted += FileSystemWatcher_Event;
if (changeTypes.HasFlag(WatcherChangeTypes.Changed))
source.Changed += FileSystemWatcher_Event;
if (changeTypes.HasFlag(WatcherChangeTypes.Renamed))
source.Renamed += FileSystemWatcher_Event;
return new Disposable(() =>
{
source.Created -= FileSystemWatcher_Event;
source.Deleted -= FileSystemWatcher_Event;
source.Changed -= FileSystemWatcher_Event;
source.Renamed -= FileSystemWatcher_Event;
});
async void FileSystemWatcher_Event(object sender, FileSystemEventArgs e)
{
var key = e.FullPath;
var cts = new CancellationTokenSource();
lock (locker)
{
if (cancellations.TryGetValue(key, out var existing))
{
existing.Cancel();
}
cancellations[key] = cts;
}
try
{
await Task.Delay(delay, cts.Token);
// Omitting ConfigureAwait(false) is intentional here.
// Continuing in the captured context is desirable.
}
catch (TaskCanceledException)
{
return;
}
lock (locker)
{
if (cancellations.TryGetValue(key, out var existing)
&& existing == cts)
{
cancellations.Remove(key);
}
}
cts.Dispose();
handler(sender, e);
}
}
public static IDisposable OnAllEvents(this FileSystemWatcher source,
FileSystemEventHandler handler, int delay)
=> OnAnyEvent(source, WatcherChangeTypes.All, handler, delay);
public static IDisposable OnCreated(this FileSystemWatcher source,
FileSystemEventHandler handler, int delay)
=> OnAnyEvent(source, WatcherChangeTypes.Created, handler, delay);
public static IDisposable OnDeleted(this FileSystemWatcher source,
FileSystemEventHandler handler, int delay)
=> OnAnyEvent(source, WatcherChangeTypes.Deleted, handler, delay);
public static IDisposable OnChanged(this FileSystemWatcher source,
FileSystemEventHandler handler, int delay)
=> OnAnyEvent(source, WatcherChangeTypes.Changed, handler, delay);
public static IDisposable OnRenamed(this FileSystemWatcher source,
FileSystemEventHandler handler, int delay)
=> OnAnyEvent(source, WatcherChangeTypes.Renamed, handler, delay);
private struct Disposable : IDisposable
{
private readonly Action _action;
internal Disposable(Action action) => _action = action;
public void Dispose() => _action?.Invoke();
}
}
Usage example:
myWatcher.OnAnyEvent(WatcherChangeTypes.Created | WatcherChangeTypes.Changed,
MyFileSystemWatcher_Event, 100);
This line combines the subscription to two events, the Created
and the Changed
. So it is roughly equivalent to these:
myWatcher.Created += MyFileSystemWatcher_Event;
myWatcher.Changed += MyFileSystemWatcher_Event;
The difference is that the two events are regarded as a single type of event, and in case of a quick succession of these events only the last one will be propagated. For example if a Created
event is followed by two Changed
events, and there is no time gap larger than 100 msec between these three events, only the second Changed
event will be propagated by invoking the MyFileSystemWatcher_Event
handler, and the previous ones will be discarded.
Use subquery
SELECT * FROM RES_DATA inner join (SELECT [CUSTOMER ID], sum([TOTAL AMOUNT]) FROM INV_DATA group by [CUSTOMER ID]) T on RES_DATA.[CUSTOMER ID] = t.[CUSTOMER ID]
Here is the solution that worked for me
=IF(H14<>"",NOW(),"")
Updated version of @Alaaedeen's answer. You can specify any part of the version of any package you want to install. This may cause other package versions to change. For example, if you don't care about which specific version of PyQt4 you want, do:
conda install pyqt=4
This would install the latest minor version and release of PyQt 4. You can specify any portion of the version that you want, not just the major number. So, for example
conda install pyqt=4.11
would install the latest (or last) release of version 4.11.
Keep in mind that installing a different version of a package may cause the other packages that depend on it to be rolled forward or back to where they support the version you want.
After carefully searching, I figured out the best approach to accomplish this.
private HttpResponseMessage response;
[SetUp]
public void Setup()
{
var handlerMock = new Mock<HttpMessageHandler>();
handlerMock
.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.IsAny<HttpRequestMessage>(),
ItExpr.IsAny<CancellationToken>())
// This line will let you to change the response in each test method
.ReturnsAsync(() => response);
_httpClient = new HttpClient(handlerMock.Object);
yourClinet = new YourClient( _httpClient);
}
As you noticed I have used Moq and Moq.Protected packages.
import { Dimensions } from 'react-native';
const { width, fontScale } = Dimensions.get("window");
const styles = StyleSheet.create({
fontSize: idleFontSize / fontScale,
});
fontScale
get scale as per your device.
If you use Spring Boot 2.0.0 use:
server.servlet.context-path
Erin's method updated to Swift 3, This shows days from today (disregarding time of day)
func daysBetweenDates( endDate: Date) -> Int
let calendar: Calendar = Calendar.current
let date1 = calendar.startOfDay(for: Date())
let date2 = calendar.startOfDay(for: secondDate)
return calendar.dateComponents([.day], from: date1, to: date2).day!
}
As of JDK6U18 following are configurations for the Heap Size.
In the Client JVM, the default Java heap configuration has been modified to improve the performance of today's rich client applications. Initial and maximum heap sizes are larger and settings related to generational garbage collection are better tuned.
The default maximum heap size is half of the physical memory up to a physical memory size of 192 megabytes and otherwise one fourth of the physical memory up to a physical memory size of 1 gigabyte. For example, if your machine has 128 megabytes of physical memory, then the maximum heap size is 64 megabytes, and greater than or equal to 1 gigabyte of physical memory results in a maximum heap size of 256 megabytes. The maximum heap size is not actually used by the JVM unless your program creates enough objects to require it. A much smaller amount, termed the initial heap size, is allocated during JVM initialization. This amount is at least 8 megabytes and otherwise 1/64 of physical memory up to a physical memory size of 1 gigabyte.
Source : http://www.oracle.com/technetwork/java/javase/6u18-142093.html
@bbum covers blocks in depth in a blog post and touches on the __block storage type.
__block is a distinct storage type
Just like static, auto, and volatile, __block is a storage type. It tells the compiler that the variable’s storage is to be managed differently.
...
However, for __block variables, the block does not retain. It is up to you to retain and release, as needed.
...
As for use cases you will find __block
is sometimes used to avoid retain cycles since it does not retain the argument. A common example is using self.
//Now using myself inside a block will not
//retain the value therefore breaking a
//possible retain cycle.
__block id myself = self;
To insert the Value into the Dictionary
Dictionary<string, string> dDS1 = new Dictionary<string, string>();//Declaration
dDS1.Add("VEqpt", "aaaa");//adding key and value into the dictionary
string Count = dDS1["VEqpt"];//assigning the value of dictionary key to Count variable
dDS1["VEqpt"] = Count + "bbbb";//assigning the value to key
In XSLT 1.0 the upper-case()
and lower-case()
functions are not available.
If you're using a 1.0 stylesheet the common method of case conversion is translate()
:
<xsl:variable name="lowercase" select="'abcdefghijklmnopqrstuvwxyz'" />
<xsl:variable name="uppercase" select="'ABCDEFGHIJKLMNOPQRSTUVWXYZ'" />
<xsl:template match="/">
<xsl:value-of select="translate(doc, $lowercase, $uppercase)" />
</xsl:template>
As Trying as indicated, volatile
deals only with visibility.
Consider this snippet in a concurrent environment:
boolean isStopped = false;
:
:
while (!isStopped) {
// do some kind of work
}
The idea here is that some thread could change the value of isStopped
from false to true in order to indicate to the subsequent loop that it is time to stop looping.
Intuitively, there is no problem. Logically if another thread makes isStopped
equal to true, then the loop must terminate. The reality is that the loop will likely never terminate even if another thread makes isStopped
equal to true.
The reason for this is not intuitive, but consider that modern processors have multiple cores and that each core has multiple registers and multiple levels of cache memory that are not accessible to other processors. In other words, values that are cached in one processor's local memory are not visisble to threads executing on a different processor. Herein lies one of the central problems with concurrency: visibility.
The Java Memory Model makes no guarantees whatsoever about when changes that are made to a variable in one thread may become visible to other threads. In order to guarantee that updates are visisble as soon as they are made, you must synchronize.
The volatile
keyword is a weak form of synchronization. While it does nothing for mutual exclusion or atomicity, it does provide a guarantee that changes made to a variable in one thread will become visible to other threads as soon as it is made. Because individual reads and writes to variables that are not 8-bytes are atomic in Java, declaring variables volatile
provides an easy mechanism for providing visibility in situations where there are no other atomicity or mutual exclusion requirements.
Here is a working example: http://jsfiddle.net/rVBzt/ (using jQuery)
<img id="tiger" src="https://twimg0-a.akamaihd.net/profile_images/2642324404/46d743534606515238a9a12cfb4b264a.jpeg">
<a id="toggle">click to toggle</a>
img {display: none;}
a {cursor: pointer; color: blue;}
$('#toggle').click(function() {
$('#tiger').toggle();
});
Well it's not even close to the full spec, but there is a JavaScript and Canvas based PDF viewer out there.
Here is a pure JavaScript solution I tested working in Firefox and Chrome but not in Internet Explorer:
function downloadDataUrlFromJavascript(filename, dataUrl) {
// Construct the 'a' element
var link = document.createElement("a");
link.download = filename;
link.target = "_blank";
// Construct the URI
link.href = dataUrl;
document.body.appendChild(link);
link.click();
// Cleanup the DOM
document.body.removeChild(link);
delete link;
}
Cross-browser solutions found up until now:
downloadify -> Requires Flash
databounce -> Tested in IE 10 and 11, and doesn't work for me. Requires a servlet and some customization. (Incorrectly detects navigator. I had to set IE in compatibility mode to test, default charset in servlet, JavaScript options object with correct servlet path for absolute paths...) For non-IE browsers, it opens the file in the same window.
download.js -> http://danml.com/download.html Another library similar but not tested. Claims to be pure JavaScript, not requiring servlet nor Flash, but doesn't work on IE <= 9.
Your code looks fine, but there are a couple of things to be aware of:
Post::find($id);
acts upon the primary key, if you have set your primary key in your model to something other than id
by doing:
protected $primaryKey = 'slug';
then find
will search by that key instead.
Laravel also expects the id
to be an integer, if you are using something other than an integer (such as a string) you need to set the incrementing property on your model to false:
public $incrementing = false;
If you have python, you can use a package called iis_bridge that solves the problem. To install:
pip install iis_bridge
then in the python console:
import iis_bridge as iis
iis.install()
The -R, --relative
option will do this.
For example: if you want to backup /var/named/chroot
and create the same directory structure on the remote server then -R
will do just that.
This article clarifies the question for me and discusses other types of load balancer persistence.
Dave's Thoughts: Load balancer persistence (sticky sessions)
Exists = IsObject(CurrentDb.TableDefs(tablename))
As Chris suggests, you can do it like this:
public string GetXMLAsString(XmlDocument myxml)
{
return myxml.OuterXml;
}
Or like this:
public string GetXMLAsString(XmlDocument myxml)
{
StringWriter sw = new StringWriter();
XmlTextWriter tx = new XmlTextWriter(sw);
myxml.WriteTo(tx);
string str = sw.ToString();//
return str;
}
and if you really want to create a new XmlDocument
then do this
XmlDocument newxmlDoc= myxml
Modified from Mr ChuckBevitt
Working solution:
string CSVFilePathName = APP_PATH + "Facilities.csv";
string[] Lines = File.ReadAllLines(CSVFilePathName);
string[] Fields;
Fields = Lines[0].Split(new char[] { ',' });
int Cols = Fields.GetLength(0);
DataTable dt = new DataTable();
//1st row must be column names; force lower case to ensure matching later on.
for (int i = 0; i < Cols-1; i++)
dt.Columns.Add(Fields[i].ToLower(), typeof(string));
DataRow Row;
for (int i = 0; i < Lines.GetLength(0)-1; i++)
{
Fields = Lines[i].Split(new char[] { ',' });
Row = dt.NewRow();
for (int f = 0; f < Cols-1; f++)
Row[f] = Fields[f];
dt.Rows.Add(Row);
}
doThrow : Basically used when you want to throw an exception when a method is being called within a mock object.
public void validateEntity(final Object object){}
Mockito.doThrow(IllegalArgumentException.class)
.when(validationService).validateEntity(Matchers.any(AnyObjectClass.class));
doReturn : Used when you want to send back a return value when a method is executed.
public Socket getCosmosSocket() throws IOException {}
Mockito.doReturn(cosmosSocket).when(cosmosServiceImpl).getCosmosSocket();
doAnswer: Sometimes you need to do some actions with the arguments that are passed to the method, for example, add some values, make some calculations or even modify them doAnswer gives you the Answer interface that being executed in the moment that method is called, this interface allows you to interact with the parameters via the InvocationOnMock argument. Also, the return value of answer method will be the return value of the mocked method.
public ReturnValueObject quickChange(Object1 object);
Mockito.doAnswer(new Answer<ReturnValueObject>() {
@Override
public ReturnValueObject answer(final InvocationOnMock invocation) throws Throwable {
final Object1 originalArgument = (invocation.getArguments())[0];
final ReturnValueObject returnedValue = new ReturnValueObject();
returnedValue.setCost(new Cost());
return returnedValue ;
}
}).when(priceChangeRequestService).quickCharge(Matchers.any(Object1.class));
doNothing: Is the easiest of the list, basically it tells Mockito to do nothing when a method in a mock object is called. Sometimes used in void return methods or method that does not have side effects, or are not related to the unit testing you are doing.
public void updateRequestActionAndApproval(final List<Object1> cmItems);
Mockito.doNothing().when(pagLogService).updateRequestActionAndApproval(
Matchers.any(Object1.class));
Here is the easiest way of creating a splash screen:
First of all, add the following line of code before the namespace in Form1.cs code:
using System.Threading;
Now, follow the following steps:
Add a new form in you application
Name this new form as FormSplashScreen
In the BackgroundImage property, choose an image from one of your folders
Add a progressBar
In the Dock property, set it as Bottom
In MarksAnimationSpeed property, set as 50
In your main form, named as Form1.cs by default, create the following method:
private void StartSplashScreen()
{
Application.Run(new Forms.FormSplashScreen());
}
In the constructor method of Form1.cs, add the following code:
public Form1()
{
Thread t = new Thread(new ThreadStart(StartSplashScreen));
t.Start();
Thread.Sleep(5000);
InitializeComponent();//This code is automatically generated by Visual Studio
t.Abort();
}
Now, just run the application, it is going to work perfectly.
Ah, that would be because RegExp is not jQuery. :)
Try this page. jQuery.attr
doesn't return a String so that would certainly cause in this regard. Fortunately I believe you can just use .text()
to return the String representation.
Something like:
$("li").val("title").search(/sometext/i));
If you want to reload specific entities, with the DbContextApi, RX_DID_RX already gave you the answer.
If you want to reload / refresh all the entities you loaded:
If you are using Entity Framework 4.1+ (EF5, or EF 6 probably), DbContext API:
public void RefreshAll()
{
foreach (var entity in ctx.ChangeTracker.Entries())
{
entity.Reload();
}
}
If you are using entityFramework 4 (ObjectContext API):
public void RefreshAll()
{
// Get all objects in statemanager with entityKey
// (context.Refresh will throw an exception otherwise)
var refreshableObjects = (from entry in context.ObjectStateManager.GetObjectStateEntries(EntityState.Deleted
| EntityState.Modified
| EntityState.Unchanged)
where entry.EntityKey != null
select entry.Entity);
context.Refresh(RefreshMode.StoreWins, refreshableObjects);
}
Best advice anyway is, try to use a "short lived context" and you'll avoid this kind of problems.
I wrote a couple of articles on the matter:
A practical observation... In my NodeJS script I have the following function:
function writeToLogFile (message) {
fs.appendFile('myserverlog.txt', Date() + " " + message + "\r\n", function (err) {
if (err) throw err;
});
}
First I had only "\n" but I noticed that when I open the log file in Notepad, it shows all entries on the same line. Notepad++ on the other hand shows the entries each on their own line. After changing the code to "\r\n", even Notepad shows every entry on its own line.
I have to agree with foobarbecue (I don't have enough recs to be able to simply insert a comment under his post):
It's now recommended that python notebook isn't started wit the argument --pylab
, and according to Fernando Perez (creator of ipythonnb) %matplotlib inline
should be the initial notebook command.
[^]
( within [ ] ) is negation in regular expression whereas ^
is "begining of string"
[^a-z]
matches any single character that is not from "a" to "z"
^[a-z]
means string starts with from "a" to "z"
git stash
to save your uncommited changesgit stash list
to list your saved uncommited stashesgit stash apply stash@{x}
where x can be 0,1,2..no of stashes that you have madeRegarding the width of your website, you'll want to consider using a wrapper class to surround your content (this should help to constrain your element widths and prevent them from expanding too far beyond the content):
<style>
.wrapper {
width: 980px;
}
</style>
<body>
<div class="wrapper">
//everything else
</div>
</body>
As far as the content boxes go, I would suggest trying to use
<style>
.boxes {
display: inline-block;
width: 360px;
height: 360px;
}
#leftBox {
float: left;
}
#rightBox {
float: right;
}
</style>
I would spend some time researching the box-object model and all of the "display" properties. They will be forever helpful. Pay particularly close attention to "inline-block", I use it practically every day.
$(this).css({'text-align':'center'});
You can use class name and id in place of this
$('.classname').css({'text-align':'center'});
or
$('#id').css({'text-align':'center'});
In a recent project I changed the default activity in AndroidManifest.xml with:
<activity android:name=".MyAppRuntimePermissions">
</activity>
<activity android:name=".MyAppDisplay">
<intent-filter>
<action android:name="android.intent.activity.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
In Android Studio 3.6; this seems to broken. I've used this technique in example applications, but when I use it in this real-world application it falls flat. The IDE once again reports:
Error running app: Default activity not found.
The IDE still showed a configuration error in the "run app" space in the toolbar (yellow arrow in this screenshot)
To correct this error I've tried several rebuilds of the project, and finally File >> "Invalidate Cache/Restart". This did not help. To run the application I had to "Edit Configurations" and point at the specific activity instead of the default activity:
The aim of using StringBuilder, i.e reducing memory. Is it achieved?
No, not at all. That code is not using StringBuilder
correctly. (I think you've misquoted it, though; surely there aren't quotes around id2
and table
?)
Note that the aim (usually) is to reduce memory churn rather than total memory used, to make life a bit easier on the garbage collector.
Will that take memory equal to using String like below?
No, it'll cause more memory churn than just the straight concat you quoted. (Until/unless the JVM optimizer sees that the explicit StringBuilder
in the code is unnecessary and optimizes it out, if it can.)
If the author of that code wants to use StringBuilder
(there are arguments for, but also against; see note at the end of this answer), better to do it properly (here I'm assuming there aren't actually quotes around id2
and table
):
StringBuilder sb = new StringBuilder(some_appropriate_size);
sb.append("select id1, ");
sb.append(id2);
sb.append(" from ");
sb.append(table);
return sb.toString();
Note that I've listed some_appropriate_size
in the StringBuilder
constructor, so that it starts out with enough capacity for the full content we're going to append. The default size used if you don't specify one is 16 characters, which is usually too small and results in the StringBuilder
having to do reallocations to make itself bigger (IIRC, in the Sun/Oracle JDK, it doubles itself [or more, if it knows it needs more to satisfy a specific append
] each time it runs out of room).
You may have heard that string concatenation will use a StringBuilder
under the covers if compiled with the Sun/Oracle compiler. This is true, it will use one StringBuilder
for the overall expression. But it will use the default constructor, which means in the majority of cases, it will have to do a reallocation. It's easier to read, though. Note that this is not true of a series of concatenations. So for instance, this uses one StringBuilder
:
return "prefix " + variable1 + " middle " + variable2 + " end";
It roughly translates to:
StringBuilder tmp = new StringBuilder(); // Using default 16 character size
tmp.append("prefix ");
tmp.append(variable1);
tmp.append(" middle ");
tmp.append(variable2);
tmp.append(" end");
return tmp.toString();
So that's okay, although the default constructor and subsequent reallocation(s) isn't ideal, the odds are it's good enough — and the concatenation is a lot more readable.
But that's only for a single expression. Multiple StringBuilder
s are used for this:
String s;
s = "prefix ";
s += variable1;
s += " middle ";
s += variable2;
s += " end";
return s;
That ends up becoming something like this:
String s;
StringBuilder tmp;
s = "prefix ";
tmp = new StringBuilder();
tmp.append(s);
tmp.append(variable1);
s = tmp.toString();
tmp = new StringBuilder();
tmp.append(s);
tmp.append(" middle ");
s = tmp.toString();
tmp = new StringBuilder();
tmp.append(s);
tmp.append(variable2);
s = tmp.toString();
tmp = new StringBuilder();
tmp.append(s);
tmp.append(" end");
s = tmp.toString();
return s;
...which is pretty ugly.
It's important to remember, though, that in all but a very few cases it doesn't matter and going with readability (which enhances maintainability) is preferred barring a specific performance issue.
The usual way to submit a form in general is to call submit() on the form itself, as described in krtek's answer.
However, if you need to actually click a submit button for some reason (your code depends on the submit button's name/value being posted or something), you can click on the submit button itself like this:
document.getElementById('loginSubmit').click();
In the tsconfig.app.json, a standard Angular 10 app has:
{
"extends": "./tsconfig.base.json",
"compilerOptions": {
"outDir": "./out-tsc/app",
"types": []
},
"files": [
"src/main.ts",
"src/polyfills.ts"
],
"include": [
"src/**/*.d.ts"
]
}
Once I changed the include like to be:
"include": [
"src/**/*.d.ts",
"src/**/*.ts"
]
The following function does the trick and keeps all the attributes. You use it for example like this: changeTag("div", "p")
function changeTag(originTag, destTag) {
while($(originTag).length) {
$(originTag).replaceWith (function () {
var attributes = $(this).prop("attributes");
var $newEl = $(`<${destTag}>`)
$.each(attributes, function() {
$newEl.attr(this.name, this.value);
});
return $newEl.html($(this).html())
})
}
}
To be sure that it works, check the following example
function changeTag(originTag, destTag) {_x000D_
while($(originTag).length) {_x000D_
$(originTag).replaceWith (function () {_x000D_
var attributes = $(this).prop("attributes");_x000D_
var $newEl = $(`<${destTag}>`)_x000D_
$.each(attributes, function() {_x000D_
$newEl.attr(this.name, this.value);_x000D_
}); _x000D_
return $newEl.html($(this).html())_x000D_
})_x000D_
}_x000D_
}_x000D_
_x000D_
changeTag("div", "p")_x000D_
_x000D_
console.log($("body").html())
_x000D_
<body>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="A" style="font-size:1em">_x000D_
<div class="B" style="font-size:1.1em">A</div>_x000D_
</div>_x000D_
<div class="C" style="font-size:1.2em">_x000D_
B_x000D_
</div>_x000D_
</body>
_x000D_
CONTAINS
is for a Full Text Indexed field - if not, then use LIKE
The following statement appends the value to the element with the id of response
$('#response').append(total);
This makes it look like you are concatenating the strings, but you aren't, you're actually appending them to the element
change that to
$('#response').text(total);
You need to change the drop event so that it replaces the value of the element with the total, you also need to keep track of what the total is, I suggest something like the following
$(function() {
var data = [];
var total = 0;
$( "#draggable1" ).draggable();
$( "#draggable2" ).draggable();
$( "#draggable3" ).draggable();
$("#droppable_box").droppable({
drop: function(event, ui) {
var currentId = $(ui.draggable).attr('id');
data.push($(ui.draggable).attr('id'));
if(currentId == "draggable1"){
var myInt1 = parseFloat($('#MealplanCalsPerServing1').val());
}
if(currentId == "draggable2"){
var myInt2 = parseFloat($('#MealplanCalsPerServing2').val());
}
if(currentId == "draggable3"){
var myInt3 = parseFloat($('#MealplanCalsPerServing3').val());
}
if ( typeof myInt1 === 'undefined' || !myInt1 ) {
myInt1 = parseInt(0);
}
if ( typeof myInt2 === 'undefined' || !myInt2){
myInt2 = parseInt(0);
}
if ( typeof myInt3 === 'undefined' || !myInt3){
myInt3 = parseInt(0);
}
total += parseFloat(myInt1 + myInt2 + myInt3);
$('#response').text(total);
}
});
$('#myId').click(function(event) {
$.post("process.php", ({ id: data }), function(return_data, status) {
alert(data);
//alert(total);
});
});
});
I moved the var total = 0;
statement out of the drop event and changed the assignment statment from this
total = parseFloat(myInt1 + myInt2 + myInt3);
to this
total += parseFloat(myInt1 + myInt2 + myInt3);
Here is a working example http://jsfiddle.net/axrwkr/RCzGn/
Use
[A-Z]?
to make the letter optional. {1}
is redundant. (Of course you could also write [A-Z]{0,1}
which would mean the same, but that's what the ?
is there for.)
You could improve your regex to
^([0-9]{5})+\s+([A-Z]?)\s+([A-Z])([0-9]{3})([0-9]{3})([A-Z]{3})([A-Z]{3})\s+([A-Z])[0-9]{3}([0-9]{4})([0-9]{2})([0-9]{2})
And, since in most regex dialects, \d
is the same as [0-9]
:
^(\d{5})+\s+([A-Z]?)\s+([A-Z])(\d{3})(\d{3})([A-Z]{3})([A-Z]{3})\s+([A-Z])\d{3}(\d{4})(\d{2})(\d{2})
But: do you really need 11 separate capturing groups? And if so, why don't you capture the fourth-to-last group of digits?
I'm unable to reproduce your problem but have you tried converting it to an integer first?
image_name_data['id'] = image_name_data['id'].astype(int).astype('str')
Then, regarding your more general question you could use map
(as in this answer). In your case:
image_name_data['id'] = image_name_data['id'].map('{:.0f}'.format)
This sub will populate a Collection with all files matching the filename or pattern you pass in.
Sub GetFiles(StartFolder As String, Pattern As String, _
DoSubfolders As Boolean, ByRef colFiles As Collection)
Dim f As String, sf As String, subF As New Collection, s
If Right(StartFolder, 1) <> "\" Then StartFolder = StartFolder & "\"
f = Dir(StartFolder & Pattern)
Do While Len(f) > 0
colFiles.Add StartFolder & f
f = Dir()
Loop
If DoSubfolders then
sf = Dir(StartFolder, vbDirectory)
Do While Len(sf) > 0
If sf <> "." And sf <> ".." Then
If (GetAttr(StartFolder & sf) And vbDirectory) <> 0 Then
subF.Add StartFolder & sf
End If
End If
sf = Dir()
Loop
For Each s In subF
GetFiles CStr(s), Pattern, True, colFiles
Next s
End If
End Sub
Usage:
Dim colFiles As New Collection
GetFiles "C:\Users\Marek\Desktop\Makro\", FName & ".xls", True, colFiles
If colFiles.Count > 0 Then
'work with found files
End If
Yes, It is possible. I've separated the code in two files:
index.php
<?php
$time = time()+(60*60*24*10);
$timeMemo = (string)$time;
setcookie("cookie", "" . $timeMemo . "", $time);
?>
<html>
<head>
<title>
Get cookie expiration date from JS
</title>
<script type="text/javascript">
function cookieExpirationDate(){
var infodiv = document.getElementById("info");
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest;
}else{
xmlhttp = new ActiveXObject(Microsoft.XMLHTTP);
}
xmlhttp.onreadystatechange = function (){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
infodiv.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "cookie.php", true);
xmlhttp.send();
}
</script>
</head>
<body>
<input type="button" onclick="javascript:cookieExpirationDate();" value="Get Cookie expire date" />
<hr />
<div id="info">
</div>
</body>
</html>
cookie.php
<?php
function secToDays($sec){
return ($sec / 60 / 60 / 24);
}
if(isset($_COOKIE['cookie'])){
if(round(secToDays((intval($_COOKIE['cookie']) - time())),1) < 1){
echo "Cookie will expire today";
}else{
echo "Cookie will expire in " . round(secToDays((intval($_COOKIE['cookie']) - time())),1) . " day(s)";
}
}else{
echo "Cookie not set...";
}
?>
Now, index.php must be loaded once. The button "Get Cookie expire date", thru an AJAX request, will always get you an updated "time left" for cookie expiration, in this case in days.
You can specify the style
of the plotted line when calling df.plot
:
df.plot(x='col_name_1', y='col_name_2', style='o')
The style
argument can also be a dict
or list
, e.g.:
import numpy as np
import pandas as pd
d = {'one' : np.random.rand(10),
'two' : np.random.rand(10)}
df = pd.DataFrame(d)
df.plot(style=['o','rx'])
All the accepted style formats are listed in the documentation of matplotlib.pyplot.plot
.
You could use Javascript's substring method. For example:
var list = ["bird1", "bird2", "pig1"]
for (var i = 0; i < list.length; i++) {
if (list[i].substring(0,4) == "bird") {
console.log(list[i]);
}
}
Which outputs:
bird1
bird2
Basically, you're checking each item in the array to see if the first four letters are 'bird'. This does assume that 'bird' will always be at the front of the string.
So let's say your getting a pathname from a URL :
Let's say your at bird1?=letsfly - you could use this code to check the URL:
var listOfUrls = [
"bird1?=letsfly",
"bird",
"pigs?=dontfly",
]
for (var i = 0; i < list.length; i++) {
if (listOfUrls[i].substring(0,4) === 'bird') {
// do something
}
}
The above would match the first to URL's, but not the third (not the pig). You could easily swap out url.substring(0,4)
with a regex, or even another javascript method like .contains()
Using the .contains()
method might be a little more secure. You won't need to know which part of the URL 'bird' is at. For instance:
var url = 'www.example.com/bird?=fly'
if (url.contains('bird')) {
// this is true
// do something
}
Use PropertyInfo.PropertyType
to get the type of the property.
public bool ValidateData(object data)
{
foreach (PropertyInfo propertyInfo in data.GetType().GetProperties())
{
if (propertyInfo.PropertyType == typeof(string))
{
string value = propertyInfo.GetValue(data, null);
if value is not OK
{
return false;
}
}
}
return true;
}
For longitudes use: Decimal(9,6)
, and latitudes use: Decimal(8,6)
If you're not used to precision and scale parameters, here's a format string visual:
###.######
and ##.######
I do this without external libaries:
var yourArray = ['aaa','bbb','ccc'];
var counter = [];
yourArray.forEach(function(name){
conn.collection(name).drop(function(err) {
counter.push(true);
console.log('dropped');
if(counter.length === yourArray.length){
console.log('all dropped');
}
});
});
You can get all keys in the Request.Form and then compare and get your desired values.
Your method body will look like this: -
List<int> listValues = new List<int>();
foreach (string key in Request.Form.AllKeys)
{
if (key.StartsWith("List"))
{
listValues.Add(Convert.ToInt32(Request.Form[key]));
}
}
Simple example:
public function productsAction()
{
$saveFileName = 'ceneo.xml';
$filename = $this->path . $saveFileName;
if(file_exists($filename)) {
$reader = new XMLReader();
$reader->open($filename);
$countElements = 0;
while($reader->read()) {
if($reader->nodeType == XMLReader::ELEMENT) {
$nodeName = $reader->name;
}
if($reader->nodeType == XMLReader::TEXT && !empty($nodeName)) {
switch ($nodeName) {
case 'id':
var_dump($reader->value);
break;
}
}
if($reader->nodeType == XMLReader::END_ELEMENT && $reader->name == 'offer') {
$countElements++;
}
}
$reader->close();
exit(print('<pre>') . var_dump($countElements));
}
}
Visual Studio Community 2015 suffices to build extensions for Python 3.5. It's free but a 6 GB download (overkill). On my computer it installed vcvarsall at C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat
For Python 3.4 you'd need Visual Studio 2010. I don't think there's any free edition. See https://matthew-brett.github.io/pydagogue/python_msvc.html
I've had this same error, without your whole code it is difficult to pinpoint exactly how to fix it but it is caused by not having a __set function.
The way that I have gotten around it in the past is I have done things like this:
$user = createUser();
$role = $user->role;
$role->rolename = 'Test';
now if you do this:
echo $user->role->rolename;
you should see 'Test'
From another answer:
A little history
Remember, there is nothing inherently special about $
. It is a variable name just like any other. In earlier days, people used to write code using document.getElementById. Because JavaScript is case-sensitive, it was normal to make a mistake while writing document.getElementById
. Should I capital 'b'
of 'by'
? Should I capital 'i'
of Id?
You get the drift. Because functions are first-class citizens in JavaScript, you can always do this:
var $ = document.getElementById; //freedom from document.getElementById!
When Prototype library arrived, they named their function, which gets the DOM elements, as '$'
. Almost all the JavaScript libraries copied this idea. Prototype also introduced a $$
function to select elements using CSS selector.
jQuery also adapted $
function but expanded to make it accept all kinds of 'selectors' to get the elements you want. Now, if you are already using Prototype in your project and wanted to include jQuery, you will be in problem as '$'
could either refer to Prototype's implementation OR jQuery's implementation. That's why jQuery has the option of noConflict so that you can include jQuery in your project which uses Prototype and slowly migrate your code. I think this was a brilliant move on John's part! :)
Comparison between different approaches in swift 3.0
1. Sleep
This method does not have a call back. Put codes directly after this line to be executed in 4 seconds. It will stop user from iterating with UI elements like the test button until the time is gone. Although the button is kind of frozen when sleep kicks in, other elements like activity indicator is still spinning without freezing. You cannot trigger this action again during the sleep.
sleep(4)
print("done")//Do stuff here
2. Dispatch, Perform and Timer
These three methods work similarly, they are all running on the background thread with call backs, just with different syntax and slightly different features.
Dispatch is commonly used to run something on the background thread. It has the callback as part of the function call
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(4), execute: {
print("done")
})
Perform is actually a simplified timer. It sets up a timer with the delay, and then trigger the function by selector.
perform(#selector(callback), with: nil, afterDelay: 4.0)
func callback() {
print("done")
}}
And finally, timer also provides ability to repeat the callback, which is not useful in this case
Timer.scheduledTimer(timeInterval: 4, target: self, selector: #selector(callback), userInfo: nil, repeats: false)
func callback() {
print("done")
}}
For all these three method, when you click on the button to trigger them, UI will not freeze and you are allowed to click on it again. If you click on the button again, another timer is set up and the callback will be triggered twice.
In conclusion
None of the four method works good enough just by themselves. sleep
will disable user interaction, so the screen "freezes"(not actually) and results bad user experience. The other three methods will not freeze the screen, but you can trigger them multiple times, and most of the times, you want to wait until you get the call back before allowing user to make the call again.
So a better design will be using one of the three async methods with screen blocking. When user click on the button, cover the entire screen with some translucent view with a spinning activity indicator on top, telling user that the button click is being handled. Then remove the view and indicator in the call back function, telling user that the the action is properly handled, etc.
File >> New Project >> Java Project With Existing Source>Next >> Project Name(add a name for your project) >> Next>>Add Folder >> select your existing project source code from your Directory>>Next >> Finish
Java Project With Existing Source
Easiest explanation:
I held down the 'd' key for a second and then released.
dddddd
the keydown event happened once before the first d appeared on the screen, the keypress event happened 6 times and the keyup event happened after the last d appeared on the screen.
don't try to do this
$ make action value1 value2
instead create script:
#! /bin/sh
# rebuild if necessary
make
# do action with arguments
action "$@"
and do this:
$ ./buildthenaction.sh value1 value2
for more explanation why do this and caveats of makefile hackery read my answer to another very similar but seemingly not duplicate question: Passing arguments to "make run"
An alternative to converting the image is to create an RGB index from the palette.
from PIL import Image
def chunk(seq, size, groupByList=True):
"""Returns list of lists/tuples broken up by size input"""
func = tuple
if groupByList:
func = list
return [func(seq[i:i + size]) for i in range(0, len(seq), size)]
def getPaletteInRgb(img):
"""
Returns list of RGB tuples found in the image palette
:type img: Image.Image
:rtype: list[tuple]
"""
assert img.mode == 'P', "image should be palette mode"
pal = img.getpalette()
colors = chunk(pal, 3, False)
return colors
# Usage
im = Image.open("image.gif")
pal = getPalletteInRgb(im)
I used MP4Box to decode the atom tags in the mp4. (MP4Box -v myfile.mp4) I also used ffmpeg to convert the mp41 to mp42. After comparing the differences and experimenting, I found that IE11 did not like that my original mp4 had two avC1 atoms inside stsd.
After deleting the duplicate avC1 in my original mp41 mp4, IE11 would play the mp4.
Some important facts were not given in other answers:
"async await" is more complex at CIL level and thus costs memory and CPU time.
Any task can be canceled if the waiting time is unacceptable.
In the case "async await" we do not have a handler for such a task to cancel it or monitoring it.
Using Task is more flexible then "async await".
Any sync functionality can by wrapped by async.
public async Task<ActionResult> DoAsync(long id)
{
return await Task.Run(() => { return DoSync(id); } );
}
"async await" generate many problems. We do not now is await statement will be reached without runtime and context debugging. If first await not reached everything is blocked. Some times even await seems to be reached still everything is blocked:
https://github.com/dotnet/runtime/issues/36063
I do not see why I'm must live with the code duplication for sync and async method or using hacks.
Conclusion: Create Task manually and control them is much better. Handler to Task give more control. We can monitor Tasks and manage them:
https://github.com/lsmolinski/MonitoredQueueBackgroundWorkItem
Sorry for my english.
Obviously you mean the baseurl. If so:
base url: URL to your CodeIgniter root. Typically this will be your base URL, | WITH a trailing slash.
Root in codeigniter specifically means that the position where you can append your controller to your url.
For example, if the root is localhost/ci_installation/index.php/
, then to access the mycont
controller you should go to localhost/ci_installation/index.php/mycont
.
So, instead of writing such a long link you can (after loading "url" helper) , replace the term localhost/ci_installation/index.php/
by base_url()
and this function will return the same string url.
NOTE: if you hadn't appended index.php/
to your base_url
in your config.php
, then if you use base_url()
, it will return something like that localhost/ci_installation/mycont
. And that will not work, because you have to access your controllers from index.php
, instead of that you can place a .htaccess
file to your codeigniter installation position. Cope that the below code to it:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /imguplod/index.php/$1 [L]
And it should work :)
I know this is a year old but I just came across it with the same problem. My problem was that I didn't have a constructor in my implementation file. I think the problem here could be the comment marks at the end of the header file after the #endif...
By the answer of rudivonstaden
txtBlock.Text = await response.Content.ReadAsStringAsync();
but if you don't want to make the method async you can use
txtBlock.Text = response.Content.ReadAsStringAsync();
txtBlock.Text.Wait();
Wait() it's important, bec?use we are doing async operations and we must wait for the task to complete before going ahead.
InputProperty[] ip = new InputProperty[nvPairs.Length];
Or, you can use a list like so:
List<InputProperty> list = new List<InputProperty>();
InputProperty ip = new (..);
list.Add(ip);
update.items = list.ToArray();
Another thing I'd like to point out, in C# you can delcare your int variable use in a for loop right inside the loop:
for(int i = 0; i<nvPairs.Length;i++
{
.
.
}
And just because I'm in the mood, here's a cleaner way to do this method IMO:
private Update BuildMetaData(MetaData[] nvPairs)
{
Update update = new Update();
var ip = new List<InputProperty>();
foreach(var nvPair in nvPairs)
{
if (nvPair == null) break;
var inputProp = new InputProperty
{
Name = "udf:" + nvPair.Name,
Val = nvPair.Value
};
ip.Add(inputProp);
}
update.Items = ip.ToArray();
return update;
}
Similar to answer above but without the absolute positioning:
<select style="width: 200px; float: left;" onchange="this.nextElementSibling.value=this.value">
<option></option>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<input style="width: 185px; margin-left: -199px; margin-top: 1px; border: none; float: left;"/>
So create a input box and put it over the top of the combobox
and
, or
:Let's first define a useful function to determine if something is executed or not. A simple function that accepts an argument, prints a message and returns the input, unchanged.
>>> def fun(i):
... print "executed"
... return i
...
One can observe the Python's short-circuiting behavior of and
, or
operators in the following example:
>>> fun(1)
executed
1
>>> 1 or fun(1) # due to short-circuiting "executed" not printed
1
>>> 1 and fun(1) # fun(1) called and "executed" printed
executed
1
>>> 0 and fun(1) # due to short-circuiting "executed" not printed
0
Note: The following values are considered by the interpreter to mean false:
False None 0 "" () [] {}
any()
, all()
:Python's any()
and all()
functions also support short-circuiting. As shown in the docs; they evaluate each element of a sequence in-order, until finding a result that allows an early exit in the evaluation. Consider examples below to understand both.
The function any()
checks if any element is True. It stops executing as soon as a True is encountered and returns True.
>>> any(fun(i) for i in [1, 2, 3, 4]) # bool(1) = True
executed
True
>>> any(fun(i) for i in [0, 2, 3, 4])
executed # bool(0) = False
executed # bool(2) = True
True
>>> any(fun(i) for i in [0, 0, 3, 4])
executed
executed
executed
True
The function all()
checks all elements are True and stops executing as soon as a False is encountered:
>>> all(fun(i) for i in [0, 0, 3, 4])
executed
False
>>> all(fun(i) for i in [1, 0, 3, 4])
executed
executed
False
Additionally, in Python
Comparisons can be chained arbitrarily; for example,
x < y <= z
is equivalent tox < y and y <= z
, except thaty
is evaluated only once (but in both casesz
is not evaluated at all whenx < y
is found to be false).
>>> 5 > 6 > fun(3) # same as: 5 > 6 and 6 > fun(3)
False # 5 > 6 is False so fun() not called and "executed" NOT printed
>>> 5 < 6 > fun(3) # 5 < 6 is True
executed # fun(3) called and "executed" printed
True
>>> 4 <= 6 > fun(7) # 4 <= 6 is True
executed # fun(3) called and "executed" printed
False
>>> 5 < fun(6) < 3 # only prints "executed" once
executed
False
>>> 5 < fun(6) and fun(6) < 3 # prints "executed" twice, because the second part executes it again
executed
executed
False
Edit:
One more interesting point to note :- Logical and
, or
operators in Python returns an operand's value instead of a Boolean (True
or False
). For example:
Operation
x and y
gives the resultif x is false, then x, else y
Unlike in other languages e.g. &&
, ||
operators in C that return either 0 or 1.
Examples:
>>> 3 and 5 # Second operand evaluated and returned
5
>>> 3 and ()
()
>>> () and 5 # Second operand NOT evaluated as first operand () is false
() # so first operand returned
Similarly or
operator return left most value for which bool(value)
== True
else right most false value (according to short-circuiting behavior), examples:
>>> 2 or 5 # left most operand bool(2) == True
2
>>> 0 or 5 # bool(0) == False and bool(5) == True
5
>>> 0 or ()
()
So, how is this useful? One example is given in Practical Python By Magnus Lie Hetland:
Let’s say a user is supposed to enter his or her name, but may opt to enter nothing, in which case you want to use the default value '<Unknown>'
.
You could use an if statement, but you could also state things very succinctly:
In [171]: name = raw_input('Enter Name: ') or '<Unknown>'
Enter Name:
In [172]: name
Out[172]: '<Unknown>'
In other words, if the return value from raw_input
is true (not an empty string), it is assigned to name (nothing changes); otherwise, the default '<Unknown>'
is assigned to name
.
I know this is an old post but I would like share my solution. I spent several hours trying to make a justified navigation menu. You do not really need to modify anything in bootstrap css. Just need to add the correct class in the html.
<nav class="nav navbar-default navbar-fixed-top">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#collapsable-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#top">Brand Name</a>
</div>
<div class="collapse navbar-collapse" id="collapsable-1">
<ul class="nav nav-justified">
<li><a href="#about-me">About Me</a></li>
<li><a href="#skills">Skills</a></li>
<li><a href="#projects">Projects</a></li>
<li><a href="#contact-me">Contact Me</a></li>
</ul>
</div>
</nav>
This CSS code will simply remove the navbar-brand class when the screen reaches 768px.
media@(min-width: 768px){
.navbar-brand{
display: none;
}
}
I prefer to do it in a more direct fashion. It does not have the Rows but is still has the array of rows.
tblCrm.DefaultView.RowFilter = "customertype = 'new'";
qtytotal = 0;
for (int i = 0; i < tblCrm.DefaultView.Count; i++)
{
result = double.TryParse(tblCrm.DefaultView[i]["qty"].ToString(), out num);
if (result == false) num = 0;
qtytotal = qtytotal + num;
}
labQty.Text = qtytotal.ToString();
curl -X GET -u username:password {{ http://www.example.com/filename.txt }} -O
1.
To_Date(To_Char(MaxDate, 'DD/MM/YYYY')) = REP_DATE
is causing the issue. when you use to_date without the time format, oracle will use the current sessions NLS format to convert, which in your case might not be "DD/MM/YYYY". Check this...
SQL> select sysdate from dual;
SYSDATE
---------
26-SEP-12
Which means my session's setting is DD-Mon-YY
SQL> select to_char(sysdate,'MM/DD/YYYY') from dual;
TO_CHAR(SY
----------
09/26/2012
SQL> select to_date(to_char(sysdate,'MM/DD/YYYY')) from dual;
select to_date(to_char(sysdate,'MM/DD/YYYY')) from dual
*
ERROR at line 1:
ORA-01843: not a valid month
SQL> select to_date(to_char(sysdate,'MM/DD/YYYY'),'MM/DD/YYYY') from dual;
TO_DATE(T
---------
26-SEP-12
2.
More importantly, Why are you converting to char and then to date, instead of directly comparing
MaxDate = REP_DATE
If you want to ignore the time component in MaxDate before comparision, you should use..
trunc(MaxDate ) = rep_date
instead.
==Update : based on updated question.
Rep_Date = 01/04/2009 Rep_Time = 01/01/1753 13:00:00
I think the problem is more complex. if rep_time is intended to be only time, then you cannot store it in the database as a date. It would have to be a string or date to time interval or numerically as seconds (thanks to Alex, see this) . If possible, I would suggest using one column rep_date that has both the date and time and compare it to the max date column directly.
If it is a running system and you have no control over repdate, you could try this.
trunc(rep_date) = trunc(maxdate) and
to_char(rep_date,'HH24:MI:SS') = to_char(maxdate,'HH24:MI:SS')
Either way, the time is being stored incorrectly (as you can tell from the year 1753) and there could be other issues going forward.
I think I see your problem, you need to use the @
syntax to define parameters you will pass in this way, also I'm not sure what loginID or password are doing you don't seem to define them anywhere and they are not being used as URL parameters so are they being sent as query parameters?
This is what I can suggest based on what I see so far:
.factory('MagComments', function ($resource) {
return $resource('http://localhost/dooleystand/ci/api/magCommenct/:id', {
loginID : organEntity,
password : organCommpassword,
id : '@magId'
});
})
The @magId
string will tell the resource to replace :id
with the property magId
on the object you pass it as parameters.
I'd suggest reading over the documentation here (I know it's a bit opaque) very carefully and looking at the examples towards the end, this should help a lot.
Another working example:
var zlib = require('zlib');
var tar = require('tar');
var ftp = require('ftp');
var files = [];
var conn = new ftp();
conn.on('connect', function(e)
{
conn.auth(function(e)
{
if (e)
{
throw e;
}
conn.get('/tz/tzdata-latest.tar.gz', function(e, stream)
{
stream.on('success', function()
{
conn.end();
console.log("Processing files ...");
for (var name in files)
{
var file = files[name];
console.log("filename: " + name);
console.log(file);
}
console.log("OK")
});
stream.on('error', function(e)
{
console.log('ERROR during get(): ' + e);
conn.end();
});
console.log("Reading ...");
stream
.pipe(zlib.createGunzip())
.pipe(tar.Parse())
.on("entry", function (e)
{
var filename = e.props["path"];
console.log("filename:" + filename);
if( files[filename] == null )
{
files[filename] = "";
}
e.on("data", function (c)
{
files[filename] += c.toString();
})
});
});
});
})
.connect(21, "ftp.iana.org");
If you add -chain to your command line, it will export any chained certificates.
I've found that the best (and easiest) way to delete leading, trailing (and excessive) spaces in Excel is to use a third-party plugin. I've been using ASAP Utilities for Excel and it accomplishes the task as well as adds many other much-needed features. This approach doesn't require writing formulas and can remove spaces on any selection spanning multiple columns and/or rows. I also use this to sanitize and remove the uninvited non-breaking space that often finds its way into Excel data when copying-and-pasting from other Microsoft products.
More information regarding ASAP Utilities and trimming can be found here:
http://www.asap-utilities.com/asap-utilities-excel-tools-tip.php?tip=87
You are asking a lot of questions that you could answer yourself by reading the documentation, so I'll give you a general advice: read it and experiment in the python shell. You'll see that itemgetter
returns a callable:
>>> func = operator.itemgetter(1)
>>> func(a)
['Paul', 22, 'Car Dealer']
>>> func(a[0])
8
To do it in a different way, you can use lambda
:
a.sort(key=lambda x: x[1])
And reverse it:
a.sort(key=operator.itemgetter(1), reverse=True)
Sort by more than one column:
a.sort(key=operator.itemgetter(1,2))
See the sorting How To.
I think you try to get the remote host of the conneting user...
You can get a String like 'myuser@localhost' from the command:
SELECT USER()
You can split this result on the '@' sign, to get the parts:
-- delivers the "remote_host" e.g. "localhost"
SELECT SUBSTRING_INDEX(USER(), '@', -1)
-- delivers the user-name e.g. "myuser"
SELECT SUBSTRING_INDEX(USER(), '@', 1)
if you are conneting via ip address you will get the ipadress instead of the hostname.
Annotate type and gender properties with @XmlAttribute
and the description property with @XmlValue
:
package org.example.sport;
import javax.xml.bind.annotation.*;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
public class Sport {
@XmlAttribute
protected String type;
@XmlAttribute
protected String gender;
@XmlValue;
protected String description;
}
For More Information
IE11 uses an older version of the Grid specification.
The properties you are using don't exist in the older grid spec. Using prefixes makes no difference.
Here are three problems I see right off the bat.
repeat()
The repeat()
function doesn't exist in the older spec, so it isn't supported by IE11.
You need to use the correct syntax, which is covered in another answer to this post, or declare all row and column lengths.
Instead of:
.grid {
display: -ms-grid;
display: grid;
-ms-grid-columns: repeat( 4, 1fr );
grid-template-columns: repeat( 4, 1fr );
-ms-grid-rows: repeat( 4, 270px );
grid-template-rows: repeat( 4, 270px );
grid-gap: 30px;
}
Use:
.grid {
display: -ms-grid;
display: grid;
-ms-grid-columns: 1fr 1fr 1fr 1fr; /* adjusted */
grid-template-columns: repeat( 4, 1fr );
-ms-grid-rows: 270px 270px 270px 270px; /* adjusted */
grid-template-rows: repeat( 4, 270px );
grid-gap: 30px;
}
Older spec reference: https://www.w3.org/TR/2011/WD-css3-grid-layout-20110407/#grid-repeating-columns-and-rows
span
The span
keyword doesn't exist in the older spec, so it isn't supported by IE11. You'll have to use the equivalent properties for these browsers.
Instead of:
.grid .grid-item.height-2x {
-ms-grid-row: span 2;
grid-row: span 2;
}
.grid .grid-item.width-2x {
-ms-grid-column: span 2;
grid-column: span 2;
}
Use:
.grid .grid-item.height-2x {
-ms-grid-row-span: 2; /* adjusted */
grid-row: span 2;
}
.grid .grid-item.width-2x {
-ms-grid-column-span: 2; /* adjusted */
grid-column: span 2;
}
Older spec reference: https://www.w3.org/TR/2011/WD-css3-grid-layout-20110407/#grid-row-span-and-grid-column-span
grid-gap
The grid-gap
property, as well as its long-hand forms grid-column-gap
and grid-row-gap
, don't exist in the older spec, so they aren't supported by IE11. You'll have to find another way to separate the boxes. I haven't read the entire older spec, so there may be a method. Otherwise, try margins.
There was some discussion in the old spec about grid item auto placement, but the feature was never implemented in IE11. (Auto placement of grid items is now standard in current browsers).
So unless you specifically define the placement of grid items, they will stack in cell 1,1.
Use the -ms-grid-row
and -ms-grid-column
properties.
I think using react-native-responsive-dimensions
might help you a little better on your case.
You can still get:
device-width by using and responsiveScreenWidth(100)
and
device-height by using and responsiveScreenHeight(100)
You also can more easily arrange the locations of your absolute components by setting margins and position values with proportioning it over 100% of the width and height
While your mileage may vary, running npm cache verify
fixed the issue for me.
You might be best starting with reading this post by Dan Abramov where he discusses various implementations of Flux and their trade-offs at the time he was writing redux: The Evolution of Flux Frameworks
Secondly that motivations page you link to does not really discuss the motivations of Redux so much as the motivations behind Flux (and React). The Three Principles is more Redux specific though still does not deal with the implementation differences from the standard Flux architecture.
Basically, Flux has multiple stores that compute state change in response to UI/API interactions with components and broadcast these changes as events that components can subscribe to. In Redux, there is only one store that every component subscribes to. IMO it feels at least like Redux further simplifies and unifies the flow of data by unifying (or reducing, as Redux would say) the flow of data back to the components - whereas Flux concentrates on unifying the other side of the data flow - view to model.
You have to modify the control template instead of ItemsPanelTemplate:
<ItemsControl >
<ItemsControl.Template>
<ControlTemplate>
<ScrollViewer x:Name="ScrollViewer" Padding="{TemplateBinding Padding}">
<ItemsPresenter />
</ScrollViewer>
</ControlTemplate>
</ItemsControl.Template>
</ItemsControl>
Maybe, your code does not working because StackPanel has own scrolling functionality. Try to use StackPanel.CanVerticallyScroll property.
For footer change from position: relative;
to position:fixed;
footer {
background-color: #333;
width: 100%;
bottom: 0;
position: fixed;
}
Example: http://jsfiddle.net/a6RBm/
Enter "SA" instead of "sa" in the owner textbox. This worked for me.
There are two types of drop down lists available (I am not sure since which version).
ActiveX Drop Down
You can set the column widths, so your hidden column can be set to 0.
Form Drop Down
You could set the drop down range to a hidden sheet and reference the cell adjacent to the selected item. This would also work with the ActiveX type control.
http://www.erichynds.com/jquery/jquery-ui-multiselect-widget/
I found that the only way to get the cursor to effectively reset its style back to what it had prior to being changed to the wait style was to set the original style in a style sheet or in style tags at the start of the page, set the class of the object in question to the name of the style. Then after your wait period, you set the cursor style back to an empty string, NOT "default" and it reverts back to its original value as set in your style tags or style sheet. Setting it to "default" after the wait period only changes the cursor style for every element to the style called "default" which is a pointer. It doesn't change it back to its former value.
There are two conditions to make this work. First you must set the style in a style sheet or in the header of the page with style tags, NOT as an inline style and second is to reset its style by setting the wait style back to an empty string.
I don't think location.LatLng
is working, however this works:
results[0].geometry.location.lat(), results[0].geometry.location.lng()
Found it while exploring Get Lat Lon source code.
I recently wrote a module called keysight that translates keypress
, keydown
, and keyup
events into characters and keys respectively.
Example:
element.addEventListener("keydown", function(event) {
var character = keysight(event).char
})
First, I am copying all values of arrays into a single array then I am removing duplicates values into the array. Line 12, explaining if same number occur more than time then put some extra garbage value into "j" position. At the end, traverse from start-end and check if same garbage value occur then discard.
public class Union {
public static void main(String[] args){
int arr1[]={1,3,3,2,4,2,3,3,5,2,1,99};
int arr2[]={1,3,2,1,3,2,4,6,3,4};
int arr3[]=new int[arr1.length+arr2.length];
for(int i=0;i<arr1.length;i++)
arr3[i]=arr1[i];
for(int i=0;i<arr2.length;i++)
arr3[arr1.length+i]=arr2[i];
System.out.println(Arrays.toString(arr3));
for(int i=0;i<arr3.length;i++)
{
for(int j=i+1;j<arr3.length;j++)
{
if(arr3[i]==arr3[j])
arr3[j]=99999999; //line 12
}
}
for(int i=0;i<arr3.length;i++)
{
if(arr3[i]!=99999999)
System.out.print(arr3[i]+" ");
}
}
}
I had this problem when using Butterknife library. I had:
View rootView = inflater.inflate
(R.layout.fragment_recipe_detail_view, container, false);
ButterKnife.bind(rootView);
But the correct version is:
View rootView = inflater.inflate
(R.layout.fragment_recipe_detail_view, container, false);
ButterKnife.bind(this, rootView);
As well as pointers and references to incomplete types, you can also declare function prototypes that specify parameters and/or return values that are incomplete types. However, you cannot define a function having a parameter or return type that is incomplete, unless it is a pointer or reference.
Examples:
struct X; // Forward declaration of X
void f1(X* px) {} // Legal: can always use a pointer
void f2(X& x) {} // Legal: can always use a reference
X f3(int); // Legal: return value in function prototype
void f4(X); // Legal: parameter in function prototype
void f5(X) {} // ILLEGAL: *definitions* require complete types
Using location.go(url)
is the way to go, but instead of hardcoding the url , consider generating it using router.createUrlTree()
.
Given that you want to do the following router call: this.router.navigate([{param: 1}], {relativeTo: this.activatedRoute})
but without reloading the component, it can be rewritten as:
const url = this.router.createUrlTree([], {relativeTo: this.activatedRoute, queryParams: {param: 1}}).toString()
this.location.go(url);
It seems strange, but nonetheless HTML5 supports drawing lines, circles, rectangles and many other basic shapes, it does not have anything suitable for drawing the basic point. The only way to do so is to simulate a point with whatever you have.
So basically there are 3 possible solutions:
Each of them has their drawbacks.
Line
function point(x, y, canvas){
canvas.beginPath();
canvas.moveTo(x, y);
canvas.lineTo(x+1, y+1);
canvas.stroke();
}
Keep in mind that we are drawing to South-East direction, and if this is the edge, there can be a problem. But you can also draw in any other direction.
Rectangle
function point(x, y, canvas){
canvas.strokeRect(x,y,1,1);
}
or in a faster way using fillRect because render engine will just fill one pixel.
function point(x, y, canvas){
canvas.fillRect(x,y,1,1);
}
Circle
One of the problems with circles is that it is harder for an engine to render them
function point(x, y, canvas){
canvas.beginPath();
canvas.arc(x, y, 1, 0, 2 * Math.PI, true);
canvas.stroke();
}
the same idea as with rectangle you can achieve with fill.
function point(x, y, canvas){
canvas.beginPath();
canvas.arc(x, y, 1, 0, 2 * Math.PI, true);
canvas.fill();
}
Problems with all these solutions:
If you are wondering, what is the best way to draw a point, I would go with filled rectangle. You can see my jsperf here with comparison tests
<html>
<body>
<p>Enter some text in the fields below, and then press the "Submit form" button to submit the form.</p>
<form id="myForm" action="/action_page.php">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br><br>
<input type="button" onclick="myFunction()" value="Submit form">
</form>
<script>
function myFunction() {
document.getElementById("myForm").submit();
}
</script>
</body>
</html>
use position:fixed
instead of position:absolute
The first one is relative to your screen window. (not affected by scrolling)
The second one is relative to the page. (affected by scrolling)
Note : IE6 doesn't support position:fixed.
Change:
data: JSON.stringify({ model: source })
To:
data: {model: JSON.stringify(source)}
And in your controller you do this:
public void PartSourceAPI(string model)
{
System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
var result = js.Deserialize<PartSourceModel>(model);
}
If the url you use in jquery is /api/PartSourceAPI
then the controller name must be api
and the action(method) should be PartSourceAPI
/
^ # start of string
( # first group start
(?:
(?:[^?+*{}()[\]\\|]+ # literals and ^, $
| \\. # escaped characters
| \[ (?: \^?\\. | \^[^\\] | [^\\^] ) # character classes
(?: [^\]\\]+ | \\. )* \]
| \( (?:\?[:=!]|\?<[=!]|\?>)? (?1)?? \) # parenthesis, with recursive content
| \(\? (?:R|[+-]?\d+) \) # recursive matching
)
(?: (?:[?+*]|\{\d+(?:,\d*)?\}) [?+]? )? # quantifiers
| \| # alternative
)* # repeat content
) # end first group
$ # end of string
/
This is a recursive regex, and is not supported by many regex engines. PCRE based ones should support it.
Without whitespace and comments:
/^((?:(?:[^?+*{}()[\]\\|]+|\\.|\[(?:\^?\\.|\^[^\\]|[^\\^])(?:[^\]\\]+|\\.)*\]|\((?:\?[:=!]|\?<[=!]|\?>)?(?1)??\)|\(\?(?:R|[+-]?\d+)\))(?:(?:[?+*]|\{\d+(?:,\d*)?\})[?+]?)?|\|)*)$/
.NET does not support recursion directly. (The (?1)
and (?R)
constructs.) The recursion would have to be converted to counting balanced groups:
^ # start of string
(?:
(?: [^?+*{}()[\]\\|]+ # literals and ^, $
| \\. # escaped characters
| \[ (?: \^?\\. | \^[^\\] | [^\\^] ) # character classes
(?: [^\]\\]+ | \\. )* \]
| \( (?:\?[:=!]
| \?<[=!]
| \?>
| \?<[^\W\d]\w*>
| \?'[^\W\d]\w*'
)? # opening of group
(?<N>) # increment counter
| \) # closing of group
(?<-N>) # decrement counter
)
(?: (?:[?+*]|\{\d+(?:,\d*)?\}) [?+]? )? # quantifiers
| \| # alternative
)* # repeat content
$ # end of string
(?(N)(?!)) # fail if counter is non-zero.
Compacted:
^(?:(?:[^?+*{}()[\]\\|]+|\\.|\[(?:\^?\\.|\^[^\\]|[^\\^])(?:[^\]\\]+|\\.)*\]|\((?:\?[:=!]|\?<[=!]|\?>|\?<[^\W\d]\w*>|\?'[^\W\d]\w*')?(?<N>)|\)(?<-N>))(?:(?:[?+*]|\{\d+(?:,\d*)?\})[?+]?)?|\|)*$(?(N)(?!))
From the comments:
Will this validate substitutions and translations?
It will validate just the regex part of substitutions and translations. s/<this part>/.../
It is not theoretically possible to match all valid regex grammars with a regex.
It is possible if the regex engine supports recursion, such as PCRE, but that can't really be called regular expressions any more.
Indeed, a "recursive regular expression" is not a regular expression. But this an often-accepted extension to regex engines... Ironically, this extended regex doesn't match extended regexes.
"In theory, theory and practice are the same. In practice, they're not." Almost everyone who knows regular expressions knows that regular expressions does not support recursion. But PCRE and most other implementations support much more than basic regular expressions.
using this with shell script in the grep command , it shows me some error.. grep: Invalid content of {} . I am making a script that could grep a code base to find all the files that contain regular expressions
This pattern exploits an extension called recursive regular expressions. This is not supported by the POSIX flavor of regex. You could try with the -P switch, to enable the PCRE regex flavor.
Regex itself "is not a regular language and hence cannot be parsed by regular expression..."
This is true for classical regular expressions. Some modern implementations allow recursion, which makes it into a Context Free language, although it is somewhat verbose for this task.
I see where you're matching
[]()/\
. and other special regex characters. Where are you allowing non-special characters? It seems like this will match^(?:[\.]+)$
, but not^abcdefg$
. That's a valid regex.
[^?+*{}()[\]\\|]
will match any single character, not part of any of the other constructs. This includes both literal (a
- z
), and certain special characters (^
, $
, .
).
Repository selection screen cannot be shown on your system (OS X), since OS X no longer includes X11. R tries to show you the prompt through X11. Install X11 from http://xquartz.macosforge.org/landing/. Then run the install command. The repo selection prompt will be shown.
Try adding window
before location
(i.e. window.location
).
In case you want to download the repo from your shell/terminal it should work like this:
wget https://user:[email protected]/user-name/repo-name/get/master.tar.bz2
or whatever download URL you might have.
Please make sure the user:password are both URL-encoded. So for instance if your username contains the @
symbol then replace it with %40
.
The Decimal value type represents decimal numbers ranging from positive 79,228,162,514,264,337,593,543,950,335 to negative 79,228,162,514,264,337,593,543,950,335. The Decimal value type is appropriate for financial calculations requiring large numbers of significant integral and fractional digits and no round-off errors. The Decimal type does not eliminate the need for rounding. Rather, it minimizes errors due to rounding.
I'd like to point to this excellent answer by zneak on why double shouldn't be used.
One additional information I just one to add is that a PATCH request use less bandwidth compared to a PUT request since just a part of the data is sent not the whole entity. So just use a PATCH request for updates of specific records like (1-3 records) while PUT request for updating a larger amount of data. That is it, don't think too much or worry about it too much.
Try this:
DataTable dt = new DataTable();
int sum = 0;
foreach (DataRow dr in dt.Rows)
{
foreach (DataColumn dc in dt.Columns)
{
sum += (int)dr[dc];
}
}
This is a JQuery code for Preventing Submit
$('form').submit(function (e) {
if (radioButtonValue !== "0") {
e.preventDefault();
}
});
When Object variables are initially used in a language like Java, they have absolutely no value at all - not zero, but literally no value - that is null
For instance: String s;
If you were to use s
, it would actually have a value of null
, because it holds absolute nothing.
An empty string, however, is a value - it is a string of no characters.
String s; //Inits to null
String a =""; //A blank string
Null
is essentially 'nothing' - it's the default 'value' (to use the term loosely) that Java assigns to any Object variable that was not initialized.
Null
isn't really a value - and as such, doesn't have properties. So, calling anything that is meant to return a value - such as .length()
, will invariably return an error, because 'nothing' cannot have properties.
To go into more depth, by creating s1 = "";
you are initializing an object, which can have properties, and takes up relevant space in memory. By using s2;
you are designating that variable name to be a String, but are not actually assigning any value at that point.
If the IE example doesn't work use this one. Anyway this should be faster than starting up an instance of IE.
Here is a complete solution based on
http://www.dailydoseofexcel.com/archives/2005/02/23/html-in-cells-ii/
Note, if your innerHTML is all numbers eg '12345', HTML formatting dosen't fully work in excel as it treats number differently? but add a character eg a trailing space at the end eg. 12345 + "& nbsp;" formats ok.
Sub test()
Cells(1, 1).Value = "<HTML>1<font color=blue>a</font>" & _
"23<font color=red>4</font></HTML>"
Dim rng As Range
Set rng = ActiveSheet.Cells(1, 1)
Worksheet_Change rng, ActiveSheet
End Sub
Private Sub Worksheet_Change(ByVal Target As Range, ByVal sht As Worksheet)
Dim objData As DataObject ' Set a reference to MS Forms 2.0
Dim sHTML As String
Dim sSelAdd As String
Application.EnableEvents = False
If Target.Cells.Count = 1 Then
Set objData = New DataObject
sHTML = Target.Text
objData.SetText sHTML
objData.PutInClipboard
Target.Select
sht.PasteSpecial Format:="Unicode Text"
End If
Application.EnableEvents = True
End Sub
Another way of dealing with this situation if your files ARE already checked in, and your files have been merged (but not committed, so the merge conflicts are inserted into the file) is to run:
git reset
This will switch to HEAD, and tell git to forget any merge conflicts, and leave the working directory as is. Then you can edit the files in question (search for the "Updated upstream" notices). Once you've dealt with the conflicts, you can run
git add -p
which will allow you to interactively select which changes you want to add to the index. Once the index looks good (git diff --cached
), you can commit, and then
git reset --hard
to destroy all the unwanted changes in your working directory.
We here use simply linear search. At first initialize the index equal to -1 . Then search the array , if found the assign the index value in index variable and break. Otherwise, index = -1.
int find(int arr[], int n, int key)
{
int index = -1;
for(int i=0; i<n; i++)
{
if(arr[i]==key)
{
index=i;
break;
}
}
return index;
}
int main()
{
int arr[ 5 ] = { 4, 1, 3, 2, 6 };
int n = sizeof(arr)/sizeof(arr[0]);
int x = find(arr ,n, 3);
cout<<x<<endl;
return 0;
}
Mark your package/directory as Test Sources in your IntelliJ IDEA.
Here is an updated method with syntax that is more common in python code. It also prevents you from opening the same file multiple times.
import pandas as pd
sheet1, sheet2 = None, None
with pd.ExcelFile("PATH\FileName.xlsx") as reader:
sheet1 = pd.read_excel(reader, sheet_name='Sheet1')
sheet2 = pd.read_excel(reader, sheet_name='Sheet2')
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html
In case of writing in python3
>>> a = u'bats\u00E0'
>>> print a
batsà
>>> f = open("/tmp/test", "w")
>>> f.write(a)
>>> f.close()
>>> data = open("/tmp/test").read()
>>> data
'batsà'
In case of writing in python2:
>>> a = u'bats\u00E0'
>>> f = open("/tmp/test", "w")
>>> f.write(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe0' in position 4: ordinal not in range(128)
To avoid this error you would have to encode it to bytes using codecs "utf-8" like this:
>>> f.write(a.encode("utf-8"))
>>> f.close()
and decode the data while reading using the codecs "utf-8":
>>> data = open("/tmp/test").read()
>>> data.decode("utf-8")
u'bats\xe0'
And also if you try to execute print on this string it will automatically decode using the "utf-8" codecs like this
>>> print a
batsà
It will work both, but personally I'd prefer option 2 so the span is "around" the link.
It's all in the tutorial how to do that:
ContentValues args = new ContentValues();
args.put(columnName, newValue);
db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null);
Use ContentValues
to set the updated columns and than the update()
method in which you have to specifiy, the table and a criteria to only update the rows you want to update.
Try the following:
<c:set var="count" value="0" scope="page" />
//in your loops
<c:set var="count" value="${count + 1}" scope="page"/>
To recognise your Tomcat installation folder, Eclipse is scanning for the following files:
conf/catalina.policy
conf/server.xml
conf/web.xml
conf/context.xml
conf/tomcat-users.xml
conf/catalina.policy
conf/catalina.properties
lib/catalina.jar
so make sure you're pointing to the right place and have the right read permissions.
E.g.
brew
), it's: /usr/local/opt/tomcat/libexec
Fundamentally you hadn't declare location which is what nginx uses to bind URL with resources.
server {
listen 80;
server_name localhost;
access_log logs/localhost.access.log main;
location / {
root /var/www/board/public;
index index.html index.htm index.php;
}
}
You are using go install on a directory outside the GOPATH folder. Set your GOBIN env variable, or move src folder inside GOPATH.
GOPATH/
bin/
src/
go-statsd-client/
More info: GO BUILD Source code, line 296
As JavaScript is a client-side language and PHP is a server-side language you would need to physically push the variable to the PHP script, by either including the variable on the page load of the PHP script (script.php?var=test), which really has nothing to do with JavaScript, or by passing the variable to the PHP via an AJAX/AHAH call each time the variable is changed.
If you did want to go down the second path, you'd be looking at XMLHttpRequest, or my preference, jQuerys Ajax calls: http://docs.jquery.com/Ajax
If anyone stumbles across this and NEITHER Invalidate Cache
or Update Kotlin's Version
work:
1) First, make sure you can build it from outside the IDE. If you're using gradle
, for instance:
gradle clean build
If everything goes well , then your environment is all good to work with Kotlin
.
2) To fix the IDE build, try the following:
Project Structure -> {Select Module} -> Kotlin -> FIX
As suggested by a JetBrain's member here: https://discuss.kotlinlang.org/t/intellij-kotlin-project-screw-up/597
The problem I found was even sillier than what other folks have mentioned.
Our makefiles get passed lists of things to build. Someone added TheOtherLibrary
to one of the lists, as shown below.
LIBRARYDIRS = src/Library
LIBRARYDIRS = src/TheOtherLibrary
They should have done this:
LIBRARYDIRS = src/Library
LIBRARYDIRS += src/TheOtherLibrary
Had they done it the second way, they would not have wiped out the Library
build. The plus in +=
is very important.
You can get the first column as a Series by following code:
x[x.columns[0]]
Not append()
but appends()
So, right answer is:
{!! $records->appends(Input::except('page'))->links() !!}
Try to surround the path with quotes, and remove the spaces
export PYTHONPATH="/home/user/my_project":$PYTHONPATH
And don't forget to preserve previous content suffixing by :$PYTHONPATH (which is the value of the variable)
Execute the following command to check everything is configured correctly:
echo $PYTHONPATH
A few comments:
analog=True
in the call to butter
, and you should use scipy.signal.freqz
(not freqs
) to generate the frequency response.Here's my modified version of your script, followed by the plot that it generates.
import numpy as np
from scipy.signal import butter, lfilter, freqz
import matplotlib.pyplot as plt
def butter_lowpass(cutoff, fs, order=5):
nyq = 0.5 * fs
normal_cutoff = cutoff / nyq
b, a = butter(order, normal_cutoff, btype='low', analog=False)
return b, a
def butter_lowpass_filter(data, cutoff, fs, order=5):
b, a = butter_lowpass(cutoff, fs, order=order)
y = lfilter(b, a, data)
return y
# Filter requirements.
order = 6
fs = 30.0 # sample rate, Hz
cutoff = 3.667 # desired cutoff frequency of the filter, Hz
# Get the filter coefficients so we can check its frequency response.
b, a = butter_lowpass(cutoff, fs, order)
# Plot the frequency response.
w, h = freqz(b, a, worN=8000)
plt.subplot(2, 1, 1)
plt.plot(0.5*fs*w/np.pi, np.abs(h), 'b')
plt.plot(cutoff, 0.5*np.sqrt(2), 'ko')
plt.axvline(cutoff, color='k')
plt.xlim(0, 0.5*fs)
plt.title("Lowpass Filter Frequency Response")
plt.xlabel('Frequency [Hz]')
plt.grid()
# Demonstrate the use of the filter.
# First make some data to be filtered.
T = 5.0 # seconds
n = int(T * fs) # total number of samples
t = np.linspace(0, T, n, endpoint=False)
# "Noisy" data. We want to recover the 1.2 Hz signal from this.
data = np.sin(1.2*2*np.pi*t) + 1.5*np.cos(9*2*np.pi*t) + 0.5*np.sin(12.0*2*np.pi*t)
# Filter the data, and plot both the original and filtered signals.
y = butter_lowpass_filter(data, cutoff, fs, order)
plt.subplot(2, 1, 2)
plt.plot(t, data, 'b-', label='data')
plt.plot(t, y, 'g-', linewidth=2, label='filtered data')
plt.xlabel('Time [sec]')
plt.grid()
plt.legend()
plt.subplots_adjust(hspace=0.35)
plt.show()
Coming late to the party, but I found this fantastic step-by-step guide on getting control of your SQLExpress instance if you don't have your sa password. I used this process to not only reset my sa password, but I also added my domain account to all the available server roles. I can now create databases, alter logins, do bulk operations, backups/restores, etc using my normal login.
To summarize, you use SQL Server Configuration Manager to put your instance into single-user mode. This elevates you to sysadmin when you connect, allowing you the ability to set everything up.
Edit: I've copied the steps below - kudos to the original author of the link above.
Go to the project explorer block ... right click on project name select "Build Path"-----------> "Configuration Build Path"
then the pop up window will get open.
in this pop up window you will find 4 tabs. 1)source 2) project 3)Library 4)order and export
Click on 1) Source
select the project (under which that file is present which you want to compile)
and then click on ok....
Go to the workspace location of the project open a bin folder and search that class file ...
you will get that java file compiled...
just to cross verify check the changed timing.
hope this will help.
Thanks.
<input name="submitBnt" type="submit" value="like"/>
name is useful when using $_POST
in php and also in javascript as document.getElementByName('submitBnt')
.
Also you can use name as a CS selector like input[name="submitBnt"]
;
Hope this helps
private List<DataValue> datavalue=new ArrayList<Datavalue>;
@Override
public View getView(int position, View view, ViewGroup viewGroup) {
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
datavalue.remove(position);
notifyDataSetChanged();
}
});
}
}
Sure, a very similar question was asked before. Set the controller for ajax requests:
public ActionResult Show()
{
if (Request.IsAjaxRequest())
{
return PartialView("Your_partial_view", new Model());
}
else
{
return View();
}
}
Set the action link as wanted:
@Ajax.ActionLink("Show",
"Show",
null,
new AjaxOptions { HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "dialog_window_id",
OnComplete = "your_js_function();" })
Note that I'm using Razor view engine, and that your AjaxOptions may vary depending on what you want. Finally display it on a modal window. The jQuery UI dialog is suggested.
While writing to S3, you need to specify the length of S3 object to be sure that there are no out of memory errors.
Using IOUtils.toByteArray(stream)
is also prone to OOM errors because this is backed by ByteArrayOutputStream
So, the best option is to first write the inputstream to a temp file on local disk and then use that file to write to S3 by specifying the length of temp file.
You have to create two triggers, but you can move the common code into a procedure and have them both call the procedure.
just you need to use couple of methods for this, that's it!
var strVale = "130,235,342,124";
var resultArray = strVale.split(',').map(function(strVale){return Number(strVale);});
the output will be the array of numbers.
You're correct, length
is a data member, not a method.
From the Arrays tutorial:
The length of an array is established when the array is created. After creation, its length is fixed.
put below tag in web.config file in configuration node
<connectionStrings>
<add name="NameOFConnectionString" connectionString="Data Source=Server;Initial Catalog=DatabaseName;User ID=User;Password=Pwd"
providerName="System.Data.SqlClient" />
then you can use above connectionstring, e.g.
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["NameOFConnectionString"].ToString();
$('.date-pick').datePicker().val(new Date()).trigger('change')
finally, that what i look for the last few hours! I need initiate changes, not just setup date in text field!
I came across this question as I was attempting to focus the ChromeVox screen reader to the top of the "screen" after navigating to a new screen in a React single page app. Basically trying to emulate what would happen if this page was loaded by following a link to a new server-rendered web page.
This solution doesn't require any listeners, it uses withRouter()
and the componentDidUpdate()
lifecycle method to trigger a click to focus ChromeVox on the desired element when navigating to a new url path.
I created a "Screen" component which is wrapped around the react-router switch tag which contains all the apps screens.
<Screen>
<Switch>
... add <Route> for each screen here...
</Switch>
</Screen>
Screen.tsx
ComponentNote: This component uses React + TypeScript
import React from 'react'
import { RouteComponentProps, withRouter } from 'react-router'
class Screen extends React.Component<RouteComponentProps> {
public screen = React.createRef<HTMLDivElement>()
public componentDidUpdate = (prevProps: RouteComponentProps) => {
if (this.props.location.pathname !== prevProps.location.pathname) {
// Hack: setTimeout delays click until end of current
// event loop to ensure new screen has mounted.
window.setTimeout(() => {
this.screen.current!.click()
}, 0)
}
}
public render() {
return <div ref={this.screen}>{this.props.children}</div>
}
}
export default withRouter(Screen)
I had tried using focus()
instead of click()
, but click causes ChromeVox to stop reading whatever it is currently reading and start again where I tell it to start.
Advanced note: In this solution, the navigation <nav>
which inside the Screen component and rendered after the <main>
content is visually positioned above the main
using css order: -1;
. So in pseudo code:
<Screen style={{ display: 'flex' }}>
<main>
<nav style={{ order: -1 }}>
<Screen>
If you have any thoughts, comments, or tips about this solution, please add a comment.
I got this error because i was dispatching redux actions in modal and modal was not opened at that time. I was dispatching actions the moment modal component recieve input. So i put setTimeout there in order to make sure that modal is opened and then actions are dipatched.
Just use
from IPython.display import Image
Image('image.png')
As a LinearSegmentedColormaps
is based on a dictionary of red, green and blue, it's necessary to reverse each item:
import matplotlib.pyplot as plt
import matplotlib as mpl
def reverse_colourmap(cmap, name = 'my_cmap_r'):
"""
In:
cmap, name
Out:
my_cmap_r
Explanation:
t[0] goes from 0 to 1
row i: x y0 y1 -> t[0] t[1] t[2]
/
/
row i+1: x y0 y1 -> t[n] t[1] t[2]
so the inverse should do the same:
row i+1: x y1 y0 -> 1-t[0] t[2] t[1]
/
/
row i: x y1 y0 -> 1-t[n] t[2] t[1]
"""
reverse = []
k = []
for key in cmap._segmentdata:
k.append(key)
channel = cmap._segmentdata[key]
data = []
for t in channel:
data.append((1-t[0],t[2],t[1]))
reverse.append(sorted(data))
LinearL = dict(zip(k,reverse))
my_cmap_r = mpl.colors.LinearSegmentedColormap(name, LinearL)
return my_cmap_r
See that it works:
my_cmap
<matplotlib.colors.LinearSegmentedColormap at 0xd5a0518>
my_cmap_r = reverse_colourmap(my_cmap)
fig = plt.figure(figsize=(8, 2))
ax1 = fig.add_axes([0.05, 0.80, 0.9, 0.15])
ax2 = fig.add_axes([0.05, 0.475, 0.9, 0.15])
norm = mpl.colors.Normalize(vmin=0, vmax=1)
cb1 = mpl.colorbar.ColorbarBase(ax1, cmap = my_cmap, norm=norm,orientation='horizontal')
cb2 = mpl.colorbar.ColorbarBase(ax2, cmap = my_cmap_r, norm=norm, orientation='horizontal')
EDIT
I don't get the comment of user3445587. It works fine on the rainbow colormap:
cmap = mpl.cm.jet
cmap_r = reverse_colourmap(cmap)
fig = plt.figure(figsize=(8, 2))
ax1 = fig.add_axes([0.05, 0.80, 0.9, 0.15])
ax2 = fig.add_axes([0.05, 0.475, 0.9, 0.15])
norm = mpl.colors.Normalize(vmin=0, vmax=1)
cb1 = mpl.colorbar.ColorbarBase(ax1, cmap = cmap, norm=norm,orientation='horizontal')
cb2 = mpl.colorbar.ColorbarBase(ax2, cmap = cmap_r, norm=norm, orientation='horizontal')
But it especially works nice for custom declared colormaps, as there is not a default _r
for custom declared colormaps. Following example taken from http://matplotlib.org/examples/pylab_examples/custom_cmap.html:
cdict1 = {'red': ((0.0, 0.0, 0.0),
(0.5, 0.0, 0.1),
(1.0, 1.0, 1.0)),
'green': ((0.0, 0.0, 0.0),
(1.0, 0.0, 0.0)),
'blue': ((0.0, 0.0, 1.0),
(0.5, 0.1, 0.0),
(1.0, 0.0, 0.0))
}
blue_red1 = mpl.colors.LinearSegmentedColormap('BlueRed1', cdict1)
blue_red1_r = reverse_colourmap(blue_red1)
fig = plt.figure(figsize=(8, 2))
ax1 = fig.add_axes([0.05, 0.80, 0.9, 0.15])
ax2 = fig.add_axes([0.05, 0.475, 0.9, 0.15])
norm = mpl.colors.Normalize(vmin=0, vmax=1)
cb1 = mpl.colorbar.ColorbarBase(ax1, cmap = blue_red1, norm=norm,orientation='horizontal')
cb2 = mpl.colorbar.ColorbarBase(ax2, cmap = blue_red1_r, norm=norm, orientation='horizontal')
OpenCV image format supports the numpy array interface. A helper function can be made to support either grayscale or color images. This means the BGR -> RGB conversion can be conveniently done with a numpy slice, not a full copy of image data.
Note: this is a stride trick, so modifying the output array will also change the OpenCV image data. If you want a copy, use .copy()
method on the array!
import numpy as np
def img_as_array(im):
"""OpenCV's native format to a numpy array view"""
w, h, n = im.width, im.height, im.channels
modes = {1: "L", 3: "RGB", 4: "RGBA"}
if n not in modes:
raise Exception('unsupported number of channels: {0}'.format(n))
out = np.asarray(im)
if n != 1:
out = out[:, :, ::-1] # BGR -> RGB conversion
return out
int Random = (int)(Math.random()*100);
if You need to generate more than one value, then just use for loop for that
for (int i = 1; i <= 10 ; i++)
{
int Random = (int)(Math.random()*100);
System.out.println(Random);
}
If You want to specify a more decent range, like from 10 to 100 ( both are in the range )
so the code would be :
int Random =10 + (int)(Math.random()*(91));
/* int Random = (min.value ) + (int)(Math.random()* ( Max - Min + 1));
*Where min is the smallest value You want to be the smallest number possible to
generate and Max is the biggest possible number to generate*/
-
in "-".join(my_list)
declares that you are converting to a string from joining elements a list.It's result-oriented. (just for easy memory and understanding)
I made an exhaustive cheatsheet of methods_of_string for your reference.
string_methods_44 = {
'convert': ['join','split', 'rsplit','splitlines', 'partition', 'rpartition'],
'edit': ['replace', 'lstrip', 'rstrip', 'strip'],
'search': ['endswith', 'startswith', 'count', 'index', 'find','rindex', 'rfind',],
'condition': ['isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isnumeric','isidentifier',
'islower','istitle', 'isupper','isprintable', 'isspace', ],
'text': ['lower', 'upper', 'capitalize', 'title', 'swapcase',
'center', 'ljust', 'rjust', 'zfill', 'expandtabs','casefold'],
'encode': ['translate', 'maketrans', 'encode'],
'format': ['format', 'format_map']}
Adding a new answer to this as the question of printing PDF's in .net has been around for a long time and most of the answers pre-date the Google Pdfium library, which now has a .net wrapper. For me I was researching this problem myself and kept coming up blank, trying to do hacky solutions like spawning Acrobat or other PDF readers, or running into commercial libraries that are expensive and have not very compatible licensing terms. But the Google Pdfium library and the PdfiumViewer .net wrapper are Open Source so are a great solution for a lot of developers, myself included. PdfiumViewer is licensed under the Apache 2.0 license.
You can get the NuGet package here:
https://www.nuget.org/packages/PdfiumViewer/
and you can find the source code here:
https://github.com/pvginkel/PdfiumViewer
Here is some simple code that will silently print any number of copies of a PDF file from it's filename. You can load PDF's from a stream also (which is how we normally do it), and you can easily figure that out looking at the code or examples. There is also a WinForm PDF file view so you can also render the PDF files into a view or do print preview on them. For us I simply needed a way to silently print the PDF file to a specific printer on demand.
public bool PrintPDF(
string printer,
string paperName,
string filename,
int copies)
{
try {
// Create the printer settings for our printer
var printerSettings = new PrinterSettings {
PrinterName = printer,
Copies = (short)copies,
};
// Create our page settings for the paper size selected
var pageSettings = new PageSettings(printerSettings) {
Margins = new Margins(0, 0, 0, 0),
};
foreach (PaperSize paperSize in printerSettings.PaperSizes) {
if (paperSize.PaperName == paperName) {
pageSettings.PaperSize = paperSize;
break;
}
}
// Now print the PDF document
using (var document = PdfDocument.Load(filename)) {
using (var printDocument = document.CreatePrintDocument()) {
printDocument.PrinterSettings = printerSettings;
printDocument.DefaultPageSettings = pageSettings;
printDocument.PrintController = new StandardPrintController();
printDocument.Print();
}
}
return true;
} catch {
return false;
}
}
Using Jquery you could do something like this:
$(document).ready(function() {
if ($("img").attr("src") != null)
{
if ($("img").attr("src").toString() == "")
{
$("img").attr("src", "images/default.jpg");
}
}
else
{
$("img").attr("src", "images/default.jpg");
}
});
Recursively update Windows 7 until it shows no more updates, using Windows Update check option in Windows 7.
Then download and install Visual C++ Redistributable vc_redist.x64.exe from the Windows website.
Then try to run Apache server.
the first,Using get_encoding_type to get the files type of encode:
import os
from chardet import detect
# get file encoding type
def get_encoding_type(file):
with open(file, 'rb') as f:
rawdata = f.read()
return detect(rawdata)['encoding']
the second, opening the files with the type:
open(current_file, 'r', encoding = get_encoding_type, errors='ignore')
I had the same question and more, and though this thread is old, it is still a good one, so in summary for SSRS 2008R2 I found...
Situations
Actions
If applicable, be sure to replace Reports/Pages/Report.aspx?ItemPath= with ReportServer?. In other words: Instead of this:
http://server/Reports/Pages/Report.aspx?ItemPath=/ReportFolder/ReportSubfolder/ReportName
Use this syntax:
http://server/ReportServer?/ReportFolder/ReportSubfolder/ReportName
Add parameter(s) to the report and set as hidden (or visible if user action allowed, though keep in mind that while the report parameter will change, the URL will not change based on an updated entry).
Attach parameters to URL with &ParameterName=Value
Parameters can be referenced or displayed in report using @ParameterName, whether they're set in the report or in the URL
To hide the toolbar where parameters are displayed, add &rc:Toolbar=false to the URL (reference)
Putting that all together, you can run a URL with embedded values, or call this as an action from one report and read by another report:
http://server.domain.com/ReportServer?/ReportFolder1/ReportSubfolder1/ReportName&UserID=ABC123&rc:Toolbar=false
In report dataset properties query: SELECT stuff FROM view WHERE User = @UserID
In report, set expression value to [UserID] (or =Fields!UserID.Value)
Keep in mind that if a report has multiple parameters, you might need to include all parameters in the URL, even if blank, depending on how your dataset query is written.
To pass a parameter using Action = Go to URL, set expression to:
="http://server.domain.com/ReportServer?/ReportFolder1/ReportSubfolder1/ReportName&UserID="
&Fields!UserID.Value
&"&rc:Toolbar=false"
&"&rs:ClearSession=True"
Be sure to have a space after an expression if followed by & (a line break is isn't enough). No space is required before an expression. This method can pass a parameter but does not hide it as it is visible in the URL.
If you don't include &rs:ClearSession=True then the report won't refresh until browser session cache is cleared.
To pass a parameter using Action = Go to report:
For reference, / = %2f
better to use touchstart
event with .on()
jQuery method:
$(window).load(function() { // better to use $(document).ready(function(){
$('.List li').on('click touchstart', function() {
$('.Div').slideDown('500');
});
});
And i don't understand why you are using $(window).load()
method because it waits for everything on a page to be loaded, this tend to be slow, while you can use $(document).ready()
method which does not wait for each element on the page to be loaded first.
$('.login').toggle(
function(){
$('#panel').animate({
height: "150",
padding:"20px 0",
backgroundColor:'#000000',
opacity:.8
}, 500);
$('#otherdiv').animate({
//otherdiv properties here
}, 500);
},
function(){
$('#panel').animate({
height: "0",
padding:"0px 0",
opacity:.2
}, 500);
$('#otherdiv').animate({
//otherdiv properties here
}, 500);
});
In jsFiddle by default the code you type into the script block is wrapped in a function executed on window.onload:
<script type='text/javascript'>//<![CDATA[
window.onload = function () {
function myFunc(id){
alert(id);
}
}
//]]>
</script>
Because of this, your function myFunc
is not in the global scope so is not available to your html buttons. By changing the option to No-wrap in <head>
as Sergio suggests your code isn't wrapped:
<script type='text/javascript'>//<![CDATA[
function myFunc(id){
alert(id);
}
//]]>
</script>
and so the function is in the global scope and available to your html buttons.
All you need is to add the following to your TabLayout
custom:tabGravity="fill"
So then you'll have:
xmlns:custom="http://schemas.android.com/apk/res-auto"
<android.support.design.widget.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
custom:tabGravity="fill"
/>
Using array formula.
=SUM(COUNT(IF(D1:D5="Yes",COUNT(D1:D5),"")),COUNT(IF(D1:D5="No",COUNT(D1:D5),"")),COUNT(IF(D1:D5="Agree",COUNT(D1:D5),"")))
PRESS = CTRL + SHIFT + ENTER.
Install "xclip" if you haven't...
sudo apt-get install xclip
Xclip puts the data into the "selection/highlighted" clipboard that you middle-click to paste as opposed to "ctrl+v"
While in vim use ex commands:
7w !xclip
or
1,7w !xclip
or
%w !xclip
Then just middle-click to paste into any other application...
use
<activity android:name=".ActivityName"
android:theme="@android:style/Theme.NoTitleBar">
In my case it was an issue of the PHP version.
The .phar file I was using was not compatible with PHP 5.3.9. Switching interpreter to PHP 7 did fix it.
While @dfa answer of org.apache.commons.lang.StringEscapeUtils.escapeHtml
is nice and I have used it in the past it should not be used for escaping HTML (or XML) attributes otherwise the whitespace will be normalized (meaning all adjacent whitespace characters become a single space).
I know this because I have had bugs filed against my library (JATL) for attributes where whitespace was not preserved. Thus I have a drop in (copy n' paste) class (of which I stole some from JDOM) that differentiates the escaping of attributes and element content.
While this may not have mattered as much in the past (proper attribute escaping) it is increasingly become of greater interest given the use use of HTML5's data-
attribute usage.
I think previous answers are correct , this is another way of doing the same thing. I am sharing it here with others just in case if it becomes useful for someone. This is how you can change the text/title color for the navbar in ios7:
UIColor *red = [UIColor colorWithRed:254.0f/255.0f green:0.0f/255.0f blue:0.0f/255.0f alpha:1.0];
NSMutableDictionary *navBarTextAttributes = [NSMutableDictionary dictionaryWithCapacity:1];
[navBarTextAttributes setObject:red forKey:NSForegroundColorAttributeName ];
self.navigationController.navigationBar.titleTextAttributes = navBarTextAttributes;
The solution posted by https://stackoverflow.com/users/1373278/hoss above worked for me. I am reproducing it here because I cannot yet comment on hoss' post:
Remove import android.R;
from your activity file in question.
My setup:
Android Studio 1.2.2
Exported project from one Mac to Git (everything was working). I then imported the project on another Mac from Git. Thats when it stopped resolving the resource files.
I tried everything on this thread:
Nothing worked except removing import android.R;
from my activity java file.
To avoid this issue in the future add .idea
folder to your .gitignore
file. There is a nice plugin from git for gitignore in Android Studio. Install this plugin and right click in .idea > Add to .gitignore
Using a third-party library (Newtonsoft.Json) as alternative:
public static string XmlEscape(string unescaped)
{
if (unescaped == null) return null;
return JsonConvert.SerializeObject(unescaped); ;
}
public static string XmlUnescape(string escaped)
{
if (escaped == null) return null;
return JsonConvert.DeserializeObject(escaped, typeof(string)).ToString();
}
Examples of escaped string:
a<b
==> "a<b"
<foo></foo>
==> "foo></foo>"
NOTE: In newer versions, the code written above may not work with escaping, so you need to specify how the strings will be escaped:
public static string XmlEscape(string unescaped)
{
if (unescaped == null) return null;
return JsonConvert.SerializeObject(unescaped, new JsonSerializerSettings()
{
StringEscapeHandling = StringEscapeHandling.EscapeHtml
});
}
Examples of escaped string:
a<b
==> "a\u003cb"
<foo></foo>
==> "\u003cfoo\u003e\u003c/foo\u003e"
I'd use recursion just in case so you can deep copy the map
and avoid bad surprises in case you were to change a map
element that is a map
itself.
Here's an example in a utils.go:
package utils
func CopyMap(m map[string]interface{}) map[string]interface{} {
cp := make(map[string]interface{})
for k, v := range m {
vm, ok := v.(map[string]interface{})
if ok {
cp[k] = CopyMap(vm)
} else {
cp[k] = v
}
}
return cp
}
And its test file (i.e. utils_test.go):
package utils
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestCopyMap(t *testing.T) {
m1 := map[string]interface{}{
"a": "bbb",
"b": map[string]interface{}{
"c": 123,
},
}
m2 := CopyMap(m1)
m1["a"] = "zzz"
delete(m1, "b")
require.Equal(t, map[string]interface{}{"a": "zzz"}, m1)
require.Equal(t, map[string]interface{}{
"a": "bbb",
"b": map[string]interface{}{
"c": 123,
},
}, m2)
}
It should easy enough to adapt if you need the map
key to be something else instead of a string
.
You could also use plain Javascript window.innerWidth
to compare width.
But use jQuery's .resize()
fired automatically for you:
$( window ).resize(function() {
// your code...
});
Here's a code snippet that should help for .NET 3 and higher.
using System.IO;
using System.Text.RegularExpressions;
public static class PathValidation
{
private static string pathValidatorExpression = "^[^" + string.Join("", Array.ConvertAll(Path.GetInvalidPathChars(), x => Regex.Escape(x.ToString()))) + "]+$";
private static Regex pathValidator = new Regex(pathValidatorExpression, RegexOptions.Compiled);
private static string fileNameValidatorExpression = "^[^" + string.Join("", Array.ConvertAll(Path.GetInvalidFileNameChars(), x => Regex.Escape(x.ToString()))) + "]+$";
private static Regex fileNameValidator = new Regex(fileNameValidatorExpression, RegexOptions.Compiled);
private static string pathCleanerExpression = "[" + string.Join("", Array.ConvertAll(Path.GetInvalidPathChars(), x => Regex.Escape(x.ToString()))) + "]";
private static Regex pathCleaner = new Regex(pathCleanerExpression, RegexOptions.Compiled);
private static string fileNameCleanerExpression = "[" + string.Join("", Array.ConvertAll(Path.GetInvalidFileNameChars(), x => Regex.Escape(x.ToString()))) + "]";
private static Regex fileNameCleaner = new Regex(fileNameCleanerExpression, RegexOptions.Compiled);
public static bool ValidatePath(string path)
{
return pathValidator.IsMatch(path);
}
public static bool ValidateFileName(string fileName)
{
return fileNameValidator.IsMatch(fileName);
}
public static string CleanPath(string path)
{
return pathCleaner.Replace(path, "");
}
public static string CleanFileName(string fileName)
{
return fileNameCleaner.Replace(fileName, "");
}
}
You can not serialize a Python 3 'string' to bytes without explict conversion to some encoding.
outfile.write(plaintext.encode('utf-8'))
is possibly what you want. Also this works for both python 2.x and 3.x.
I know this is a little late, but if someone else comes across this looking, you can now use public_path(); in Laravel 4, it has been added to the helper.php file in the support folder see here.
You can use a join to do this
SELECT t1.* from myTable t1
LEFT OUTER JOIN myTable t2 on t2.ID=t1.ID AND t2.`Date` > t1.`Date`
WHERE t2.`Date` IS NULL;
Only rows which have the latest date for each ID with have a NULL join to t2.
I think you could use istream .read() function. You can just loop with reasonable chunk size and read directly to memory buffer, then append it to some sort of arbitrary memory container (such as std::vector). I could write an example, but I doubt you want a complete solution; please let me know if you shall need any additional information.
The current version of AVG Free antivirus is incompatible with Microsoft Visual Studio 2015.
It does not allow Visual Studio to be installed on the computer. It gets stuck at "Creating restore point". Visual Studio installs perfectly when AVG is turned off.
Any code compiled in "Release" mode targeting x86 platform/environment (in project properties) does not compile. It compiles successfully when AVG is turned off.
I posted the issues in AVG support forum but no one responded.
I guess your end goal is to show Distinct (unique) values inside your original Pivot table.
For example you could have data set with OrderNumber, OrderDate, OrderItem, orderQty
First pivot table will show you OrderDate and sum of OrderQty and you probably want to see Count of unique orders in the same Pivot. You woudln't be able to do so within standard pivot table
If you want to do it, you would need Office 2016 (or perhaps pover Pivot might work). In office 2016 select your data > Insert > Pivot Table > choose tick "Add this data to the Data Model"
After that, you would be able to select grouping method as Distinct (Count)
int elem = 42;
std::vector<int> v;
v.push_back(elem);
if(std::find(v.begin(), v.end(), elem) != v.end())
{
//elem exists in the vector
}
if (obj instanceof C) {
//your code
}
Note: According to JDN96, the answer below may cause a memory leak by repeatedly destroying and recreating frames. However, I have not tested to verify this myself.
One way to switch frames in tkinter
is to destroy the old frame then replace it with your new frame.
I have modified Bryan Oakley's answer to destroy the old frame before replacing it. As an added bonus, this eliminates the need for a container
object and allows you to use any generic Frame
class.
# Multi-frame tkinter application v2.3
import tkinter as tk
class SampleApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self._frame = None
self.switch_frame(StartPage)
def switch_frame(self, frame_class):
"""Destroys current frame and replaces it with a new one."""
new_frame = frame_class(self)
if self._frame is not None:
self._frame.destroy()
self._frame = new_frame
self._frame.pack()
class StartPage(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
tk.Label(self, text="This is the start page").pack(side="top", fill="x", pady=10)
tk.Button(self, text="Open page one",
command=lambda: master.switch_frame(PageOne)).pack()
tk.Button(self, text="Open page two",
command=lambda: master.switch_frame(PageTwo)).pack()
class PageOne(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
tk.Label(self, text="This is page one").pack(side="top", fill="x", pady=10)
tk.Button(self, text="Return to start page",
command=lambda: master.switch_frame(StartPage)).pack()
class PageTwo(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
tk.Label(self, text="This is page two").pack(side="top", fill="x", pady=10)
tk.Button(self, text="Return to start page",
command=lambda: master.switch_frame(StartPage)).pack()
if __name__ == "__main__":
app = SampleApp()
app.mainloop()
switch_frame()
works by accepting any Class object that implements Frame
. The function then creates a new frame to replace the old one.
_frame
if it exists, then replaces it with the new frame..pack()
, such as menubars, will be unaffected.tkinter.Frame
.v2.3
- Pack buttons and labels as they are initialized
v2.2
- Initialize `_frame` as `None`.
- Check if `_frame` is `None` before calling `.destroy()`.
v2.1.1
- Remove type-hinting for backwards compatibility with Python 3.4.
v2.1
- Add type-hinting for `frame_class`.
v2.0
- Remove extraneous `container` frame.
- Application now works with any generic `tkinter.frame` instance.
- Remove `controller` argument from frame classes.
- Frame switching is now done with `master.switch_frame()`.
v1.6
- Check if frame attribute exists before destroying it.
- Use `switch_frame()` to set first frame.
v1.5
- Revert 'Initialize new `_frame` after old `_frame` is destroyed'.
- Initializing the frame before calling `.destroy()` results
in a smoother visual transition.
v1.4
- Pack frames in `switch_frame()`.
- Initialize new `_frame` after old `_frame` is destroyed.
- Remove `new_frame` variable.
v1.3
- Rename `parent` to `master` for consistency with base `Frame` class.
v1.2
- Remove `main()` function.
v1.1
- Rename `frame` to `_frame`.
- Naming implies variable should be private.
- Create new frame before destroying old frame.
v1.0
- Initial version.
this works with "NA"
not for NA
comments = c("no","yes","NA")
for (l in 1:length(comments)) {
#if (!is.na(comments[l])) print(comments[l])
if (comments[l] != "NA") print(comments[l])
}
This line looks questionable:
page_output.innerHTML = str_output;
You can use .innerHTML
within jQuery, or you can use it without, but you have to address the selector semantically one way or the other:
$('#page_output').innerHTML /* for jQuery */
document.getElementByID('page_output').innerHTML /* for standard JS */
or better yet
$('#page_output').html(str_output);
npm fund [<pkg>]
This command retrieves information on how to fund the dependencies of a given project. If no package name is provided, it will list all dependencies that are looking for funding in a tree-structure in which are listed the type of funding and the url to visit.
The message can be disabled using: npm install --no-fund
ProgressDialog
was deprecated in API level 26 .
refers to functions or elements that are in the process of being replaced by newer ones."Deprecated"
ProgressDialog is a modal dialog, which prevents the user from interacting with the app. Instead of using this class, you should use a progress indicator like
ProgressBar
, which can be embedded in your app's UI.
Advantage
I would personally say that ProgressBar
has the edge over the two .ProgressBar
is a user interface element that indicates the progress of an operation. Display progress bars to a user in a non-interruptive way. Show the progress bar in your app's user interface.
In Ruby 2.1, each_with_index method is removed. Instead you can use each_index
Example:
a = [ "a", "b", "c" ]
a.each_index {|x| print x, " -- " }
produces:
0 -- 1 -- 2 --