prompt
stringlengths 49
4.73k
| response
stringlengths 238
35k
|
---|---|
array type is not assignable
I need to create two references to an array which could be refer to the same array. I tried the following:
```
extern int (&a)[];
extern int (&b)[];
int main()
{
b = a; // error: array type 'int []' is not assignable
}
```
Is there a way to do that in c++?
| Two things: first [arrays](http://en.cppreference.com/w/cpp/language/array) cannot appear on the left hand of an assignment operator. cppreference probably takes its text directly from the standard, particularly:
§ 8.3.4
>
> 5 Objects of array types cannot be modified, see 3.10.
>
>
>
Also, like cppreference says, arrays are lvalues:
§ 3.10
>
> 1 Expressions are categorized according to the taxonomy in
> Figure 1. — An lvalue (so called, historically, because lvalues could
> appear on the left-hand side of an assignment expression) designates a
> function or an object.
>
>
>
Although, the standard explicitly says that objects of array types cannot be modified, therefore concluding that arrays (which are objects) cannot appear on the left hand side of the assignment operator.
Secondly, while the compiler may not complain if you do this:
```
int a = 50, c = 42;
int& b = a;
b = c;
b = 80;
std::cout << a << " " << c; // 80 42
```
you will see that `c` remains unchanged. Please refer to the [parashift C++-faq](http://www.parashift.com/c++-faq/index.html).
[[8.5] How can you reseat a reference to make it refer to a different object?](http://www.parashift.com/c++-faq/reseating-refs.html)
>
> No way.
>
>
> You can't separate the reference from the referent.
>
>
> Unlike a pointer, once a reference is bound to an object, it can *not*
> be "reseated" to another object. The reference itself isn't an object
> (it has no identity; taking the address of a reference gives you the
> address of the referent; remember: the reference *is* its referent).
>
>
>
|
Linq to objects Predicate Builder
What is the best way to do a conditional query using linq to objects(not linq to sql).
Currently I am using the Predicate builder found here <http://www.albahari.com/nutshell/predicatebuilder.aspx>
and passing the compiled predicate to the IEnumerable.Where and it seems to work nicely.
Example code of what I want to solve:
eg I have this
```
string keyword1 = "Test1";
string keyword2 = "Test3";
IEnumerable<TestObject> tests = new List<TestObject>()
{
new TestObject() {Name1 = "Test1", Name2 = "Test1"},
new TestObject() {Name1 = "Test2", Name2 = "Test2"},
new TestObject() {Name1 = "Test3", Name2 = "Test3"},
};
if (!String.IsNullOrEmpty(keyword1) && String.IsNullOrEmpty(keyword2))
tests = tests.Where(e => e.Name1.Contains(keyword1));
else if (!String.IsNullOrEmpty(keyword2) && !String.IsNullOrEmpty(keyword1))
tests = tests.Where(e => e.Name2.Contains(keyword2) || e.Name1.Contains(keyword1));
return tests.ToList();
```
| Just change `PredicateBuilder` to use delegates instead of expression trees and use lambdas to build the results:
```
public static class DelegatePredicateBuilder
{
public static Func<T, bool> True<T>() { return f => true; }
public static Func<T, bool> False<T>() { return f => false; }
public static Func<T, bool> Or<T>(this Func<T, bool> expr1,
Func<T, bool> expr2)
{
return t => expr1(t) || expr2(t);
}
public static Func<T, bool> And<T>(this Func<T, bool> expr1,
Func<T, bool> expr2)
{
return t => expr1(t) && expr2(t);
}
}
```
|
Cache SSD shutdown data loss
Most SSD have a cache to provide fast write speed. But what happens when I shutdown the computer with full cache? Is that cache volatile? How fast ist the cache processed and persisted? Do I need to wait some seconds before I shutdown my computer after transferring a lot of data? Do I need power loss protection to avoid data loss?
| During a controlled shutdown, the OS/filesystem flushes all pending writes to stable storage, issuing a final write barrier (ie: ATA FLUSH) to be sure no data remains in the volatile write cache. This can need some time, but you don't have to do anything: just wait for the operation to complete (and the system to power-off).
But what does happen during an *unexpected* shutdown, for example just after a power loss? On consumer SSDs, lacking a powerloss protected write cache, you will lose any unsynched cache content. To avoid losing cached data, the user/OS needs to explicitly sync and flush important but pending data (eg: a database write or a filesystem journal update) via a sync+barrier primitive (ie: sync and fsync() on Linux).
On enterprise SSDs that provide capacitor-based powerloss protected write back cache, a sudden power failure will not cause any data loss. Depending on the drive type/firmware, this protected cache can be exported as writeback or writethrough:
- in the first case (writeback), the OS will continue sending write barriers and cache flushes, but the drive will simply ignore them unless the on-board controller detects some issues with the powerloss protection circuitry. This mode of operation commands a somewhat higher overhead (due to barrier being generated by the OS), but permits the drive to dynamically switch between actual writeback/writeback+flushes/writethrough modes based on internal health counters;
- in the second case (writethrough), the OS avoid sending any write barriers. This leads to greater performance (due to less OS overhead), but if the drive electronic detects any issues it can only switch to "full" writethrough, were *any* write is considered important and immediately flushed to the physical media.
|
Add levels selector class to wordpress nav menu
I would like to add level classes to each li when echoing the results of wp\_list\_pages. Currently, I'm using:
```
<?php
wp_nav_menu(array('theme_location' => 'main_menu', 'container' => '', 'menu_class' => 'fR clearfix', 'menu_id' => 'nav'));
<?php } ?>
```
The desired output would be:
```
<ul class="menu">
<li class="page_item page-item-9 level-0 current_page_item"><a href="" title=""></a>
<ul class="children expanded" style="display: block; ">
<li class="page_item page-item-40 level-1"><a href="" title=""></a></li>
<li class="page_item page-item-43 level-1"><a href="" title=""></a></li>
<li class="page_item page-item-45 level-1"><a href="" title=""></a></li>
<li class="page_item page-item-47 level-1"><a href="" title=""></a></li>
</ul>
</li>
<!-- So on -->
</ul>
```
Is this possible to have the desired output? please help!
| There isn't a direct way to do this.
You can use the wp\_nav\_menu\_objects filter and manipulate the menu item's classes.
Here is the code for you:
```
<?php
add_filter('wp_nav_menu_objects' , 'my_menu_class');
function my_menu_class($menu) {
$level = 0;
$stack = array('0');
foreach($menu as $key => $item) {
while($item->menu_item_parent != array_pop($stack)) {
$level--;
}
$level++;
$stack[] = $item->menu_item_parent;
$stack[] = $item->ID;
$menu[$key]->classes[] = 'level-'. ($level - 1);
}
return $menu;
}
```
|
Convert Date to another timezone in JavaScript and Print with Correct Timezone
I need to convert a local timezone to Pacific/Los angeles.
Example, if user in Hawaii
**Code:** taken here from <https://stackoverflow.com/a/54127122/15358601>
```
function convertTZ(date, tzString) {
return new Date((typeof date === "string" ? New Date(date) : date).toLocaleString("en-US", {timeZone: tzString}));
}
convertTZ(new Date(), "America/Los_Angeles")
```
>
> Sun Mar 14 2021 17:01:59 GMT-1000 (Hawaii-Aleutian Standard Time) {}
>
>
>
It still prints the final with Hawaii. I need America/Los Angeles Display, not Hawaii. (however it still prints the correct new Hours and Minutes, just the Display label is incorrect)
How can this be done?
![Results picture](https://i.stack.imgur.com/iZwCj.png)
The solution should work for other timezones also, printing it respectively its other timezone, eg: America/New\_York, Europe/London, Europe/Paris, etc ,
| A few things:
- The approach in the answer you linked to for the `convertTZ` is flawed. One should not parse the output of `toLocalString` with the `Date` constructor. Please read the comments following that answer.
- The `Date` object *can not* be converted to another time zone, because it is not actually in *any* time zone. The only thing encapsulated by the `Date` object is its Unix timestamp, which can be seen with `.valueOf()`, `.getTime()`, or any mechanism that coerces it to a `Number`. Such values are always UTC-based.
- When you see local time or a time zone coming from the `Date` object, the system's local time zone is applied to the internal UTC-based Unix Timestamp to create the output. The local time zone cannot be changed programmatically from JavaScript (or TypeScript), nor can it be altered on a per-object basis.
- Instead of trying to convert a `Date` object in one time zone to a `Date` object in another time zone, recognize that all `Date` objects are inherently UTC. Thus, you can create a *string* that is in a different time zone, (for example, using `toLocaleString` with the `timeZone` option) but you cannot create a new `Date` object from that string. If you want an object that can actually be set to a different time zone, consider [Luxon](https://moment.github.io/luxon/). If you need a solution without a library, you will one day be able to use a [`ZonedDateTime`](https://tc39.es/proposal-temporal/docs/index.html#Temporal-ZonedDateTime) from the [TC39 Temporal Proposal](https://tc39.es/proposal-temporal/docs/index.html), which will eventually be part of ECMAScript.
- Beware of calling `console.log` on a `Date` object. Neither the ECMAScript spec nor the WhatWG Console spec defines the behavior of such a call. It is undefined behavior. In some environments, the string output logged is the same as calling `.toString()` on the `Date` object - which will give the local time equivalent of the `Date` object's timestamp, along with a display name for the local time zone. Other environments will show the same output of calling `.toISOString()`, which will give an ISO-8601 representation of the timestamp in UTC. Instead of logging `Date` objects, call one of those two functions yourself and log the output.
|
In a UITableView, best method to cancel GCD operations for cells that have gone off screen?
I have a `UITableView` that loads images from a URL into cells asynchronously using GCD. Problem is if a user flicks past 150 rows, 150 operations queue up and execute. What I want is to dequeue/cancel the ones that blew past and went off screen.
How do I do this?
My code at this point (pretty standard):
```
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
// after getting the cell...
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
if (runQ) {
NSString *galleryTinyImageUrl = [[self.smapi getImageUrls:imageId imageKey:imageKey] objectForKey:@"TinyURL"];
NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:galleryTinyImageUrl]];
dispatch_async(dispatch_get_main_queue(), ^{
if (imageData != nil) {
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.imageView.image = [UIImage imageWithData:imageData];
}
});
}
});
```
runQ is a `BOOL` ivar I set to `NO` on `viewWillDisappear`, which (I think) has the effect of flushing out the queue rapidly when this `UITableView` pops off the navigation controller.
So, back to my original question: how do I cancel the image fetch operations for cells that have gone off screen? Thanks.
| First, don't queue operations while scrolling. Instead, load images for just the visible rows in `viewDidLoad` and when the user stops scrolling:
```
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
for (NSIndexPath *indexPath in [self.tableView indexPathsForVisibleRows]) {
[self loadImageForCellAtPath:indexPath];
}
}
```
If you still want to be able to cancel loading for invisible cells, you could use `NSBlockOperation` instead of GCD:
```
self.operationQueue = [[[NSOperationQueue alloc] init] autorelease];
[self.operationQueue setMaxConcurrentOperationCount:NSOperationQueueDefaultMaxConcurrentOperationCount];
// ...
-(void)loadImageForCellAtPath:(NSIndexPath *)indexPath {
__block NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
if (![operation isCancelled]) {
NSString *galleryTinyImageUrl = [[self.smapi getImageUrls:imageId imageKey:imageKey] objectForKey:@"TinyURL"];
NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:galleryTinyImageUrl]];
dispatch_async(dispatch_get_main_queue(), ^{
if (imageData != nil) {
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.imageView.image = [UIImage imageWithData:imageData];
}
});
}
}];
NSValue *nonRetainedOperation = [NSValue valueWithNonretainedObjectValue:operation];
[self.operations addObject:nonRetainedOperation forKey:indexPath];
[self.operationQueue addOperation:operation];
}
```
Here `operations` is an `NSMutableDictionary`. When you want to cancel an operation, you retrieve it by the cell's `indexPath`, cancel it, and remove it from the dictionary:
```
NSValue *operationHolder = [self.operations objectForKey:indexPath];
NSOperation *operation = [operationHolder nonretainedObjectValue];
[operation cancel];
```
|
CSS Polygon Shadow
I'm using the `clip-path` property to shape my block element.
```
clip-path: polygon(0 0, 100% 0, 100% 100px, 50% 100%, 0 100px);
```
I would like to put a "drop shadow" in that element. So, I've tried some techniques, like:
```
box-shadow: 0 15px 30px 0 rgba(0, 0, 0, 0.5);
```
Or...
```
filter: drop-shadow(0 15px 30px rgba(0, 0, 0, 0.5));
```
[See my test environment on CodePen.](https://codepen.io/caio/pen/zwoqXX)
Is it possible with CSS or SVG?
| As it was said in the comments, you need 2 nested elements for this, the inner for the clipping and the outer for the shadow.
```
body {
background-color: gray;
}
.navigation {
filter: drop-shadow(0 15px 30px rgba(0, 0, 200, 0.5));
}
.innernav {
/* PATH */
clip-path: polygon(0 0, 100% 0, 100% 100px, 50% 100%, 0 100px);
/* OTHERS */
background-color: silver;
color: white;
height: 150px;
position: fixed;
text-align: center;
top: 0;
width: 100%;
z-index: 100;
}
.main {
padding: 200px 20px 0;
text-align: center;
}
```
```
<nav class="navigation"><div class="innernav">Hi, I'm a nav.</div></nav>
<main class="main">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptates quia velit modi veniam! Velit fuga facilis blanditiis iure aperiam cumque quasi officia quaerat dignissimos neque repellat quisquam voluptates sequi, hic?</p>
</main>
```
|
Opening multiple windows with Applescript
I am trying to write an Applescript to open three VLC windows in different screen positions. The script opens three instances of VLC but has them one on top of the other (using the position for window 1). Help with the code appreciated:
```
do shell script "open -n /Applications/Video/VLC.app"
tell application "System Events"
activate
set bounds of first window of application "VLC" to {13, 36, 790, 519}
end tell
do shell script "open -n /Applications/Video/VLC.app"
tell application "System Events"
activate
set bounds of second window of application "VLC" to {13, 544, 790, 1027}
end tell
do shell script "open -n /Applications/Video/VLC.app"
tell application "System Events"
activate
set bounds of third window of application "VLC" to {13, 1043, 790, 1526}
end tell
```
| @khagler's comment provides the right pointer: the VLC instances must be distinguished by their PIDs (process IDs; called `unix id` in AppleScript) in the `System Events` context.
The code below should do what you want, arrived at after much toil and trouble -- par for the [AppleScript obstacle] course. One obstacle was that the VLC instances' main windows do not get created right away.
The comments provide more details.
Note that because user-interface elements are programmatically manipulated, the application running your script must be granted [assistive access](http://support.apple.com/kb/HT5914) for security reasons.
Note that I'm starting the instances with `do shell script "open -na VLC.app"`, relying on the location of the app being known to Launch services (should that not work for some reason, revert to your method of specifying the full path).
```
# Specify the desired window bounds.
# !! In the "System Events" context, windows do not
# !! have `bounds` properties, but separate `position` and
# !! `size` properties.
set WIN_POSITIONS to {{13, 36}, {13, 544}, {13, 1043}}
set WIN_SIZES to {{790, 519}, {790, 519}, {790, 519}}
# Launch the VLC instances.
repeat with i from 1 to count of WIN_POSITIONS
do shell script "open -na VLC.app"
end repeat
# Note:
# Instance-specific manipulation must
# be performed in the "System Events" context, because
# we must distinguish the VLC instances by their
# PIDs (process IDs; called `unix id` in AppleScript).
tell application "System Events"
# Get the PIDs (process IDs) of all VLC instances.
set vlcPids to get the unix id of every process whose name is "VLC"
# Loop over all instance PIDs.
# !! It is imperative to *continue* to use object specifiers
# !! with *filters based on the PID* so as to ensure that the
# !! individual instances are targeted.
# !! Attempting to store references to these instances in
# !! variables fails subtly, as evidenced by the "Events"
# !! tab in AppleScript editor later showing the non-specific
# !! process "VLC" of application "System Events" specifiers.
set winNdx to 1
repeat with vlcPid in vlcPids
# WAIT for each instance to create its main window, wich
# sadly, is not available right away.
# Once created, position it.
set haveWin to false
tell (first process whose unix id is vlcPid)
repeat with i from 1 to 25 # times out after 25 * .2 == 5 secs.
if (count of windows of it) > 0 then
set haveWin to true
tell front window of it
# !! In the "System Events" context, windows do not
# !! have `bounds` properties, but separate `position` and
# !! `size` properties.
set position to item winNdx of WIN_POSITIONS
set size to item winNdx of WIN_SIZES
end tell
exit repeat
end if
delay 0.2 # no window yet; sleep some and try again
end repeat
end tell
if not haveWin then error "VLC instance " & vlcPid & " unexpectedly did not create a window within the timeout period."
set winNdx to winNdx + 1
end repeat
end tell
```
---
How to make this work with **Finder**:
Targeting Finder changes the approach for two reasons:
- there's only *one* Finder instance.
- you cannot open multiple *windows* with `open -na Finder.app`; thankfully, [this answer](https://stackoverflow.com/a/21189333/45375) shows how to do it (see the comments there for quirks).
Note that the following blindly opens *additional* Finder windows.
```
set WIN_POSITIONS to {{13, 36}, {13, 544}, {13, 1043}}
set WIN_SIZES to {{790, 519}, {790, 519}, {790, 519}}
# Sample target locations for the Finder windows.
# Note the use of the "System Events" context to faciliate use of
# POSIX-style *input* paths; note, however, that the paths are
# *stored* as HFS paths so that Finder accepts them.
tell application "System Events"
set WIN_TARGETS to {¬
path of desktop folder, ¬
path of folder "~/Downloads", ¬
path of folder "/Library/Audio"}
end tell
set winCount to count of WIN_POSITIONS
# Launch the Finder windows.
tell application "Finder"
# Create the windows in reverse orders.
repeat with i from winCount to 1 by -1
set newWin to make new Finder window
set target of newWin to item i of WIN_TARGETS
end repeat
end tell
tell application "System Events"
set i to 1
repeat with i from 1 to winCount
tell window i of application process "Finder"
# !! In the "System Events" context, windows do not
# !! have `bounds` properties, but separate `position` and
# !! `size` properties.
set position to item i of WIN_POSITIONS
set size to item i of WIN_SIZES
end tell
end repeat
end tell
```
|
Filling missing levels
I have the following type of dataframe:
```
Country <- rep(c("USA", "AUS", "GRC"),2)
Year <- 2001:2006
Level <- c("rich","middle","poor",rep(NA,3))
df <- data.frame(Country, Year,Level)
df
Country Year Level
1 USA 2001 rich
2 AUS 2002 middle
3 GRC 2003 poor
4 USA 2004 <NA>
5 AUS 2005 <NA>
6 GRC 2006 <NA>
```
I want to fill the missing values with the correct level label in the last from the right column.
So the expected outcome should be like this:
```
Country Year Level
1 USA 2001 rich
2 AUS 2002 middle
3 GRC 2003 poor
4 USA 2004 rich
5 AUS 2005 middle
6 GRC 2006 poor
```
| We can group by 'Country' and get the non-NA unique value
```
library(dplyr)
df %>%
group_by(Country) %>%
dplyr::mutate(Level = Level[!is.na(Level)][1])
# A tibble: 6 x 3
# Groups: Country [3]
# Country Year Level
# <fctr> <int> <fctr>
#1 USA 2001 rich
#2 AUS 2002 middle
#3 GRC 2003 poor
#4 USA 2004 rich
#5 AUS 2005 middle
#6 GRC 2006 poor
```
If we have loaded `dplyr` along with `plyr`, it is better to specify explicitly `dplyr::mutate` or `dplyr::summarise` so that it uses the function from `dplyr`. There are same functions in `plyr` and it could potentially mask the functions from `dplyr` when both are loaded creating different behavior.
|