_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d5401 | train | Use either packages ("pkg install erlang"), or ports (cd /usr/ports/lang/erlang && make install). Software often requires patches to make it run correctly, and ports/packages take care of that. They also automatically take care of dependencies, and that seems to be the root cause of your problem: you don't have perl installed.
A: So, I think you can install package
I have FreeBSD storage 10.1-RELEASE-p16 FreeBSD 10.1-RELEASE-p16 #0
And simple way is pkg install erlang
A: There's kerl which is an excellent project for building and maintaining all Erlang/OTP versions | unknown | |
d5402 | train | It's hard to say exactly what's wrong based only on what you posted. But I do see that you are calculating the start date based on the end date, by only subtracting months. There is no allowance for days. So you might be missing some of that first month by not allowing for the early days of that first month.
That is , if end date occurs mid-month, I think your algorithm would cause start date to be mid-month also. Perhaps missing days 1-x of that first month. | unknown | |
d5403 | train | I found this webpage with a detailed explanation on how to make the conversion:
http://sandbox.mc.edu/~bennet/cs110/flt/ftod.html
The following is a copy-paste of one 8-bit example that breaks the binary string as 0 010 0110:
Convert the 8-bit floating point number 26 (in hex) to decimal.
Convert and separate: 2616 = 00100110 2
Exponent: 0102 = 210; 2 − 3 = -1.
Denormalize: 1.0112 × 2-1 = 0.1011.
Convert:
Exponents 20 2-1 2-2 2-3 2-4
Place Values 1 0.5 0.25 0.125 0.0625
Bits 0 . 1 0 1 1
Value 0.5 + 0.125 + 0.0625 = 0.6875
Sign: positive
Result: 26 is 0.6875. | unknown | |
d5404 | train | In principle, you can get this done in hbase very easily thanks to versioning. I've never tried something as extreme at 1,000 versions per column (normally 5-10) but I don't think there is any specific restriction as to how many versions you can have. You should just see if it creates any performance implications. Also check out this discussion: https://www.quora.com/Is-there-a-limit-to-the-number-of-versions-for-an-HBase-cell
When you define your table and your column family, you can specify the max versions parameter. This way, when you simply keep doing the Puts with the same row value, the key for that row will keep generating new versions (they will all be time-stamped as well. Once you do your 1,001th Put, the 1st put will automatically be deleted, and so on on the FIFO basis. Similarly, when you do a Get on that row-key, you can use various methods to retrieve a range of versions. In that case it depends on what API you will be using to get the values (this is easy to do with native Java API, but not sure about other access methods).
100mln rows is quite small for HBase, so generally it shouldn't be a problem. But of course if each of your rows really has 1,000 versions, then you are looking at 100bln key-values. Again, I'd say it's doable for HBase, but you should see imperially whether this causes any performance problems and you should size your cluster appropriately. | unknown | |
d5405 | train | You could just check if the color match the colorPicker value or not
if (cell.dataset.color !== colorPicker.value) {
cell.style.backgroundColor = colorPicker.value;
cell.dataset.color = colorPicker.value;
} else {
cell.style.backgroundColor = "";
cell.dataset.color = ""
}
https://codepen.io/anon/pen/EoLELd?editors=0010
Reason to why I'm setting a dataset color here is because backgroundColor converts the hexadecimal from the colorPicker value to RGB so a check between the two won't work. | unknown | |
d5406 | train | Yii2 Has different config files for web and console works. So you need to config both of them. Regarding this issue, I had to make mail config file (for example mailer.php) and include it in both config files (web.php & console.php) like:
'components' => [
...
'mailer' => require(__DIR__ . '/mailer.php'),
...
],
A: I think you have configured the mailer wrongly. Because it is still using the default mail function. From the documentation the configuration should be like below. The mailer should be inside components.
'components' => [
...
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.gmail.com',
'username' => 'username',
'password' => 'password',
'port' => '587',
'encryption' => 'tls',
],
],
...
],
One more suggestion is to use port "465" and encryption as "ssl" instead of port "587", encryption "tls".
A: Might be useful for someone as reference:
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '@common/mail',
'useFileTransport' => false,
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.gmail.com',
'username' => 'username',
'password' => 'password',
'port' => 587,
'encryption' => 'tls',
'streamOptions' => [
'ssl' => [
'allow_self_signed' => true,
'verify_peer' => false,
'verify_peer_name' => false,
],
]
],
] | unknown | |
d5407 | train | EDIT July 2022: Since the original solution worked only on older RxJS versions and was basically based on a bug in RxJS here's the same functionality for RxJS 7.0+:
import { of, defer, share, delay, tap, timestamp, map, Observable } from 'rxjs';
let counter = 1;
const mockHttpRequest = () =>
defer(() => {
console.log('Making request...');
return of(`Response ${counter++}`).pipe(delay(100));
});
const createCachedSource = (
makeRequest: () => Observable<any>,
windowTime: number
) => {
let cache;
return new Observable((obs) => {
const isFresh = cache?.timestamp + windowTime > new Date().getTime();
// console.log(isFresh, cache);
if (isFresh) {
obs.next(cache.value);
obs.complete();
} else {
return makeRequest()
.pipe(
timestamp(),
tap((current) => (cache = current)),
map(({ value }) => value)
)
.subscribe(obs);
}
}).pipe(share());
};
const cached$ = createCachedSource(() => mockHttpRequest(), 1000);
// Triggers the 1st request.
cached$.subscribe(console.log);
cached$.subscribe(console.log);
setTimeout(() => cached$.subscribe(console.log), 50);
setTimeout(() => cached$.subscribe(console.log), 200);
// Triggers the 2nd request.
setTimeout(() => cached$.subscribe(console.log), 1500);
setTimeout(() => cached$.subscribe(console.log), 1900);
setTimeout(() => cached$.subscribe(console.log), 2400);
// Triggers the 3nd request.
setTimeout(() => cached$.subscribe(console.log), 3000);
Live demo: https://stackblitz.com/edit/rxjs-rudgkn?devtoolsheight=60&file=index.ts
ORIGINAL ANSWER: If I understand you correctly you want to cache responses based on their id parameter so when I make two getProduct() with different ids I'll get two different uncached results.
I think the last variant is almost correct. You want it to unsubscribe from its parent so it can re-subscribe and refresh the cached value later.
The shareReplay operator worked differently until RxJS 5.5 if I recall this correctly where shareReplay has changed and it didn't re-subscribe to its source. It was later reimplemented in RxJS 6.4 where you can modify its behavior based on a config object passed to shareReplay. Since you're using shareReplay(1, 5000) it seems like you're using RxJS <6.4 so it's better to use publishReplay() and refCount() operators instead.
private cache: Observable<Product>[] = {}
getProduct$(id: string): Observable<Product> {
if (!this.cache[id]) {
this.cache[id] = this.http.get<Product>(`${API_URL}/${id}`).pipe(
publishReplay(1, 5000),
refCount(),
take(1),
);
}
return this.cache[id];
}
Notice that I also included take(1). That's because I want the chain to complete immediately after publishReplay emits its buffer and before it subscribes to its source Observable. It's not necessary to subscribe to its source because we just want to use the cached value. After 5s the cached value is discarded and publishReplay will subscribe to its source again.
I hope this all makes sense :). | unknown | |
d5408 | train | Simply Call your code on Form Load Event
private void Form1_Load(object sender, System.EventArgs e)
{
Thread.Sleep(5000);
RightClick(28, 132);
Thread.Sleep(2000);
LeftClick(35, 137);
}
you can also call your code into constructor but it would be better if you call it inside form_load event
public yourform()
{
Thread.Sleep(5000);
RightClick(28, 132);
Thread.Sleep(2000);
LeftClick(35, 137);
} | unknown | |
d5409 | train | If you really want to use for, you don't need recursion, but you would need a mutable variable:
val nums = List(1,2,3)
def recFold(zero: Int)(op: (Int, Int) => Int): Int = {
var result: Int = zero
for { a <- nums } result = op(result, a)
result
}
recFold(0)(_ + _) // 6
Which is pretty similar to how foldLeft is actually implemented in TraversableOnce:
def foldLeft[B](z: B)(op: (B, A) => B): B = {
var result = z
this foreach (x => result = op(result, x))
result
}
A: Fold can be implemented both ways right to left or left to right. No need to use for plus recursion. Recursion is enough.
def foldRight[A, B](as: List[A], z: B)(f: (A, B) => B): B = {
as match {
case Nil => z
case x :: xs => f(x, foldRight(xs, z)(f))
}
}
@annotation.tailrec
def foldLeft[A, B](as: List[A], z: B)(f: (A, B) => B): B = {
as match {
case Nil => z
case x :: xs => foldLeft(xs, f(x, z))(f)
}
} | unknown | |
d5410 | train | There are numerous errors in the program although it compiled without any warnings. Chiefly the pointer types for your array, and the memory allocated. Secondly the function does not know how many words is allowed, and does not return how many were read - your method did not work at all (as in comments). Thirdly the string comparisons: you did not state the goals clearly, but in comment you want the "biggest string". strcoll does not do that - it's a lexical comparison, so I changed that section to find the longest string for the two sentences you enter. See comments, I made a large number of changes.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int returnArrayOfWords (char *str4Parsing, char *arrayParsed[], int maxtokens) // added max
{
char seps[] = " ,\t\n"; // separators
char *token1 = NULL;
char *next_token1 = NULL;
int i = 0;
// Establish string and get the first token:
token1 = strtok_s( str4Parsing, seps, &next_token1);
// While there are tokens in "str4Parsing"
while (token1 != NULL)
{
if(i >= maxtokens)
return i; // ignore the rest
arrayParsed[i] = token1;
printf( " %s\n", token1 );
token1 = strtok_s( NULL, seps, &next_token1);
i++;
}
return i;
}
int main (void) // correct signature
{
int i, j, n = 80; /*max number of words in string*/
char arrS1[80], arrS2[80];
//const char *w1, *w2; /*pointers*/ // deleted
char **ptrArray1, **ptrArray2; // changed type
int currLength1 = 0, currLength2 = 0 ;
int sizeArr1 = 0, sizeArr2 = 0;
int maxLength = 0;
char *wordMaxLength; // changed to pointer
ptrArray1 = malloc(n * sizeof (char*)); // allocate mem for pointer array
if (ptrArray1 == NULL)
return 1;
ptrArray2 = malloc(n * sizeof (char*)); // allocate mem for pointer array
if (ptrArray2 == NULL)
return 1;
printf("Type your first string: ");
fgets(arrS1, 80, stdin);
sizeArr1 = returnArrayOfWords(arrS1, ptrArray1, n); // indirection error, added max words, get actual num
printf("Type your second string: ");
fgets(arrS2, 80, stdin);
sizeArr2 = returnArrayOfWords(arrS2, ptrArray2, n); // indirection error, added max words, get actual num
for (i = 0; i < sizeArr1; i++) // this section rewritten
{
// to find the largest word in the array
currLength1 = strlen(ptrArray1[i]);
if(currLength1 > maxLength)
{
maxLength = currLength1;
wordMaxLength = ptrArray1[i]; // changed definition to pointer
}
}
for (j = 0; j < sizeArr2; j++)
{
// to find the largest word in the array
currLength2 = strlen(ptrArray2[j]);
if(currLength2 > maxLength)
{
maxLength = currLength2;
wordMaxLength = ptrArray2[j]; // changed definition to pointer
}
}
printf("The largest word is: %s", wordMaxLength);
free(ptrArray1); // added
free(ptrArray2);
return 0;
}
Program session:
Type your first string: one two three four
one
two
three
four
Type your second string: apple banana pear
apple
banana
pear
The largest word is: banana | unknown | |
d5411 | train | On the security.yml you can set up that remember me is by default YES.
Here is the reference, i don't want to copy on the whole config file.
Symfony reference
A: My suggestion is to place tinyMCE (any 3rd party app on your site) behind the firewall.
#security.yml
firewalls:
tiny_mce:
pattern: ^/path/to/your/tinymce/dir
http_basic: # Any authentication provider here
realm: "Secured Demo Area"
When user will open tinymce, browser will request for http://example.com/path/to/your/tinymce/dir/tinymcefile.html. And symfony will require user for authentication, because you have mentioned this path in your security.yml
Update
Also this issue may appear when you was logged in on dev environment and then you try to access path from prod env or inverse! I see that for tiny mce you use dev env. Check on what env you was logged in previously. | unknown | |
d5412 | train | Your code looks ok to me, just remember that the value of a checkbox is posted only if the checkbox is checked, if it's not checket $_POST['chk'] is not set
EDIT - since you are revriting your checkboxes as suggested in the comment use an array
<?php
foreach ($holidays as $holiday)
{
$resultTable .= "<p><a href=\"{$holiday->link}\">{$holiday->title}</a>" . "<br/>" .
"{$holiday->pubDate}" . "<br>" .
"{$holiday->description}" . "<input type='checkbox' name='chk[]' value='{$holiday->title}' />" . "<br /></p>";
}
?>
And then server side $_POST['chk'] will be ann array
A: The problem is that you name each checkbox "chk", and when you submit the form, the values get overwritten. That's why it doesn't get anything in saveProcess.php. What you need to do, is either specify that the $_POST["chk"] can contain an array of value, like so:
<input type='checkbox' name='chk[]' value='{$holiday->title}' />
Notice the square brackets in the name. Now $_POST["chk"] will be an array.
Another way, would be to leave the html as it is, and just get the data, in saveProcess.php, using:
$HTTP_POST_VARS["chk"]
The first part basically explains why it doesn't work and how to fix it, while the second suggestion, is merely an alternate way of getting the data.
Have a great day! | unknown | |
d5413 | train | Try using a Set instead of an array so the order doesn't matter. You have to have this line at the top:
require 'set'
Then make a Set containing both objects and use it to help implement the equality operator and hash method. I assume Set#hash behaves correctly and your can use it in your hash method. Set#== can be used to simplify your equality operator.
http://www.ruby-doc.org/stdlib-2.1.4/libdoc/set/rdoc/Set.html
A: Are your B1 and B2 objects sortable? If so, here's an easy implementation of your hash method:
class MyClass
def hash
return [self.B1, self.B2].sort.hash
end
end
If they aren't currently sortable and it makes no sense to sort them by any inherent value, you could always just sort by object_id:
class BClass
include Comparable
def <=> (other)
case other
when BClass then return (self.object_id <=> other.object_id)
else return nil
end
end
end
This enables your B1 and B2 objects to sort themselves versus each other, while throwing "ArgumentError: comparison of X with Y failed" versus instances of any other class.
If you're going the route of using object_id, though, it may just be easier to implement your hash method using that to begin with:
class MyClass
def hash
return [self.B1.object_id, self.B2.object_id].sort.hash
end
end
but this will mean only self-same objects will correctly turn up as equal, and not just objects that "look" alike. To understand what I mean, compare the following:
# Comparison of look-alike objects
"a".object_id == "a".object_id # => false
# Comparison of self-same objects
a = "a"
a.object_id == a.object_id # => true
A: I assume the hash value can be any object as long as it is unique in each object in your case. If that assumption is correct, how about defining the object hash() method returns as an array, for example?
I am not 100% clear what you are trying to achieve. But I have interpreted the order of self.B1 and self.B2 does not matter. Then this is a possibility:
def hash
[self.B1.hash, self.B2.hash].sort
end
Then you can compare hash() of two objects with
(my_obj1.hash == my_obj2.hash) | unknown | |
d5414 | train | Change your second function definition as follows:
public OdbcDataReader QueryReader(OdbcCommand command)
{
var connection = GetConnection();
connection.Open;
try
{
command.Connection = connection;
command.Prepare();
return command.ExecuteReader(CommandBehavior.CloseConnection);
}
finally
{
//connection.Close();
}
}
I believe the solution is self explanatory. | unknown | |
d5415 | train | You can get your file like this:
$file = fopen(storage_path("whatever/file.txt"), "r");
This will result in a path similar to this
'/var/www/storage/whatever/file.txt' or '/var/www/foo/storage/whatever/file.txt' if you are serving multiple websites from the same server, it will depend on your setup, but you get the gist of it. Then you can read your file;
while(!feof($file)) {
echo fgets($file). "<br>";
}
fclose($file);
A: You need to know where your file lives. You also need a path to get there.
E.g., if your file is located in the storage folder, you could do
File::get(storage_path('whatever/test.txt'));
dd($contents);
A: Laravel v 9.0 update
File::lines('whatever/file.txt')->each(function ($line) {
$this->info($line);
}
A: $files = ExamFile::where('exam',$code)->get();
foreach ($files as $file)
{
$content = fopen(Storage::path($file->url),'r');
while(!feof($content)){
$line = fgets($content);
echo $line."<br>";
}
fclose($content);
}
You can use it like this. It works for me.
A: Hope it will help
File::get(storage_path('whatever/file.txt'));
A: So confusing!
My file was in the folder storage/app/whatever/file.txt but Laravel storage("whatever/file.txt") method recognizes it as storage/whatever/file.txt path.
As I said before it is overwhelming and confusing a lot.
So, fopen('storage/app/whatever/file.txt') works for me. | unknown | |
d5416 | train | First, there is something wrong described in your case: You should provide add the kubernetes internal load balancer private IP to the application gateway backend pool.
Then I did the test as the steps in Integrate Application Gateway with AKS cluster. As the error shows that you should make the check if the application in the AKS works fine, in your case the application is azure voting app.
If you follow the Azure Kubernetes Service tutorial and push the image to Azure Container Registry, you must grant the AKS permission to access your ACR. See Authenticate with Azure Container Registry from Azure Kubernetes Service.
And on my side, I can access the azure voting app from the public IP of the application gateway. Hope this will help you. | unknown | |
d5417 | train | Here's an extension function in Kotlin to grab the version number. The key is to call openHelper from your Room database which returns a SupportSQLiteOpenHelper object where you can then get to the actual DB attributes.
fun Context.getDBVersion() = RoomDatabase.getDatabase(this)?.openHelper?.readableDatabase?.version.toString() | unknown | |
d5418 | train | Don't create a new image each time; cache your UIImage, then use CoreGraphics calls to reposition your CGContextRef to 'point' to the right area, blit the image there, and move on. If you were to profile the code above, I imagine that CGImageCreateWithImageInRect() was taking up the vast majority of your cycles.
You should probably do this using contentOffset, rather than whatever _tableViewRect is. Also, looking at your code, while getting rid of the stuff above will help, I'm not sure it'll be enough, since you'll be redrawing a LOT. That said, here's a snippet that may work:
//I'm not sure what _tableViewRect is, so let's just assume you've got
//some variable, tableScrollY, that represents the scroll offset of your table
CGContextRef context = UIGraphicsGetCurrentContext();
if (tableScrollY < top.size.height) { //okay, we need to draw at least PART of our image
CGContextSaveGState(context);
CGContextDrawImage(context, CGRectMake(0, -tableScrollY, top.size.width, top.size.height), top.CGImage);
}
This should be a replacement for the middle if(...) portion of your code. This is not tested, so you may need to futz with it a bit. | unknown | |
d5419 | train | We may use tidyverse. Loop across the columns of 'DF1', get the column names of that column looped (cur_column()), use that to subset the 'DF2' (as row names) 'MEDIAN' element, do the comparison with almost.equal to return a logical vector, which is coerced to binary with as.integer or +. In the .names add the prefix 'dummy' so as to create as new columns
library(dplyr)
library(berryFunctions)
DF1 <- DF1 %>%
mutate(across(everything(), ~ +(almost.equal(.,
DF2[cur_column(), "MEDIAN"], tolerance = 1)),
.names = "dummy{.col}"))
-output
DF1
T01 T02 T03 T04 T05 dummyT01 dummyT02 dummyT03 dummyT04 dummyT05
1 15 20 48 25 5 0 0 0 0 0
2 12 18 35 30 12 1 1 0 1 1
3 13 15 50 60 42 1 0 0 0 0
Or using a for loop
for(i in seq_along(DF1))
DF1[paste0('dummy', names(DF1)[i])] <- +(almost.equal(DF1[[i]],
DF2[names(DF1)[i], "MEDIAN"], tolerance = 1))
data
DF1 <- structure(list(T01 = c(15L, 12L, 13L), T02 = c(20L, 18L, 15L),
T03 = c(48L, 35L, 50L), T04 = c(25L, 30L, 60L), T05 = c(5L,
12L, 42L)), class = "data.frame", row.names = c("1", "2",
"3"))
DF2 <- structure(list(MEDIAN = c(13L, 18L, 45L, 30L, 12L), SD = c(1.24,
2.05, 6.64, 15.45, 16.04)), class = "data.frame", row.names = c("T01",
"T02", "T03", "T04", "T05")) | unknown | |
d5420 | train | You don't have to worry about escaping your text as long as you use active records. | unknown | |
d5421 | train | Well, You can use firebase REST API Approach, in this case, I've used for my chrome app and its working fine. This don't require to have firebase SDK to be added!
Read the following docs,
https://firebase.googleblog.com/2014/03/announcing-streaming-for-firebase-rest.html
https://firebase.google.com/docs/reference/rest/database/
https://firebase.google.com/docs/database/rest/retrieve-data
Approach is very simple
Protocol is known as SSE (Server Sent Events) where you listen to specific server URL and when something changes, you get the event callback.
In this case, firebase officially provides SSE based mechanism
A sample code snippet is,
//firebaseUrl will be like https://xxxxx.firebaseio.com/yourNode.json or https://xxxxx.firebaseio.com/yourNode/.json
//notice ".json" at the end of URL, whatever node you want to listen, add .json as suffix
var firebaseEventSS = new EventSource(firebaseUrl);
//and you will have callbacks where you get the data
firebaseEventSS.addEventListener("patch", function (e) {
var data = e.data;
}, false);
firebaseEventSS.addEventListener("put", function (e) {
var data = e.data;
}, false);
Just check few EventSource examples and combine with Firebase Doc for REST API and you are all set!
Don't forget to close() when it's done.
firebaseEventSS.close();
A: This is an old question, but the solution offered by the Firebase team is to use a different URL protocol for the database.
So instead of using https://<app>.firebaseio.com/ you'd use wss://<app>.firebaseio.com/.
I found the solution here. Here is an answer provided by the Firebase team on this subject. | unknown | |
d5422 | train | If you limit the app to any geographical extent, then current users will be able to use it, but it won't appear to anyone on iTunes.
So, if you wanted an update for some region while having the previous version available, the answer is no, there's no way to do that.
@skorulis I find many reasons why you could want to do so, e.g. incremental release of the app update amongst many others. | unknown | |
d5423 | train | I really hate that you can't setup projects out of the box, though.
Just set up the project with sbt or maven and import it with ensime.
Essentially, what i would want is to be able to flex-find files in the project
"flex-find" is not English, so I don't really know what you mean. But what is wrong with find (the command line tool)?
A: With ensime you can load your project and then search for a type or method by name. The key sequence is C-c C-v v. This allows you to, for example, jump directly to a class definition.
A: The package projectile has a bunch of generic project-level features, such as running commands in the project root folder, grepping, creating TAGS files etc.
I'm a relatively new user of it, so I can't say exactly how big a difference it makes, but it seems like a worthwhile addition to your tool belt. | unknown | |
d5424 | train | I finally succeeded,
What I have changed:
/*
*
* TabsChooser
*
*/
import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { FormattedMessage } from 'react-intl';
import { createStructuredSelector } from 'reselect';
import { changeTab } from 'containers/App/actions';
import { makeSelectLocationState, makeSelectTabsChooser } from 'containers/App/selectors';
import messages from './messages';
import {Tabs, Tab} from 'material-ui/Tabs';
import FontIcon from 'material-ui/FontIcon';
const locationId = [
'/',
'/settings',
'/about',
];
export class TabsChooser extends React.Component { // eslint-disable-line react/prefer-stateless-function
render() {
this.contentsTab = [
{ route: this.props.onChangeTab.bind(null, locationId[0]), icon: <FontIcon className='material-icons'>home</FontIcon>, label: <FormattedMessage {...messages.home} />, },
{ route: this.props.onChangeTab.bind(null, locationId[1]), icon: <FontIcon className='material-icons'>settings</FontIcon>, label: <FormattedMessage {...messages.settings} />, },
{ route: this.props.onChangeTab.bind(null, locationId[2]), icon: <FontIcon className='material-icons'>favorite</FontIcon>, label: <FormattedMessage {...messages.about} />, },
];
let tabId = locationId.indexOf(this.props.tabLocation);
return (
<div>
<Tabs value={tabId} >
{this.contentsTab.map((tab, i) =>
<Tab key={i} value={i} icon={tab.icon} label={tab.label} onActive={tab.route} />
)}
</Tabs>
</div>
);
}
}
TabsChooser.propTypes = {
onChangeTab: React.PropTypes.func,
tabLocation: React.PropTypes.string,
};
function mapDispatchToProps(dispatch) {
return {
onChangeTab: (location) => dispatch(changeTab(location)),
};
}
const mapStateToProps = createStructuredSelector({
tabLocation: makeSelectTabsChooser(),
});
export default connect(mapStateToProps, mapDispatchToProps)(TabsChooser);
I now send the location instead of the the tab id in changeTab(),
I move action.js, reducer.js, selector.js and sagas.js into containers/App
action.js:
/*
* App Actions
*
*/
import { CHANGE_TAB, TABCHANGE_LOCATION } from './constants'
export function changeTab(tabLocation) {
return {
type: CHANGE_TAB,
tabLocation,
};
}
export function changeLocation(tabLocation) {
return {
type: TABCHANGE_LOCATION,
tabLocation,
};
}
constants.js:
/*
* AppConstants
*/
export const CHANGE_TAB = 'app/App/CHANGE_TAB';
export const TABCHANGE_LOCATION = 'app/App/TABCHANGE_LOCATION';
reducer.js:
/*
* AppReducer
*
*/
import { fromJS } from 'immutable';
import {
CHANGE_TAB,
TABCHANGE_LOCATION,
} from './constants';
// The initial state of the App
const initialState = fromJS({
tabLocation: window.location.pathname // Initial location from uri
});
function appReducer(state = initialState, action) {
switch (action.type) {
case CHANGE_TAB:
return state.set('tabLocation', action.tabLocation);
case TABCHANGE_LOCATION:
return state.set('tabLocation', action.tabLocation);
default:
return state;
}
}
export default appReducer;
The initialState tabLocation is set with the window.location.pathname, so the right tab is selected at app bootup.
selector.js:
/**
* The global state selectors
*/
import { createSelector } from 'reselect';
const selectGlobal = (state) => state.get('global');
const makeSelectLocationState = () => {
let prevRoutingState;
let prevRoutingStateJS;
return (state) => {
const routingState = state.get('route'); // or state.route
if (!routingState.equals(prevRoutingState)) {
prevRoutingState = routingState;
prevRoutingStateJS = routingState.toJS();
}
return prevRoutingStateJS;
};
};
const makeSelectTabsChooser = () => createSelector(
selectGlobal,
(globalState) => globalState.getIn(['tabLocation'])
);
export {
selectGlobal,
makeSelectLocationState,
makeSelectTabsChooser,
};
sagas.js:
import { take, call, put, select, takeLatest, takeEvery, cancel } from 'redux-saga/effects';
import { push } from 'react-router-redux';
import { changeLocation } from './actions';
import { makeSelectTabsChooser } from './selectors';
import { CHANGE_TAB } from './constants';
import { LOCATION_CHANGE } from 'react-router-redux';
function* updateLocation(action) {
//put() act as dispatch()
const url = yield put(push(action.tabLocation));
}
function* updateTab(action) {
const loc = yield put(changeLocation(action.payload.pathname));
}
// Individual exports for testing
export function* defaultSagas() {
const watcher = yield takeLatest(CHANGE_TAB, updateLocation);
const watcher2 = yield takeLatest(LOCATION_CHANGE, updateTab);
}
// All sagas to be loaded
export default [
defaultSagas,
];
So finally the sagas wrap it up. | unknown | |
d5425 | train | check if user is already logged in or not by
if (auth.getCurrentUser() != null)
//user logged in already, do your work here for logged in user
else
//user is not logged in, let user login
A: The back button most likely does not log the user out, but rather the UI elements have not updated with the user information.
If you suspect the user is being logged out, this would be an Auth refresh, which will trigger an onAuthStateChanged() event if you have one registered.
Otherwise, checking the current auth for the current user with auth().currentUser should yield null or a user object
Get current user
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
// User is signed in
} else {
// No user is signed in
}
Auth State Listener
mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
} else {
// User is signed out
}
Log.d("LOG_Login", "onAuthStateChanged:signed_out");
}
}
};
mAuth.addAuthStateListener(mAuthListener); | unknown | |
d5426 | train | Why not have make Field objects responsible for their own validation?
class Field
{
public bool Required { get; }
public string Value { get; set; }
// assuming that this method is virtual here
// if different Fields have different validation logic
// they should probably be separate classes anyhow and
// simply implement a common interface of inherit from a common base class.
public override bool IsValid
{
get { return Required && Value != String.Empty; }
}
} | unknown | |
d5427 | train | You can take a screenshot of the current activity using the given code
public void saveBitmap(Bitmap bitmap) {
File imagePath = new File(Environment.getExternalStorageDirectory() + "/screenshot.png");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
}
and make sure give write permissions of the storage in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> | unknown | |
d5428 | train | I would go with a DAO on it with two different methods to clearly differentiate what the call does.
The point of a DAO is to hide the SQL implementation details. You should always consider a question like this from the standpoint of, "What if I switched to a different persistence mechanism, like HBase?" The HBase implementation may not store this in a way that simply differentiates by a field name. The DAO should make it possible to hide that detail, thus the different methods.
Just my opinion, of course. :)
A: I would determine the logic in your controller and separate the two SQL queries into getListByOwnerBadge or getListByTaskeToBadge. That way you avoid having a method that "does it all" and could quickly get out of hand. Furthermore, other developers who choose to use the "does it all" method will have to inspect the method's internals to see what valid Strings can be passed in, whereas an explicit method call makes it obvious as to what the method is accomplishing.
A: I think that the second solution is better. Keep DAO as simple as it is possible. No logic, no flags. Create 2 simple methods and make decision in form which one to call. Or even create yet another layer between form and DAO that decides which DAO method to call.
A: To summarize:
From @McStretch - The logic for which to call goes in your controller.
From @rfreak - The query methods themselves go in the DAO
Here's an example:
//Controller
CommitmentListAction {
updateForm(...){
List<CommitmentItem> commitmentItems;
if (formUsesOwnedBy){
commitmentItems = CommitmentItemDAO.getListByOwnerBadge(...);
} else {
commitmentItems = CommitmentItemDAO.getListByTaskeToBadge(...);
}
// Do stuff with commitmentItems.
}
// DAO
getListByOwnerBadge(...){
String SQL_VIEW_LIST_BY_SUPERVISOR = SELECT_QUERY +
" WHERE c.OWNED_BY = ? " +
" ORDER BY p.PROGRAM_NAME"
return doQuery(SQL_VIEW_LIST_BY_SUPERVISOR); // Performs the actual query
}
getListByTaskeToBadge(...){
String SQL_VIEW_LIST_BY_TASKED_TO = SELECT_QUERY +
" WHERE c.TASKED_TO = ? " +
" ORDER BY p.PROGRAM_NAME"
return doQuery(SQL_VIEW_LIST_BY_TASKED_TO); // Performs the actual query
}
If you're going to have many different views of the CommitmetItems or many different criteria, consider passing in the criteria to the DAO. But only do this at the time when it appears there is an excessive number of getListBy[blah] methods polluting the DAO. | unknown | |
d5429 | train | I believe your goal is as follows.
*
*You want to convert the following curl command to Google Apps Script.
curl --location --request POST 'https://api.deliverr.com/oauth/v1/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'code={received_code_value}' \
--data-urlencode 'grant_type=authorization_code'
*You have already confirmed that your curl command worked fine.
In this case, how about the following modification?
Modified script:
function testGetToken() {
const url = "https://api.deliverr.com/oauth/v1/token";
const payload = {
'code': '{received_code_value}',
'grant-type': 'authorization_code'
};
const options = { payload };
const response = UrlFetchApp.fetch(url, options);
Logger.log(response.getContentText());
}
*
*When payload is used with UrlFetchApp, the POST method is automatically used.
*The default content type of the request header is application/x-www-form-urlencoded.
*In your curl command, the data is sent as the form.
Note:
*
*I think that the request of the above sample script is the same as your curl command. But, if an error occurs, please confirm your '{received_code_value}' and 'authorization_code' again.
Reference:
*
*fetch(url, params) | unknown | |
d5430 | train | Simplest would be to do the stroke first and then the fill. You may want to double your linewidth as doing this effectively cuts the lines in half.
%...
closepath
gsave
2 setlinewidth
black stroke
grestore
gold fill
A: PostScript is missing an anticlip operator, which should restrict painting to outside the current path. There is clip, which restricts painting to inside, but that doesn’t help with this problem.
As previously suggested, you could stroke at double linewidth, and then fill white, but if you want to paint this on top of something else, that strategy obscures whatever is below.
Or you could make the star a little bigger (I suspect, but haven’t checked, by currentlinewidth 2 5 sqrt 2 mul 5 div add sqrt mul 2 div), but that would only look right if 1 setlinejoin. | unknown | |
d5431 | train | This is better done in your build/packaging/release system not in your source control system. Since you're using hg archive (great choice) then theres a .hg_archive.txt file that's available to your packaging scripts or you can pass it to your release script as a parameter.
You're better off putting something like VERSION_GOES_HERE in your files and when you're archiving do:
LATEST_TAG="$(hg log --template '{latesttag}' -r)"
perl -pie "s/VERSION_GOES_HERE/${LATEST_TAG" | unknown | |
d5432 | train | As per the link you posted, seems you're using gcc. You can disable a lot of error/warning checks with a -Wno-xxxx flag, in your case -Wreturn-type is causing an error so you can disable it with:
-Wno-return-type
Frankly, it's better to just fix the errors/warnings when you can, and that one seems easy to fix. | unknown | |
d5433 | train | The natural way to backup EC2 instances is through snapshots. You can also create custom AMI which will simplify launching new instances with all the per-installed software of yours, along with its users and all the settings. | unknown | |
d5434 | train | The solution to my problem is illustrated here sharekit installation guide step 6
A: Things You have to do for Integrate Sharekit With your Application..(Recommended)
1) Actually You dont need to set URL scheme in .plist file for Sharekit. It's only for facebook API users..
2) Check out,Did you fill api key and secret key in SHKConfig.h file like this below
#define SHKFacebookKey @"YOUR_API_KEY"
#define SHKFacebookSecret @"YOUR_APP_SECRET_KEY"
3) Verify Did you "import SHK.h" file..
4) You have to include "MessageUI,SystemConfiguration and Security frameworks".
5) You dont need to do this #define SHKFacebookAppID @"MyFacebookAppID"
6) Invoke sharekit actionsheet as given in documentation.
A: The SHKConfig.h file seems to indicate that you don't include a literal "+" in your URL scheme. Check the last line of this quote:
// Facebook - https://developers.facebook.com/
// SHKFacebookAppID is the Application ID provided by Facebook
// SHKFacebookLocalAppID is used if you need to differentiate between several iOS apps running against a single Facebook app. Leave it blank unless you are sure of what you are doing.
// The CFBundleURLSchemes in your App-Info.plist should be "fb" + the concatenation of these two IDs.
// Example:
// SHKFacebookAppID = 555
// SHKFacebookLocalAppID = funk
//
// Your CFBundleURLSchemes entry: fb555funk | unknown | |
d5435 | train | An integer promotion results in an rvalue. long can be promoted to a long long, and then it gets bound to a const reference. Just as if you had done:
typedef long long type;
const type& x = type(l); // temporary!
Contrarily an rvalue, as you know, cannot be bound to a non-const reference. (After all, there is no actual long long to refer to.)
A: long long is not necessarily sized equal to long and may even use an entire different internal representation. Therefor you cannot bind a non-const reference to long to an object of type long long or the other way around. The Standard forbids it, and your compiler is correct to not allow it.
You can wonder the same way about the following code snippet:
long a = 0;
long long b = 0;
a = b; // works!
long *pa = 0;
long long *pb = pa;
The last initialization won't work. Just because a type is convertible to another one, doesn't mean another type that compounds one of them is convertible to a third type that compounds the other one. Likewise, for the following case
struct A { long i; };
struct B { long long i; };
A a;
B b = a; // fail!
In this case A and B each compound the type long and long long respectively, much like long& and long long& compound these types. However they won't be convertible into each other just because of that fact. Other rules happen to apply.
If the reference is to const, a temporary object is created that has the correct type, and the reference is then bound to that object.
A: I'm not a standards lawyer, but I think this is because long long is wider than long. A const reference is permitted because you won't be changing the value of l. A regular reference might lead to an assignment that's too big for l, so the compiler won't allow it.
A: Let's assume that it's possible :
long long &ref = l;
It means that later in the code you can change the value referenced by ref to the value that is bigger then long type can hold but ok for long long. Practically, it means that you overwrite extra bytes of memory which can be used by different variable with unpredictable results. | unknown | |
d5436 | train | Both elements and housetypes are 2D arrays, not 1D. The first dimension corresponds to the rows, and the second corresponds to columns.
When using Ubound, if dimension (2nd parameter) is omitted, 1 is assumed.
NumRowsElements = UBound(elements, 1)
NumColumnsHousetypes = UBound(housetypes, 2)
will return the results you want. | unknown | |
d5437 | train | In VBScript, you don't have to mention the name of the parameters while calling a function/method. You just need to pass the values. The parameters names are required in excel-vba, not in VBScript.
So, try replaying,
Worksheets("PO Buy Update").Range("H3").AutoFilter Field:=8, Criteria1:="<>"
Worksheets("PO Buy Update").Range("Q3").AutoFilter Field:=17, Criteria1:="<>"
Worksheets("PO Buy Update").Range("P3").AutoFilter Field:=16, Criteria1:=">=" & BeginDate, Operator:=xlAnd, Criteria2:="<=" & EndDate
with
Worksheets("PO Buy Update").Range("H3").AutoFilter 8,"<>"
Worksheets("PO Buy Update").Range("Q3").AutoFilter 17,"<>"
Worksheets("PO Buy Update").Range("P3").AutoFilter 16,">=" & BeginDate,1,"<=" & EndDate
Reference to the Autofilter Method
Reference to the enumerated constant xlAnd
A: VBScript can't handle named parameters. Change the last lines to
Worksheets("PO Buy Update").Range("H3").AutoFilter 8, "<>"
Worksheets("PO Buy Update").Range("Q3").AutoFilter 17, "<>"
Worksheets("PO Buy Update").Range("P3").AutoFilter 16, ">=" & BeginDate, xlAnd, "<=" & EndDate
and it'll hopefully get you a step closer. You might need to define xlAnd and other constants as well.
A: VBScript, as the other answers state, does not handle the named parameters.
Therefore it doesn't know what you mean by Worksheets. They will need to be fully qualified as references belonging to the parent objWorkbook object.
objWorkbook.Worksheets("PO Buy Update").Range("H3").AutoFilter 8, "<>"
will work just fine. You will need to replace any and all excel named values (such as xlAnd) with the enumerated value equivalent, or declare them as constants and set the value to match the enumerated value if you want to use the named parameter.
A: Thanks for your answers and pointing me, my mistakes. My final solution is below
Dim Path
Dim BeginDate
Dim EndDate
Path = WScript.Arguments.Item(0)
BeginDate = WScript.Arguments.Item(1)
EndDate = WScript.Arguments.Item(2)
Set objExcel = CreateObject("Excel.Application")
Set objWorkBook = objExcel.Workbooks.Open(Path)
Set c=objWorkBook.Worksheets("PO Buy Update") // Attached WorkbookSheet(name) into variable and then specified which row, column is a header
objExcel.Visible = True
c.cells(3,8).AutoFilter 8, "<>"
c.cells(3,17).AutoFilter 17, "<>"
c.cells(3,16).AutoFilter 16, ">=" & BeginDate, 1, "<=" & EndDate
I believe my main problem was that I have header in third row and when I did not specified that Script was searching for filtering option in first row.
Once again thanks for your time ! | unknown | |
d5438 | train | tl;dr
None of the solutions below update the input file in place; the stand-alone sed commands could be adapted with -i '' to do that; the awk solutions require saving to a different file first.
*
*The OP's input appears to be a file with classic Mac OS \r-only line breaks
Thanks, @alvits.
.
*sed invariably reads such a file as a whole, which is typically undesired and gets in the way of the OP's line-leading whitespace-trimming approach.
*awk is therefore the better choice, because it allow specifying what constitutes a line break (via the so-called input record separator):
Update: Replaced the original awk command with a simpler and faster alternative, adapted from peak's solution:
awk -v RS='\r' '{ sub(/^[ \t]+/, ""); print }'
If it's acceptable to also trim trailing whitespace, if any, from each line and to normalize whitespace between words on a line to a single space each, you can simplify to:
awk -v RS='\r' '{ $1=$1; print }'
Note that the output lines will be \n-separated, as is typically desired.
For an explanation and background information, including how to preserve \r as line breaks, read on.
Note: The first part of the answer applies generally, but assumes that the input has \n-terminated lines; the OP's special case, where lines are apparently \r-only-terminated, is handled in the 2nd part.
BSD Sed, as used on OSX, only supports \n as a control-character escape sequence; thus, \t for matching tab chars. is not supported.
To still match tabs, you can splice an ANSI C-quoted string yielding an actual tab char. into your Sed script ($'\t'):
sed 's/^[ '$'\t'']*//'
In this simple case you could use an ANSI C-quoted string for the entire Sed script (sed -e $'s/^[ \t]*//'), but this can get tricky with more complex scripts, because such strings have their own escaping rules.
*
*Note that option g was removed, because it is pointless, given that the regex is anchored to the start of the input (^).
*For a summary of the differences between GNU and BSD Sed, see this answer of mine.
As @alvits points out in a comment, the input file may actually have \r instances instead of the \n instances that Sed requires to separate lines.
I.e., the file may have Pre-OSX Mac OS line terminators: an \r by itself terminates a line.
An easy way to verify that is to pass the input file to cat -et: \r instances are visualized as ^M, whereas \n instances are visualized as $ (additionally, \t instances are visualized as ^I).
If only ^M instances, but no $ instances are in the output, the implication is that lines aren't terminated with \n (also), and the entire input file is treated as a single string, which explains why only the first input "line" was processed: the ^ only matched at the very beginning of the entire string.
Since a Sed solution (without preprocessing) causes the entire file to be read as a whole, awk is the better choice:
To create \n-separated output, as is customary on Unix-like platforms:
awk -v RS='\r' '{ sub(/^[ \t]+/, ""); print }'
*
*-v RS='\r' tells Awk to split the input into records by \r instances (special variable RS contains the input record separator).
*sub(/^[ \t]+/, "") searches for the first occurrence of regex ^[ \t]+ on the input line and replaces it with "", i.e., it effectively trims a leading run of spaces and tabs from each input line. Note that sub() without an explicit 3rd argument implicitly operates on $0, the whole input line.
*print then prints the potentially modified modified input line.
*By virtue of \n being Awk's default output record separator (OFS), the output records will be \n-terminated.
If you really want to retain \r as the line separator:
awk 'BEGIN { RS=ORS="\r" } { sub(/^[ \t]+/, ""); print }'
*
*RS=ORS="\r" sets both the input and the output record separator to \r.
If it's acceptable to also trim trailing whitespace, if any, from each line and to normalize whitespace between words on a line to a single space each, you can simplify the \n-terminated variant to:
awk -v RS='\r' '{ $1=$1; print }'
*
*Not using -F (and neither setting FS, the input field separator, in the script) means that Awk splits the input record into fields by runs of whitespace (spaces, tabs, newlines).
*$1=$1 is dummy assignment whose purpose is to trigger rebuilding of the input line, which happens whenever a field variable is assigned to.
The line is rebuilt by joining the fields with OFS, the output-field separator, which defaults to a single space.
In effect, leading and trailing whitespace is thereby trimmed, and each run of line-interior whitespace is normalized to a single space.
If you do want to stick with sed1
- even if that means reading the whole file at once:
sed $'s/^[ \t]*//; s/\r[ \t]*/\\\n/g' # note the $'...' to make \t, \r, \n work
This will output \n-terminated lines, as is customary on Unix.
If, by contrast, you want to retain \r as the line separators, use the following - but note that BSD Sed will invariably add a \n at the very end.
sed $'s/^[ \t]*//; s/\r[ \t]*/\r/g'
[1] peak's answer originally showed a pragmatic multi-utility alternative more clearly: replace all \r instances with \n instances using tr, and pipe the result to the BSD-Sed-friendly version of the original sed command:
tr '\r' '\n' file | sed $'s/^[ \t]*//'
A: If (as seems to be the case) the input file uses \r as the "end-of-line" character, then whatever else is done, it would probably make sense to convert the '\r' to '\n' or CRLF, depending on the platform. Assuming that '\n' is acceptable, and if there is any point in saving the original file with the CR replaced by LF, you could use tr:
tr '\r' '\n' < INFILE > OUTFILE
With a bash-like shell, you could then invoke sed like so:
sed -e $'s/^[ \t]*//' OUTFILE
The tr and sed commands could of course be strung together (tr ... | sed ...) but that incurs the overhead of a pipeline.
If you have no interest in saving the original file with the CR replaced by LF, then you may wish to consider the following one-stop awk variation:
awk -v RS='[\r]' '{s=$0; sub(/^[ \t]*/,"",s); print s}'
This variation is both fast and safe as no parsing into fields is involved.
(As pointed out elsewhere, one advantage of using awk is that ORS can be used to set the output-record-separator if the default setting is unsatisfactory.) | unknown | |
d5439 | train | You probably need an asterisk:
inside = (inside + averagel * (xrestriction * yrestriction)) - 2 * averagel * suml;
You can't multiply two values in C# like you can in mathematics. E.g. (averagel)(suml) makes sense in a math equation but you have to write averagel * suml in C#.
A: You've got your parentheses wrong and accidentally included a typecast in the expression. The bit at the end
(averagel) (suml)
Tries to cast suml to type averagel, and so the compiler's right to complain. I suspect you're missing an operator between those two terms. | unknown | |
d5440 | train | *.* selects files that have an extension, so it omits sub-folders.
Use * to select files and folders.
Then you should see your desired result.
for file in glob.glob("*"):
shutil.move(inpath+'/'+file,outpath)
A: You can use os.listdir to get all the files and folders in a directory.
import os
import shutil
def move_file_and_folders(inpath, outpath):
for filename in os.listdir(inpath):
shutil.move(os.path.join(inpath, filename), os.path.join(outpath, filename))
In your case,
inpath = <specify the source>
outpath = <specify the destination>
move_file_and_folders(inpath, outpath) | unknown | |
d5441 | train | By default, ajax is cached
cache (default: true, false for dataType 'script' and 'jsonp')
So add cache to the list of params
$.ajax({
cache : false,
type : 'POST',
url : 'quiz',
data : formData,
dataType : 'json',
encode : true
}) | unknown | |
d5442 | train | Your absolute import probably does not work because your root folder is not set to be mypackage. You can see here on how to do that: python: Change the scripts working directory to the script's own directory
Alternatively, you can use relative imports. You are correctly importing with from ..mypackage import module1 - however, you cannot execute a script directly with a relative import. You need to import the script into some other module which you are then executing. See explanation here: Relative imports in Python 3
A: I've had similar problems in the past and thus I've created a new import library: ultraimport
It gives you more control over your imports and lets you do file system based relative and absolute imports that do always work.
In your script1.py you could then write:
import ultraimport
module1 = ultraimport("__dir__/../mypackage/module1.py")
This will always work, no matter how you run your program and independent of all external factors. | unknown | |
d5443 | train | You can't pass null in Integer values.
public void sendEvent(String message, Integer code) {
Here Integer code return invalid either pass 0 or change it to String code
So now you can pass null values. | unknown | |
d5444 | train | I think that your @CucumberOptions are not correct and that's why the steps are not found
A: glue = "stepdefination2" here you need to specify package name under which stepdefinations class files are available. Avoid giving same name for package&class file. | unknown | |
d5445 | train | If the AV software exposes an API/CLI facility to disable it, you will need to find that from the AV company as they are all generally different.
You could uninstall the AV software, but it may not be silent about it, in other words the uninstall software may have prompts the user has to deal with before it uninstalls often requiring a reboot before you could run the windows defender scan, before you then have to reinstall the AV software. If it could uninstall/install silently, that might be a work around?
Another possible way would be to get handles to the AV software, walk through (enumerate) the screen controls and post events to the controls to simulate a user, but this is getting more into coding than scripting, and you still may not be able to walk through the controls, for example some web browsers dont let you enumerate the address bar in order to post web addresses into them and hijack them that way. | unknown | |
d5446 | train | Depends on your SQL DB. You can add your SQL DB as ESS or you can use "Execute SQL" and run a SQL query on ODBC DNS to your database.
If you are in 16 and your SQL has any API, you can call them through CURL. You can do the same with previous versions of FileMaker using plugins. | unknown | |
d5447 | train | It means that you trying to access an element in an array by using index as number with decimal point or a negative number, or maybe even using a string that looks like a number e.g. "2".
The only way to access the elements is by using positive integer OR logical (0 or 1).
array = [1 2 3 4 5 6];
array(4) # returns 4th element of the array, 4.
mask = array > 3; # creates a mask of 0's and 1's (logicals).
array(mask) # return elements greater than 3, 4 5 6.
BUT you can't do:
array(2.0)
Or anything else other than positive integer or logical.
Alex | unknown | |
d5448 | train | As long as you are grouping using the same column you should be to go. Unfortunately it is not the case if you want to group on different columns. The counts will be narrowed to the whole list of the GROUP BY, for example if you want to group by OrderLines.ID as well.
For a better performance, I would use calculated columns in the Orders table.
First you need to create a user defined function:
CREATE FUNCTION dbo.GetOrderWeight(@Key int)
RETURNS int
AS
BEGIN
RETURN (
SELECT SUM(Weight1)
FROM LineItems
WHERE OrderID = @Key
)
END
Then add a calculated column to the table:
ALTER TABLE Orders ADD OrderWeight AS dbo.GetOrderWeight(ID)
Follow with the same for other aggregate methods you have. Please be aware that this is a performance killer if used with function that has varchar(max) as input parameter type.
A: This is should be more effective then using subselects.
Just be sure that you have proper indexes to get the best performance. | unknown | |
d5449 | train | Figured it out. You need to add things like 'telemetry' (and other configuration stanzas) to the server.ha.config data structure in your values.yaml. This will push changes to vault's configmap. You then bounce all vault nodes and you're good-to-go! | unknown | |
d5450 | train | Flow.first() cancels the flow once the first value has been collected.
In your case, it means that the awaitClose function is never reached.
*
*The call to callbackFlow.first() triggers flow collection
*The send("value") transmit value to the collector
*The collector cancels the flow
*Then, depending on your implementation
*
*The delay might have start, and is cancelled along the flow. The "awaitClose" function is never reached.
*Without delay, there's a chance that 'awaitClose' might register the lambda (and therefore execute it) faster than the collector cancels the flow.
Note however, I'm not sure that the awaitClose is always reachable, even without delay. More research would be needed to give a definitive answer for that. | unknown | |
d5451 | train | The WebView class doesn't provide as much flexibility in its connectivity as using the low level classes (such as HttpPost or the like) directly.
If you need to fully control the connection to the server -- or deal with complicated authorization scenarios such as this one -- use the low level classes, retrieve the data, then use WebView.loadData() to load and show the HTML.
Here is a good example of loading content using SSL and a BasicCredentialProvider. The result of this could be loaded into the WebView as described above.
A: As it seems that WebView cannot natively handle Basic authentication when using HTTPS, I started toying with the idea of setting the Authorization header (containing the encoded username/password) manually.
Here's how I think this can be done:
import org.apache.commons.codec.binary.Base64;
// ...
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.connwebview);
// Getting info from Intent extras
// Get it if it s different from null
Bundle extras = getIntent().getExtras();
mUsrName = extras != null ? extras.getString("username") : null;
mPassC = extras != null ? extras.getString("passcode") : null;
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
// mWebView.setHttpAuthUsernamePassword("myhost.com",
// "myrealm",
// mUsrName,
// mPassC);
mWebView.setWebViewClient(new WebViewClient() {
@Override
public void onReceivedHttpAuthRequest(WebView view,
HttpAuthHandler handler,
String host,
String realm){
handler.proceed(mUsrName, mPassC);
}
public void onReceivedSslError(WebView view,
SslErrorHandler handler,
SslError error) {
handler.proceed() ;
}
});
String up = mUserName +":" +mPassC;
String authEncoded = new String(Base64.encodeBase64(up.getBytes()));
String authHeader = "Basic " +authEncoded;
Map<String, String> headers = new HashMap<String, String>();
headers.put("Authorization", authHeader);
mWebView.loadUrl("https://myhost.com/secured_area", headers);
}
This takes advantage of the WebView.loadUrl (String url, Map<String, String> additionalHttpHeaders) method and for this example I'm using the Base64Encoder from Apache Commons. The Base64Encoder part is quite trivial and if you didn't want to include external libraries in your application (for whatever reason), you could always write your own (reference).
Also note that the aforementioned WebView.loadUrl (String url, Map<String, String> additionalHttpHeaders) method is only available in API 8+. For reference, see also the Wikipedia article on Basic Authentication (which discusses the headers, etc).
A: Alternative Scenario:
If willing to write roundabout 10 lines of javascript using jQuery, this scenario is rather simple.
Inject your javascript code into the webview or in case you're controlling the html page you are displaying, include it there.
If you need to interface back from javascript, you can do that. For heavier command exchange, use the CordovaWebView-Interface which has a lower delay depending on api level. | unknown | |
d5452 | train | You can try to increase the fielddata circuit breaker limit to 75% (default is 60%) in your elasticsearch.yml config file and restart your cluster:
indices.breaker.fielddata.limit: 75%
Or if you prefer to not restart your cluster you can change the setting dynamically using:
curl -XPUT localhost:9200/_cluster/settings -d '{
"persistent" : {
"indices.breaker.fielddata.limit" : "40%"
}
}'
Give it a try.
A: I meet this problem,too.
Then i check the fielddata memory.
use below request:
GET /_stats/fielddata?fields=*
the output display:
"logstash-2016.04.02": {
"primaries": {
"fielddata": {
"memory_size_in_bytes": 53009116,
"evictions": 0,
"fields": {
}
}
},
"total": {
"fielddata": {
"memory_size_in_bytes": 53009116,
"evictions": 0,
"fields": {
}
}
}
},
"logstash-2016.04.29": {
"primaries": {
"fielddata": {
"memory_size_in_bytes":0,
"evictions": 0,
"fields": {
}
}
},
"total": {
"fielddata": {
"memory_size_in_bytes":0,
"evictions": 0,
"fields": {
}
}
}
},
you can see my indexes name base datetime, and evictions is all 0. Addition, 2016.04.02 memory is 53009116, but 2016.04.29 is 0, too.
so i can make conclusion, the old data have occupy all memory, so new data cant use it, and then when i make agg query new data , it raise the CircuitBreakingException
you can set config/elasticsearch.yml
indices.fielddata.cache.size: 20%
it make es can evict data when reach the memory limit.
but may be the real solution you should add you memory in furture.and monitor the fielddata memory use is good habits.
more detail: https://www.elastic.co/guide/en/elasticsearch/guide/current/_limiting_memory_usage.html
A: Alternative solution for CircuitBreakingException: [FIELDDATA] Data too large error is cleanup the old/unused FIELDDATA cache.
I found out that fielddata.limit been shared across indices, so deleting a cache of an unused indice/field can solve the problem.
curl -X POST "localhost:9200/MY_INDICE/_cache/clear?fields=foo,bar"
For more info https://www.elastic.co/guide/en/elasticsearch/reference/7.x/indices-clearcache.html
A: I think it is important to understand why this is happening in the first place.
In my case, I had this error because I was running aggregations on "analyzed" fields. In case you really need your string field to be analyzed, you should consider using multifields and make it analyzed for searches and not_analyzed for aggregations.
A: I ran into this issue the other day. In addition to checking the fielddata memory, I'd also consider checking the JVM and OS memory as well. In my case, the admin forgot to modify the ES_HEAP_SIZE and left it at 1gig.
A: just use:
ES_JAVA_OPTS="-Xms10g -Xmx10g" ./bin/elasticsearch
since the default heap is 1G, if your data is big ,you should set it bigger | unknown | |
d5453 | train | All you needed is to precise the charset. Here you go :
import org.bouncycastle.crypto.BufferedBlockCipher;
import org.bouncycastle.crypto.DataLengthException;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.engines.AESFastEngine;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;
public class Main
{
private BufferedBlockCipher cipher;
private final KeyParameter key = setEncryptionKey("testinggtestingg");
private static final String CHARSET = "ISO-8859-1";
public static void main(String[] argv)
{
Main main = new Main();
String plain = "trallalla";
System.out.println("initial : " + plain);
String encrypted = main.encryptString(plain);
System.out.println("after encryption : " + encrypted);
String decrypted = main.decryptString(encrypted);
System.out.println("after decryption : " + decrypted);
}
public KeyParameter setEncryptionKey(String keyText)
{
// adding in spaces to force a proper key
keyText += " ";
// cutting off at 128 bits (16 characters)
keyText = keyText.substring(0, 16);
byte[] keyBytes = keyText.getBytes();
// key = new KeyParameter(keyBytes);
AESFastEngine engine = new AESFastEngine();
cipher = new PaddedBufferedBlockCipher(engine);
return new KeyParameter(keyBytes);
}
public String encryptString(String plainText)
{
try
{
byte[] plainArray = plainText.getBytes();
cipher.init(true, key);
byte[] cipherBytes = new byte[cipher.getOutputSize(plainArray.length)];
int cipherLength = cipher.processBytes(plainArray, 0, plainArray.length, cipherBytes, 0);
cipher.doFinal(cipherBytes, cipherLength);
return (new String(cipherBytes, CHARSET));
}
catch (DataLengthException e)
{
e.printStackTrace();
}
catch (IllegalArgumentException e)
{
e.printStackTrace();
}
catch (IllegalStateException e)
{
e.printStackTrace();
}
catch (InvalidCipherTextException e)
{
e.printStackTrace();
}
catch (Exception ex)
{
ex.printStackTrace();
}
// else
return null;
}
public String decryptString(String encryptedText)
{
try
{
byte[] cipherBytes = encryptedText.getBytes(CHARSET);
cipher.init(false, key);
byte[] decryptedBytes = new byte[cipher.getOutputSize(cipherBytes.length)];
int decryptedLength = cipher.processBytes(cipherBytes, 0, cipherBytes.length, decryptedBytes, 0);
cipher.doFinal(decryptedBytes, decryptedLength);
String decryptedString = new String(decryptedBytes);
// crop accordingly
int index = decryptedString.indexOf("\u0000");
if (index >= 0)
{
decryptedString = decryptedString.substring(0, index);
}
return decryptedString;
}
catch (DataLengthException e)
{
e.printStackTrace();
}
catch (IllegalArgumentException e)
{
e.printStackTrace();
}
catch (IllegalStateException e)
{
e.printStackTrace();
}
catch (InvalidCipherTextException e)
{
e.printStackTrace();
}
catch (Exception ex)
{
ex.printStackTrace();
}
// else
return null;
}
}
But why are you using this external library ? Here is the code I use and which does not need any external libraries:
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.*;
import javax.crypto.spec.*;
public class Encryption
{
private static final String ALGORITHME = "Blowfish";
private static final String TRANSFORMATION = "Blowfish/ECB/PKCS5Padding";
private static final String SECRET = "kjkdfjslm";
private static final String CHARSET = "ISO-8859-1";
public static void main(String[] argv) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException
{
Encryption main = new Encryption();
String plain = "trallalla";
System.out.println("initial : " + plain);
String encrypted = main.encrypt(plain);
System.out.println("after encryption : " + encrypted);
String decrypted = main.decrypt(encrypted);
System.out.println("after decryption : " + decrypted);
}
public String encrypt(String plaintext)
throws NoSuchAlgorithmException,
NoSuchPaddingException,
InvalidKeyException,
UnsupportedEncodingException,
IllegalBlockSizeException,
BadPaddingException
{
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(SECRET.getBytes(CHARSET), ALGORITHME));
return new String(cipher.doFinal(plaintext.getBytes()), CHARSET);
}
public String decrypt(String ciphertext)
throws NoSuchAlgorithmException,
NoSuchPaddingException,
InvalidKeyException,
UnsupportedEncodingException,
IllegalBlockSizeException,
BadPaddingException
{
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(SECRET.getBytes(), ALGORITHME));
return new String(cipher.doFinal(ciphertext.getBytes(CHARSET)), CHARSET);
}
} | unknown | |
d5454 | train | It sounds like you're just asking how to cut a column across into another worksheet. This will move everything in the K column in the master sheet and copy it to the A column in wtd. Obviously this can be changed to any column you want.
Sheets("wtd").Range("A:A").Value = Sheets("master").Range("K:K").Value | unknown | |
d5455 | train | The two methods: scrollViewWillBeginDecelerating and scrollViewDidEndDecelerating contains two animation with different x position it is animated to:
frame.origin.x = frame.size.width-15*gallerypage;
and
frame.origin.x=gallerypage*290;
It is better if you could turn off either function: scrollViewWillBeginDecelerating or scrollViewDidEndDecelerating. Otherwise probably you should adjust the x position (must be in sync for both functions) it will be animated to.
A: if (i==0) {
webview=[[UIImageView alloc]initWithFrame:CGRectMake(i*320, 0, 270, 440)];
}
else {
webview=[[UIImageView alloc]initWithFrame:CGRectMake(i*320, 0, 270, 380)];
}
A: You need to change your implementation for loading the images from a remote resource, thats where the biggest bottle neck lies.
I don't want to go into details but try to replace this line of code
[webview setImageWithURL:url placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
With something more c.p.u friendly. Use a caching mechanism that employs multi-threading, what you want to do is move the heavy lifting (Downloading remote images) to another thread.
SDWebImage does a perfect job at this https://github.com/rs/SDWebImage
If you are a bit hard core, you can roll your own multi-threaded image downloader using
[NSURLConnection sendAsynchronousRequest:queue: completionHandler:]
And do the image loading in the block, Or even better dispatch_async(queu, block)
A: You should checkout SYPaginator (SYPaginator is a horizontal TableView with lazy loading and view recycling.)
Simple paging scroll view to make complicated tasks easier. We use
this in several of the Synthetic apps including Hipstamatic, D-Series,
and IncrediBooth.
If you need more perfomance you should give MSCachedAsyncViewDrawing a try:
Helper class that allows you to draw views (a)synchronously to a
UIImage with caching for great performance.
A: I think that happens because your images are larger in size (MB) , and you fit them into that CGRect without resizing them that specific size, also it matters how many pictures you have loaded inside the scrollview , if you load many pictures it will take a lot of memory and it will slide slowly.
A: It happens when you are trying to show an image of larger size in that case you have to use cache to get the image there and try to load image from there.For better know how to use it..use SDwebimage thats the nice way to do it and it is fast.
You can read
*
*Lazy Loading
2.paging enabled.
https://github.com/rs/SDWebImage
Need any further help.Happy to help you.
A: I am not sure why are you setting the frame when you start scrolling, but if I were in your place I would do the logic as per below:
-(void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{
// do nothing
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
int gallerypage = scrollView.contentOffset.x /scrollView.frame.size.width;
CGFloat xoffset = 290 * gallerypage;
[UIView animateWithDuration:0.5
animations:^{
scrollView.contentOffset = CGPointMake(xoffset, 0);
}
completion:^(BOOL finished){
NSLog(@"Done!");
}];
}
Hope it helps.
A: You should definitely resize your image in background prior to loading it into UIImageView. Also you should set UIImageView content mode to the none-resizing one. It gave me significantly scrolling improvement after other ways were already implemented (async cache and others). | unknown | |
d5456 | train | You want to setup your hierarchy like this:
Tab1 -> Nav1 -> View
Root --> Tab Controller -> Tab2 -> Nav2 -> View
Tab3 -> Nav3 -> View
So each tab will have it's own Nav controller, which will have an initial view pushed onto it.
In your example you have your Nav controller as the root, containing the Tab controller. This is backwards - you want the Tab controller to contain the Nav controllers. | unknown | |
d5457 | train | Here is OpenCV implementation
# OpenCV implementation of crop/resize using affine transform
import numpy as np
from matplotlib import pyplot as plt
%matplotlib inline
import cv2
src_rgb = cv2.imread('test_img.jpg')
# Source width and height in pixels
src_w_px = 640
src_h_px = 480
# Target width and height in pixels
res_w_px = 640
res_h_px = 480
# Scaling parameter
s = 2.0
Affine_Mat_w = [s, 0, res_w_px/2.0 - s*src_w_px/2.0]
Affine_Mat_h = [0, s, res_h_px/2.0 - s*src_h_px/2.0]
M = np.c_[ Affine_Mat_w, Affine_Mat_h].T
res = cv2.warpAffine(src_rgb, M, (res_w_px, res_h_px))
# Showing the result
plt.figure(figsize=(15,6))
plt.subplot(121); plt.imshow(src_rgb); plt.title('Original image');
plt.subplot(122); plt.imshow(res); plt.title('Image warped Affine transform');
A: OpenCV implementation of crop image && resize to (des_width, des_height) using affine transform
import numpy as np
import cv2
def crop_resized_with_affine_transform(img_path, roi_xyxy, des_width, des_height):
src_rgb = cv2.imread(img_path)
'''
image roi
(x0,y0)------------(x1,y1)
| |
| |
| |
| |
| |
| |
| |
| |
(-,-)------------(x2, y2)
'''
src_points = [[roi_xyxy[0], roi_xyxy[1]], [roi_xyxy[2], roi_xyxy[1]], [roi_xyxy[2], roi_xyxy[3]]]
src_points = np.array(src_points, dtype=np.float32)
des_points = [[0, 0], [des_width, 0], [des_width, des_height]]
des_points = np.array(des_points, dtype=np.float32)
M = cv2.getAffineTransform(src_points, des_points)
crop_and_resized_with_affine_transform = cv2.warpAffine(src_rgb, M, (des_width, des_height))
return crop_and_resized_with_affine_transform
def crop_resized(img_path, roi_xyxy, des_width, des_height):
src_rgb = cv2.imread(img_path)
roi_img = src_rgb[roi_xyxy[1]:roi_xyxy[3], roi_xyxy[0]:roi_xyxy[2]]
resized_roi_img = cv2.resize(roi_img, (des_width, des_height))
return resized_roi_img
if __name__ == "__main__":
'''
Source image from
https://www.whitehouse.gov/wp-content/uploads/2021/04/P20210303AS-1901.jpg
or
https://en.wikipedia.org/wiki/Joe_Biden#/media/File:Joe_Biden_presidential_portrait.jpg
'''
img_path = "Joe_Biden_presidential_portrait.jpg"
# xmin ymin xmax ymax
roi_xyxy = [745, 265, 1675, 1520]
des_width = 480
des_height = 720
crop_and_resized_with_affine_transform = crop_resized_with_affine_transform(img_path, roi_xyxy , des_width, des_height)
resized_roi_img = crop_resized(img_path, roi_xyxy, des_width, des_height)
cv2.imshow("crop_and_resized_with_affine_transform", crop_and_resized_with_affine_transform)
cv2.imwrite("crop_and_resized_with_affine_transform.jpg", crop_and_resized_with_affine_transform)
cv2.imshow("resized_roi_img", resized_roi_img)
cv2.imwrite("resized_roi_img.jpg", resized_roi_img)
cv2.waitKey(0)
Source image is Wiki:Joe_Biden_presidential_portrait.jpg | unknown | |
d5458 | train | With the introduction of Facebook Timeline the way to remove scroll bars and control page margins has changed. First (and most importantly) your body padding and margins MUST all be set to zero. This ensures all browsers process your canvas settings off absolute zero.
Depending on the 'Page Tab Width' (520px or 810px) option you set in your Apps/Page settings you will need to adjust the width in the following code. This block should be placed in the page Head:
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.Canvas.setSize();
}
// Do things that will sometimes call sizeChangeCallback()
function sizeChangeCallback() {
FB.Canvas.setSize();
}
</script>
Just below the Body tag add the following code:
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({appId: 'YOUR APP ID', status: true, cookie: true, xfbml: true});
window.fbAsyncInit = function() {
FB.Canvas.setSize({ width: 520, height: 1000 });
}
</script>
Remember to change 'YOUR APP ID'. Also width: should equal either 520 or 810. Set height: slightly larger than you require to allow overflow.
This solution has been tested in IE, FF, Safari and Chrome!
A: I added this to my css and it seemed to work:
body {
margin-top: -20px;
padding-top: 20px;
}
If you already have padding added to the top of your body, you will likely need to add 20px to it.
I assume it's because firefox measures the body height differently than other browsers.
Tested in ff8, chrome16 and ie9 with no negative repercussions.
A: I had solved this problem that way:
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
window.fbAsyncInit = function() {
FB.init({
appId : app_id, // App ID
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
var height_doc = $(document).height()+20;
FB.Canvas.setSize({height: height_doc});
};
It's works for me. I hope that help.
A: This is a known issue with canvas apps and page tabs, and has annoyingly been around for quite a while.
https://developers.facebook.com/bugs/309917422436936
Some people mention being able to use FB.Canvas.setSize({ width: 700, height: 800 }); or something like FB.Canvas.setAutoResize(500); and it gets around the issue.
Have you definitely set the iframe auto resize option in the apps control panel too?
A: Forget about body and html margins (I mean set them to zero).
Just place all your content (including header and footer) into a table with single cell.
At least all browsers will agree on how to calculate the height of the table...
like this:
<table id='m_table' width=100% align=left border=0 cellspacing=0 cellpadding=0>
<tr><td valign=top bgcolor=white align=center style='position:relative;'>
and do this :
setTimeout(function() {FB.Canvas.setSize({height:(document.getElementById('m_table').offsetHeight+40)})}, 1000);
works in IE,FireFox and Chrome/Safari...
Here is FB initialization code if you need it:
window.fbAsyncInit = function() {
FB.init({appId:'your_app_id',status:true,cookie:true,xfbml:true});fbApiInit = true;
}
function fbEnsureInit(callback)
{
if(!window.fbApiInit) setTimeout(function() {fbEnsureInit(callback);}, 50);
else if(callback) callback();
}
fbEnsureInit(function() {
FB.Canvas.scrollTo(0,0);
var h = document.getElementById('m_table').offsetHeight+40;
// console.log('setting size to '+h);
FB.Canvas.setSize({height:h});
setTimeout(function() {FB.Canvas.setSize({height:(document.getElementById('m_table').offsetHeight+40)})}, 1000);
}); | unknown | |
d5459 | train | The way I currently deal with this is through numpy:
*
*Read image into a 2D numpy array. You don't need to use numpy, but I've found it easier to use than the regular Python 2D arrays
*Convert 2D numpy array into PIL.Image object using PIL.Image.fromarray
If you insist on using PIL.Image.open, you could write a wrapper that attempts to load a PGM file first (by looking at the header). If it's a PGM, load the image using the steps above, otherwise just hands off responsibility to PIL.Image.open.
Here's some code that I use to get a PBM image into a numpy array.
import re
import numpy
def pbm2numpy(filename):
"""
Read a PBM into a numpy array. Only supports ASCII PBM for now.
"""
fin = None
debug = True
try:
fin = open(filename, 'r')
while True:
header = fin.readline().strip()
if header.startswith('#'):
continue
elif header == 'P1':
break
elif header == 'P4':
assert False, 'Raw PBM reading not implemented yet'
else:
#
# Unexpected header.
#
if debug:
print 'Bad mode:', header
return None
rows, cols = 0, 0
while True:
header = fin.readline().strip()
if header.startswith('#'):
continue
match = re.match('^(\d+) (\d+)$', header)
if match == None:
if debug:
print 'Bad size:', repr(header)
return None
cols, rows = match.groups()
break
rows = int(rows)
cols = int(cols)
assert (rows, cols) != (0, 0)
if debug:
print 'Rows: %d, cols: %d' % (rows, cols)
#
# Initialise a 2D numpy array
#
result = numpy.zeros((rows, cols), numpy.int8)
pxs = []
#
# Read to EOF.
#
while True:
line = fin.readline().strip()
if line == '':
break
for c in line:
if c == ' ':
continue
pxs.append(int(c))
if len(pxs) != rows*cols:
if debug:
print 'Insufficient image data:', len(pxs)
return None
for r in range(rows):
for c in range(cols):
#
# Index into the numpy array and set the pixel value.
#
result[r, c] = pxs[r*cols + c]
return result
finally:
if fin != None:
fin.close()
fin = None
return None
You will have to modify it slightly to fit your purposes, namely:
*
*Deal with P2 (ASCII, greyscale) instead of P1 (ASCII, bilevel).
*Use a different container if you're not using numpy. Normal Python 2D arrays will work just fine.
EDIT
Here is how I would handle a wrapper:
def pgm2pil(fname):
#
# This method returns a PIL.Image. Use pbm2numpy function above as a
# guide. If it can't load the image, it returns None.
#
pass
def wrapper(fname):
pgm = pgm2pil(fname)
if pgm is not None:
return pgm
return PIL.Image.open(fname)
#
# This is the line that "adds" the wrapper
#
PIL.Image.open = wrapper
I didn't write pgm2pil because it's going to be very similar to pgm2numpy. The only difference will be that it's storing the result in a PIL.Image as opposed to a numpy array. I also didn't test the wrapper code (sorry, a bit short on time at the moment) but it's a fairly common approach so I expect it to work.
Now, it sounds like you want other applications that use PIL for image loading to be able to handle PGMs. It's possible using the above approach, but you need to be sure that the above wrapper code gets added before the first call to PIL.Image.open. You can make sure that happens by adding the wrapper source code to the PIL source code (if you have access). | unknown | |
d5460 | train | You can achieve this with itertools that is in the standard library (you do not need to install, just import). Although there are other ways you can toggle between values, this one is convenient. I changed some parts of you code, you can let me know if theres something you do not understand.
import itertools
blueLower = [110, 50, 50]
blueUpper = [130, 255, 255]
greenLower = [29, 86, 6]
greenUpper = [64, 255, 255]
greenBounds = (greenLower, greenUpper)
blueBounds = (blueLower, blueUpper)
def loop(colorBounds, iterator):
radius = 0
lower, upper = colorBounds
print(lower, upper)
while True:
radius += 1
if radius > 250:
loop(iterator(), iterator)
toggle = itertools.cycle([greenBounds, blueBounds]).__next__
loop(greenBounds, toggle)
To clarify, I added radius=0 and radius += 1 for my own testing purposes. | unknown | |
d5461 | train | Regex is good for matching & replacing in strings based on patterns.
But to look for the differences between strings? Not exactly.
However, diff can be used to find differences.
object Main extends App {
val a = "some text abc123 some more text 321abc"
val b = "some text xyz some more text zyx"
val firstdiff = (a.split(" ") diff b.split(" "))(0)
println(firstdiff)
}
prints "abc123"
Is regex desired after all? Then realize that the splits could be replaced by regex matching.
The regex pattern in this example looks for words:
val reg = "\\w+".r
val firstdiff = (reg.findAllIn(a).toList diff reg.findAllIn(b).toList)(0) | unknown | |
d5462 | train | Use stop function of sortable evry time you sort the element from div with id sortable1.
Working Demo
stop: function( event, ui ) {
if($('#sortable2').find('img').length==5)
$('#btn-start').html("end");
}
A: You can write a callback function on the sortable method like the following:
$( "#sortable1" ).sortable({
connectWith: "div",
stop: function() {
// your logic goes here
}
});
You can also use the start callback. | unknown | |
d5463 | train | DBMS_ERROR_TEXT returns the entire sequence of recursive errors
so you should get all the required information from that
Kindly use
exception when others then functionThatPrintsMe(DBMS_ERROR_TEXT);
for more information about oracle 6i forms you can refer
http://www.oracle.com/technetwork/documentation/6i-forms-084462.html
A: At form level ON-ERROR TRIGGER .Add these lines will solve your problem
--form level error display
message(ERROR_type||'-'||TO_CHAR(message_code)||': '||ERROR_text); message(' ');
--Database level error display
if DBMS_ERROR_TEXT is not null then
message(DBMS_ERROR_TEXT );message(' ');
end if ; | unknown | |
d5464 | train | Edited after your clarification:
Change this in your HTML:
<div class="share-icons slide">
And this in your SCSS:
&:hover .slide {
// assign animation class to the share-icons class
animation: slide 2s linear;
@keyframes slide {
from {
transform: translateY(0px);
}
to {
transform: translateY(100px);
}
}
}
And then adjust the animation as needed.
And here's a fork in action:
http://codepen.io/denmch/pen/WxrLQZ | unknown | |
d5465 | train | I think you want
else {
previous_player->link=selected_player;
selected_player->link=currPtr;
}
to be
else {
prevPtr->link=selected_player;
selected_player->link=currPtr;
}
A: If this is not a homework and you are not trying to learn the intrinsics of algorithms on a linked list then you should
*
*use the standard library
*avoid using pointers when you don't need pointers
That said, to answer your question:
struct record {
std::string name;
int games_played;
int score;
};
bool lower_score(const record& a, const record& b)
{
return a.score < b.score;
}
// ...
std::vector<record> records = the_records();
std::sort(records.begin(), records.end(), lower_score);
I'm not sure why you want to use a list; if you have no specific concrete reason then you should probably use a vector. Otherwise, std::list has a sort() member:
std::list<record> records = no_no_i_meant_those_records();
records.sort(lower_score); | unknown | |
d5466 | train | You could try to set caret position manually when appending/removing % mark, using those two functions (those are pretty generic and should work for every browser if you need setting caret positions for all browsers some other time):
function getCaretPosition(element) {
var caretPos = 0;
if (element.type === 'text' || element.type === 'tel') {
if (document.selection) { // IE Support
element.focus();
var Sel = document.selection.createRange();
Sel.moveStart('character', -element.value.length);
caretPos = Sel.text.length;
} else if (element.selectionStart || element.selectionStart === '0') {// Firefox support
caretPos = element.selectionStart;
}
}
return caretPos;
}
function setCaretPosition(element, position) {
if (element.type === 'text' || element.type === 'tel') {
if (element.setSelectionRange) {
element.focus();
element.setSelectionRange(position, position);
} else if (element.createTextRange) {
var range = element.createTextRange();
range.collapse(true);
range.moveEnd('character', position);
range.moveStart('character', position);
range.select();
}
}
}
And call them only when using IE11 :) Also, if you want, you could make those functions more specific, removing parts for FF :)
A: This issue can be solved by:
*
*getting a reference to the input element
*adding an onfocus event handler
Then setting the selection range in the onfocus handler to the end of the input value, like so:
const onFocus = (el) => {
const { value } = el.value
el.setSelectionRange(value.length, value.length);
}
<input type='text' onfocus='onFocus(this)' />
If you are using ReactJS, here is that solution. | unknown | |
d5467 | train | I thought if we have an element like:
<option value="1" selected>1: Lorem ipsum</option>
if selected is there it means always option selected true as it is the same as:
<option value="1" selected="selected">1: Lorem ipsum</option>
...
but this seems not to be like so. Could anyone shed some light on this for me?
You're correct about how boolean attributes work, just not about what the selected boolean attribute represents. :-)
The selected attribute represents the default selected state, not the current selected state. It's like an input's value attribute in that way; the default (used in case of form reset, for instance), not the current value.
Just as the current value of an input is not represented in the DOM, similarly the current value of a option's selectedness is not represented in the DOM.
A: Different browser may treat this attribute differently. According to the MSDN documentation (for Internet Explorer):
To select an item in HTML, it is not
necessary to set the value of the
SELECTED attribute to true. The mere
presence of the SELECTED attribute set
its value to true.
In firefox and Safari this does work:
<option selected='false' />
From what I can tell by looking at the official WC3 standard for HTML5, the supported case is only:
<option selected='selected' />
You will either need to selectively emit the attribute, or use selected='false' or use javascript to control which item is initially selected. | unknown | |
d5468 | train | You can use Text_to_column tool in DATA tab of the excel sheet..
When the dialog box appears
*
*select the Fixed Width radio button and click next
*Then select the range you want to split..
*Then next and Finish..
You will get the required output.. | unknown | |
d5469 | train | You must wrap the fields with a new class
@XmlRootElement(name="flowPanel")
public class Image implements Serializable {
public static class Label {
@XmlAttribute()
public String text;
public Label(){}
public Label(String text) {
this.text = text;
}
}
@XmlElement(name="label")
public Label name;
@XmlElement(name="label")
public Label description;
}
A: Using Standard JAXB APIs
In order to get the same element to appear multiple times in an XML document you are going to need a List property. Note in the example below label will have a property mapped to the text attribute.
@XmlRootElement(name="flowPanel")
@XmlAccessorType(XmlAccessType.FIELD)
public class Image implements Serializable {
@XmlElement(name="label").
private List<Label> labels;
}
@XmlPath extension in EclipseLink JAXB (MOXy)
If you are using EclipseLink MOXy as your JAXB (JSR-222) provider then you could leverage the @XmlPath extension we added for this use case.
@XmlRootElement(name="flowPane")
public class Image implements Serializable {
@XmlPath("label[1]/@text")
public String name;
@XmlPath("label[1]/@text")
public String description;
}
For More Information
I have written more about this on my blog:
*
*http://blog.bdoughan.com/2010/07/xpath-based-mapping.html | unknown | |
d5470 | train | I would not call it "bad practice" even though it can cause ugly results when your text wraps over multiple lines. Just using it for "alignment-hacks" like you said should be no problem at all.
Edit:
Maybe my Answer promised too much. Be careful with the line-height property beacause as I mentioned it may cause ugly results on multi-line text. If you want to keep your website responsive margins on your paragraphs (positive or negative) are clearly the better solution.
A: Good practise in this area is the well readable text. Nothing else matters. The text should be easy to read. | unknown | |
d5471 | train | If you can select the newly created element from the DOM, this method will work nicely (needs jQuery). You will simply show the elements you created and then scroll the browser into view.
function scrollTo(element){
$("html, body").animate({
scrollTop: $(element).position().top
});
} | unknown | |
d5472 | train | The select event was renamed to activate in 1.9: http://api.jqueryui.com/tabs/#event-activate
There's documentation for 1.8 as well, including the select event: http://api.jqueryui.com/1.8/tabs/#event-select
The select event was deprecated, so it still works in 1.9, unless you set $.uiBackCompat = false. More info in the 1.9 upgrade guide: http://jqueryui.com/upgrade-guide/1.9/#preparing-for-jquery-ui-1-10
A: Before jQueryUI changed their site a few months ago, the documentation existed. You can also use:
$("#tabs").tabs({
select:function(eventt,ui){
alert("The tab at index " + ui.index + " was selected");
}
});
If you want to see more detail as to what is available in the ui object ( or tab in your code), log it to a console. | unknown | |
d5473 | train | Just make the first time result optional:
/^\((\d+)\)\s(.*?)\s{2,}(.+?) (\d+)-(\d+) (?:\(.*?\) )?(.+?)\s{2,}.*UTC-(\d+)/
# ^^^________^^
A: A set of progressive matches would probably turn out more legible / maintainable, but at least by adding the /x modifier we can allow for insignificant whitespace, which permits formatting of the regex to make it easier to read and understand.
Here's one way to do it:
my @targets = (
q{(1) Thu Jun/12 17:00 Brazil 3-1 (1-1) Croatia @ Arena de São Paulo, São Paulo (UTC-3)},
q{(1) Thu Jun/12 17:00 Brazil 3-1 Croatia @ Arena de São Paulo, São Paulo (UTC-3)}
);
foreach my $target ( @targets ) {
print "($1)($2)($3)($4)($5)($6)($7)\n"
if $target =~ m/
^\(([^)]+)\)\s+ # 1
(\w{3}\s\w{3}\/\d{1,2}\s\d{2}:\d{2})\s+ # Date and Time
(\D+?)\s+ # Team A
(\d+)-(\d+)\s+ # Score A - B
(?:\([^)]+\)\s+)? # Optional
(.+?)\s+@ # Team B
.+\(UTC-(\d+)\)$ # TZ
/x;
}
This produces the following output:
(1)(Thu Jun/12 17:00)(Brazil)(3)(1)(Croatia)(3)
(1)(Thu Jun/12 17:00)(Brazil)(3)(1)(Croatia)(3) | unknown | |
d5474 | train | This is the browser's standard header and footer, and cannot be controlled by CSS.
A: Sadly, you can't. Those headers and footers are added by the browser. You can usually remove them in the browser's "Print" settings, but there's no way to get rid of them globally for all users. | unknown | |
d5475 | train | This should do it:
$variable = 'of course it is unnecessary [http://google.com],
but it is simple["very simple"], and this simple question clearly
needs a simple, understandable answer [(where is it?)] in plain English';
preg_match_all("/(\[(.*?)\])/", $variable, $matches);
$first = reset($matches[2]);
$last = end($matches[2]);
$all = $matches[2];
# To remove all matches
foreach($matches[1] as $key => $value) {
$variable = str_replace($value, '', $variable);
}
# To remove first match
$variable = str_replace($first, '', $variable);
# To remove last match
$variable = str_replace($last, '', $variable);
Note that if you use str_replace to replace the tags, all similar occurences of the tags will be removed if such exist, not just the first. | unknown | |
d5476 | train | I already successfully setup nx + angular + firebase. (ps. with only one app in nx monorepo)
details and pictures can be found here:
https://blog-host-d6b29.web.app/2022/11/27/nx-angular-fire.html
I suggest you also try to setup a new nx + angular workspace, walk through my steps and see how it works.
--
to work with angular & firebase, I suggest using The official Angular library for Firebase "@angular/fire".
https://github.com/angular/angularfire | unknown | |
d5477 | train | ( sample record )
1, John, USA, abc222abc, ... other columns
Table B: ( sample record )
1, John, USA, abc222abc
Now lets say John changes his country location to UK, then corresponding entry in TABLE A looks like this
Table A: ( sample record )
1, John, UK, checkSumChanged, ... other columns
Now i need to update my table B accordingly, so that instead of location of John as USA it should have it as UK.
Column checksum is helpful here, since its value changes in Table A if any column changes.
This is the part i am stuck at. Not able to update just "CHANGED" rows from Table A to Table B. I have following query below. It is updating all rows instead of just the changed rows.
Here is the query.
UPDATE tableB
SET
tableB.cust_name = tableA.cust_name,
tableB.cust_location = tableA.cust_location,
tableB.check_sum = tableA.check_sum
FROM
tableA inner join tableB
on tableA.cust_id = tableB.cust_id
and tableA.check_sum != tableB.check_sum
Any ideas or suggestion how can i correct my query to just update the changed record.
Thanks in advance!!!
A: Do it without a join:
update B
SET cust_name = a.cust_name, checksum = a.checksum, cust_location = a.cust_location
FROM a
WHERE a.custid = b.custid AND a.checksum != b.checksum; | unknown | |
d5478 | train | Your JOINs got a bit scrambled. Try this below, and see if that fixes the syntax error.
Always try to get your JOINs to follow the format INNER JOIN [Table2] ON [Table2].[Field1] = [Table1].[Field1]
FROM tblClients
INNER JOIN tblAppointments ON tblClients.ClientId = tblAppointments.ClientId
INNER JOIN tblPointOfSale ON tblPointOfSale.AppointmentId = tblAppointments.AppointmentId
AND tblPointOfSale.ClientId = tblClients.ClientId
INNER JOIN tblInvoices ON tblPointOfSale.SaleId = tblInvoices.SaleId
INNER JOIN tblProductsUsed ON tblProductsUsed.SaleId = tblPointOfSale.SaleId
INNER JOIN tblProducts ON tblProductsUsed.ProductId = tblProducts.ProductId
INNER JOIN tblServicesRendered ON tblServicesRendered.AppointmentId = tblAppointments.AppointmentId
INNER JOIN tblServices ON tblServicesRendered.ServiceId = tblServices.ServiceId
A: I just copy and pasted your code into this website - http://poorsql.com/
and it hightlighted the error for you (you're missing AND in the joins).
As @DBro said - get in the habit of putting your JOINs on the new line and format it a little differently, and you'll have far less trouble. | unknown | |
d5479 | train | You can simply concatenate the two lists with the ++ operator:
val res: RDD[List[String]] = rdd1.join(rdd2)
.map { case (_, (list1, list2)) => list1 ++ list2 }
Probably a better approach that would avoid to carry List[String] around that may be very big would be to explode the RDD into smaller (key value) pairs, concatenate them and then do a groupByKey:
val flatten1: RDD[(String, String)] = rdd1.flatMapValues(identity)
val flatten2: RDD[(String, String)] = rdd2.flatMapValues(identity)
val res: RDD[Iterable[String]] = (flatten1 ++ flatten2).groupByKey.values | unknown | |
d5480 | train | Verify that the popScene method isn't run twice, perhaps by the user quickly tapping the menu item (or a bug).
That would pop both the current and the HelloWorld scene, leaving the director with no scene to display. It would also explain the director deallocating.
You can prevent this by first checking whether the director's runningScene is identical to this (as in: the SecondScene instance), and only then call popScene.
A: I have same problem too, but I solved,
I think you may have removed all children from the scene,
check you onExit or destructor to see if any release/remove options available in these two functions.
if the scene has no children, it would be black. | unknown | |
d5481 | train | Not sure I understand the question, but looking at what I assume the intent is of the code the following
symmetricKey.CreateDecryptor
Should probably be
symmetricKey.CreateEncryptor
A: Probably because AES is a block cipher with 128 bits per block.. maybe you just need to add a padding such that length % 128 == 0.
(I'm not a C# developer but it can happen that an implementation doesn't care about adding padding by itself)
Just a hint: try if it works with 256 bits | unknown | |
d5482 | train | You have to make parallel request using socket_select() and non-blocking sockets or forks, because you are spending a lot of time in waiting for the response. Additionally, it may be better to use low-level functions like socket_read() or similar to control connection and data transmission better. | unknown | |
d5483 | train | You cannot obtain this value if your code is outside of the function, unless this function stores the object in the defaults variable somewhere where it can be reached through a global variable. This is due to the way that JavaScript functions work -- code external to the function has no access to that function's local variables. (This is not very different from other programming languages.)
If your goal is only to change the value rather than obtain the default value, most jQuery plugins will allow you to pass in an object whose properties will override the default settings. Based on the name of the plugin, you could do so like this:
$("#something").simplyScroll({
auto: false
});
A: In my opinion, there are 2 ways that allows you to access to defaults object outside this function scope
1. In function scope, defaults object will be assigned to a propery of global object (= window)
...
// In the function scope
window.defobject = defaults;
...
For example:
(function($, window, undefined) {
var defaults = {
foo : "bar"
};
window.defobject = defaults;
})(jQuery, this);
console.print(defobject); // This is valid with no error
2. The function finally return this object as output
...
// In the function scope
return defaults;
For example:
var defobject = (function($, window, undefined) {
var defaults = {
foo : "bar"
};
return defaults;
})(jQuery, this);
console.print(defobject); // This is also valid with no error | unknown | |
d5484 | train | I'm using a simplified version of your idea with a UIScrollView & 3 UILabel instances.
You can easily adapt this to be UITableView & 3 UIView instances.
Idea
*
*UIScrollView & 3 UILabel instances have a common superview. In this case it's UIViewController.view.
*UIScrollView is laid out to be full screen (edge-to-edge) and extends below these 3 UILabel instances.
*UIScrollView has contentInset.top = height_of_three_labels so it's content starts below these other instances.
*Whenever UIScrollView.contentOffset changes, we shift frame.origin.y for these 3 instances to provide the needed effect.
UI Setup
import UIKit
class ViewController: UIViewController {
let tileHeight: CGFloat = 60
let view1 = UILabel()
let view2 = UILabel()
let view3 = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
let bounds = self.view.bounds
let scrollView = UIScrollView(frame: bounds)
scrollView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
scrollView.delegate = self
scrollView.alwaysBounceVertical = true
self.view.addSubview(scrollView)
view1.frame = CGRect(x: 0, y: 2*tileHeight, width: bounds.width, height: tileHeight)
configureLabel(view1, text: "1", backgroundColor: .red)
view2.frame = CGRect(x: 0, y: tileHeight, width: bounds.width, height: tileHeight)
configureLabel(view2, text: "2", backgroundColor: .blue)
view3.frame = CGRect(x: 0, y: 0, width: bounds.width, height: tileHeight)
configureLabel(view3, text: "3", backgroundColor: .green)
scrollView.contentInset = UIEdgeInsets(top: 3*tileHeight, left: 0, bottom: 0, right: 0)
// 3 is between 2 and 1, 1 is at the top, order is important here
self.view.addSubview(view2)
self.view.addSubview(view3)
self.view.addSubview(view1)
}
private func configureLabel(_ label: UILabel, text: String, backgroundColor: UIColor) {
label.text = text
label.textColor = .white
label.font = .boldSystemFont(ofSize: 34)
label.textAlignment = .center
label.backgroundColor = backgroundColor
}
}
Scroll Management
extension ViewController: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offset = scrollView.adjustedContentInset.top + scrollView.contentOffset.y
print(offset)
if offset > 0 {
view3.frame.origin.y = (offset > tileHeight) ? (tileHeight - offset) : 0
view2.frame.origin.y = tileHeight - offset
view1.frame.origin.y = 2*tileHeight - offset
}
else {
view3.frame.origin.y = 0
view2.frame.origin.y = tileHeight
view1.frame.origin.y = 2*tileHeight
}
}
}
Output
A: I think you'll be fighting a losing battle trying to toggle scrolling.
Here's another approach...
*
*add the tableView as a subview of a "container" UIView
*add the three "top" views as subviews
*give the tableView a contentInset.top of the height of the three views plus vertical spacing
*constrain the three "top" views so
*
*3 will stick to the top, until it is pushed up by 1
*2 till slide under 3 when 1 pushes it up
*update the top constraint for 1 when the tableView scrolls
You can try it with this example code (no @IBOutlet connections needed):
class ExampleViewController: UIViewController, UIScrollViewDelegate {
let tableView: UITableView = {
let v = UITableView()
v.translatesAutoresizingMaskIntoConstraints = false
v.separatorInset = .zero
return v
}()
let view1: UILabel = {
let v = UILabel()
v.translatesAutoresizingMaskIntoConstraints = false
v.textAlignment = .center
v.backgroundColor = .systemRed
v.text = "1"
return v
}()
let view2: UILabel = {
let v = UILabel()
v.translatesAutoresizingMaskIntoConstraints = false
v.textAlignment = .center
v.backgroundColor = .systemGreen
v.text = "2"
return v
}()
let view3: UILabel = {
let v = UILabel()
v.translatesAutoresizingMaskIntoConstraints = false
v.textAlignment = .center
v.backgroundColor = .systemBlue
v.text = "3"
return v
}()
// this will hold the tableView and the
// three other views
let containerView: UIView = {
let v = UIView()
v.translatesAutoresizingMaskIntoConstraints = false
// clip to bounds to prevent the "top" views from showing
// as they are "pushed up" out of bounds
v.clipsToBounds = true
return v
}()
// this constraint constant will be changed
// in scrollViewDidScroll
@IBOutlet var view1TopConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
// add our container view
view.addSubview(containerView)
// add our tableView and three "top" views
containerView.addSubview(tableView)
containerView.addSubview(view2)
containerView.addSubview(view3)
containerView.addSubview(view1)
for v in [view1, view2, view3] {
// all three "top" views should be
// equal width to tableView
// horizontally centered to tableView
// 40-pts tall
NSLayoutConstraint.activate([
v.widthAnchor.constraint(equalTo: tableView.widthAnchor),
v.centerXAnchor.constraint(equalTo: tableView.centerXAnchor),
v.heightAnchor.constraint(equalToConstant: 40.0),
])
}
let g = view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
// constrain container view with 20-pts "padding"
containerView.topAnchor.constraint(equalTo: g.topAnchor, constant: 20.0),
containerView.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0),
containerView.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -20.0),
containerView.bottomAnchor.constraint(equalTo: g.bottomAnchor, constant: -20.0),
// constrain all 4 sides of tableView ot container view
tableView.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 0.0),
tableView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 0.0),
tableView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: 0.0),
tableView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: 0.0),
])
// view3 should stick to the top of the table,
// unless it's being pushed up by view1
let v3Top = view3.topAnchor.constraint(equalTo: tableView.topAnchor)
v3Top.priority = .defaultHigh + 1
// view2 should stick to the bottom of view3,
// unless it's being pushed up by view1
let v2Top = view2.topAnchor.constraint(equalTo: view3.bottomAnchor, constant: 4.0)
v2Top.priority = .defaultHigh
// view1 should ALWAYS be 4-pts from bottom of view2
let v1TopA = view1.topAnchor.constraint(equalTo: view2.bottomAnchor, constant: 4.0)
v1TopA.priority = .required
// view1 should ALWAYS be greater-than-or-equal 4-pts from bottom of view3
let v1TopB = view1.topAnchor.constraint(greaterThanOrEqualTo: view3.bottomAnchor, constant: 4.0)
v1TopB.priority = .required
// view1 top should ALWAYS be greater-than-or-equal top of tableView
let v1TopC = view1.topAnchor.constraint(greaterThanOrEqualTo: tableView.topAnchor)
v1TopC.priority = .required
// 88-pts is 40-pts for view3 and view2 plus 4-pts vertical spacing
// view1 top should NEVER be more-than 88-pts from top of tableView
let v1TopD = view1.topAnchor.constraint(lessThanOrEqualTo: tableView.topAnchor, constant: 88.0)
v1TopD.priority = .required
// view1 top will start at 88-pts from top of tableView
view1TopConstraint = view1.topAnchor.constraint(equalTo: tableView.topAnchor, constant: 88.0)
view1TopConstraint.priority = .defaultHigh + 2
// activate those constraints
NSLayoutConstraint.activate([
v3Top,
v2Top,
v1TopA,
v1TopB,
v1TopC,
v1TopD,
view1TopConstraint,
])
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
tableView.dataSource = self
tableView.delegate = self
// top inset is
// three 40-pt tall views
// plus 4-pts vertical spacing between each
// and 4-pts vertical spacing below view1
tableView.contentInset.top = 132
tableView.contentOffset.y = -132
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
// we're getting called when the tableView scrolls
// invert the contentOffset y
let y = -scrollView.contentOffset.y
// subtract 44-pts (40-pt tall view plus 4-pts vertical spacing)
view1TopConstraint.constant = y - 44.0
}
}
extension ExampleViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 30
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let c = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
c.textLabel?.text = "Row \(indexPath.row)"
return c
}
}
Here's how it looks to start:
then, after scrolling up just a bit (2 is sliding under 3):
scrolling a bit more (1 is pushing 3 up and out of view):
and then table scrolling while 1 remains at the top: | unknown | |
d5485 | train | You are seeking for some recursion here:
def is_happy(items):
return all(item.state in ['happy', 'cheerful'] for item in items) and all(is_happy(item.childs) for item in items)
As @tobias_k pointed out this should be quicker since it iterates only once on items:
def is_happy(items):
return all(item.state in ['happy', 'cheerful'] and is_happy(item.childs) for item in items)
It is at least more readable.
In the case you only have two layers of objects a simple for might do the trick too.
def is_happy(items):
happy_children = True
for item in items:
if any(child.state not in ['happy', 'cheerful'] for child in item):
happy_children = False
break
return all(item.state in ['happy', 'cheerful'] for item in items) and happy_children
A: I guess this would be the right way:
if all(item.state in ['happy', 'cheerful'] and all(c.state in ['happy', 'cheerful'] for c in item.childs) for item in items):
pass
A: First step: flatten the list of items:
def flatten(items):
for item in items:
yield item
for child in getattr(item, 'children', ()):
yield child
Or using Python 3.4+:
def flatten(items):
for item in items:
yield item
yield from getattr(item, 'children', ())
And now you can iterate through flattened items using all(..) or some other way:
is_happy = lambda item: getattr(item, 'state') in ('happy', 'cheerful')
are_happy = lambda items: all(map(is_happy, flatten(items)))
A: Recursion is your friend here
def happy(x):
return (x.state in ('happy', 'cheerful') and
all(happy(xc) for xc in x.children))
A: This is probably best done manually.
def valid(item):
return item.state in ['happy', 'cheerful']
for item in items:
if not (valid(item) and all(valid(child) for child in item)):
break
else:
# success
Changing the generator expression to work with this is possible but makes it a bit hacky.
if all(child.state in ['happy', 'cheerful'] for item in items for child in item+[item]):
pass
So to answer your question, yes its possible to nest the all function and thats how you could do it if you really wanted. | unknown | |
d5486 | train | function toggleStep(element) {
if (element.value >= 10) { element.step = 10; }
else { element.step = 2; }
}
/**
* Sniffs for Older Edge or IE,
* more info here:
* https://stackoverflow.com/q/31721250/3528132
*/
function isOlderEdgeOrIE() {
return (
window.navigator.userAgent.indexOf("MSIE ") > -1 ||
!!navigator.userAgent.match(/Trident.*rv\:11\./) ||
window.navigator.userAgent.indexOf("Edge") > -1
);
}
function valueTotalRatio(value, min, max) {
return ((value - min) / (max - min)).toFixed(2);
}
function getLinearGradientCSS(ratio, leftColor, rightColor) {
return [
'-webkit-gradient(',
'linear, ',
'left top, ',
'right top, ',
'color-stop(' + ratio + ', ' + leftColor + '), ',
'color-stop(' + ratio + ', ' + rightColor + ')',
')'
].join('');
}
function updateRangeEl(rangeEl) {
var ratio = valueTotalRatio(rangeEl.value, rangeEl.min, rangeEl.max);
rangeEl.style.backgroundImage = getLinearGradientCSS(ratio, '#00FF00', '#c5c5c5');
}
function initRangeEl() {
var rangeEl = document.querySelector('input[type=range]');
var textEl = document.querySelector('input[type=text]');
/**
* IE/Older Edge FIX
* On IE/Older Edge the height of the <input type="range" />
* is the whole element as oposed to Chrome/Moz
* where the height is applied to the track.
*
*/
if (isOlderEdgeOrIE()) {
rangeEl.style.height = "20px";
// IE 11/10 fires change instead of input
// https://stackoverflow.com/a/50887531/3528132
rangeEl.addEventListener("change", function(e) {
textEl.value = e.target.value;
});
rangeEl.addEventListener("input", function(e) {
textEl.value = e.target.value;
});
} else {
updateRangeEl(rangeEl);
rangeEl.addEventListener("input", function(e) {
updateRangeEl(e.target);
textEl.value = e.target.value;
});
}
}
initRangeEl();
.slidecontainer {
width: 500px;
margin-left:15px;
}
input[type="range"] {
-webkit-appearance: none;
-moz-appearance: none;
width:100%;
height: 50px;
padding: 0;
border: solid 2px #000000;
border-radius: 8px;
outline: none;
cursor: pointer;
}
datalist {
display: flex;
margin-left: 2px;
margin-top: -50px;
}
datalist option {
flex-basis: 10%;
border-left: 1px solid #000;
}
datalist option:nth-child(-n+5) {
flex-basis: 2%;
}
datalist option:last-child {
display: none;
}
/*Chrome thumb*/
input[type="range"]::-webkit-slider-thumb {
-webkit-appearance: none;
-moz-appearance: none;
-webkit-border-radius: 5px;
/*16x16px adjusted to be same as 14x14px on moz*/
height: 45px;
width: 45px;
border-radius: 5px;
background: #e7e7e7;
border: 2px solid #000000;
opacity: 0.4;
cursor: pointer;
border-radius: 8px;
}
/*Mozilla thumb*/
input[type="range"]::-moz-range-thumb {
-webkit-appearance: none;
-moz-appearance: none;
-moz-border-radius: 5px;
height: 14px;
width: 14px;
border-radius: 5px;
background: #e7e7e7;
border: 1px solid #c5c5c5;
}
/*IE & Edge input*/
input[type=range]::-ms-track {
width: 300px;
height: 6px;
/*remove bg colour from the track, we'll use ms-fill-lower and ms-fill-upper instead */
background: transparent;
/*leave room for the larger thumb to overflow with a transparent border */
border-color: transparent;
border-width: 2px 0;
/*remove default tick marks*/
color: transparent;
margin-left:15px;
}
/*IE & Edge thumb*/
input[type=range]::-ms-thumb {
height: 14px;
width: 14px;
border-radius: 5px;
background: #e7e7e7;
border: 1px solid #c5c5c5;
}
/*IE & Edge left side*/
input[type=range]::-ms-fill-lower {
background: #000000;
border-radius: 2px;
margin-left:15px;
}
/*IE & Edge right side*/
input[type=range]::-ms-fill-upper {
background: #000000;
border-radius: 2px;
}
/*IE disable tooltip*/
input[type=range]::-ms-tooltip {
display: none;
}
input[type="text"] {
border: none;
}
.sliderticks {
display: flex;
justify-content: space-between;
padding: 0 50px;
}
.sliderticks p {
position: relative;
display: flex;
justify-content: center;
text-align: center;
width: 1px;
background: #D3D3D3;
height: 10px;
line-height: 40px;
margin: 0 0 20px 0;
}
<h1>Custom Range Slider</h1>
<p>Drag the slider to display the current value.</p>
<div class="slidecontainer">
<input type="range" value="10" min="0" max="100" oninput="toggleStep(this)" list="sliderticks" />
<div class="datalist">
<datalist id="sliderticks">
<option>0</option>
<option>2</option>
<option>4</option>
<option>6</option>
<option>8</option>
<option>10</option>
<option>20</option>
<option>30</option>
<option>40</option>
<option>50</option>
<option>60</option>
<option>70</option>
<option>80</option>
<option>90</option>
<option>100</option>
</datalist>
</div>
</div>
A: Hope the code below solves your needs:
document.querySelectorAll('.range input[type="range"]').forEach((range) => {
range.tickmarks = [...range.list.options].map((el) => parseFloat(el.value));
range.list.insertAdjacentHTML('afterend', `<div class="range-value"></div>`);
range.max = parseFloat(range.tickmarks[range.tickmarks.length - 1]);
let q = (range.clientWidth - 40) / range.max;
range.addEventListener('input', function(ev) {
if (this.hasAttribute('ticks-only')) {
this.value = range.tickmarks.map((x) => x).sort((x, y) => Math.abs(x - this.value) - Math.abs(y - this.value))[0];
}
this.parentElement.style.backgroundSize = `${(this.value * range.clientWidth) / range.max}px 100%, 100% 100%`;
this.list.nextElementSibling.textContent = this.value;
this.list.nextElementSibling.style.left = `${20 + this.value * q}px`;
});
range.tickmarks.forEach((el, i) => {
range.list.options[i].label = el % 10 ? ' ' : el;
range.list.options[i].style.left = 20 + el * q + 'px';
});
range.dispatchEvent(new Event('input', {bubbles: true}));
});
.range {
position: relative;
height: 52px; width: 500px;
border-radius: 0.125em;
overflow: hidden;
font: 16px/1em sans-serif;
background-image: linear-gradient(to right, #7bad23, #39594c), linear-gradient(to bottom, #84929d, #46576d);
background-size: 0 100%, 100% 100%;
background-repeat: no-repeat;
box-shadow: 0 0 0 0.125em #7f8c97, 0.0625em 0.125em 0.3125em 0em #93a2bd, -0.125em -0.1875em 0.3125em 0em #0e1116, inset 0 0 1.25em -0.3125em #0e1116;
}
datalist {
position: relative;
display: block;
height: 100%; width: 100%;
pointer-events: none;
}
.range datalist option {
position: absolute !important;
display: grid;
place-items: center;
height: 100%;
padding: 0;
transform: translatex(-50%);
font: bold 12px/1em monospace !important;
text-shadow: 1px 0 0.16666667em #fff5;
}
.range datalist option::before,
.range datalist option::after {
content: "";
position: absolute;
left: 50%;
height: 100%; width: 0;
box-shadow: 0 0 0 0.08333333em #0008;
}
.range datalist option::before { bottom: calc(50% + 1em); }
.range datalist option::after { top: calc(50% + 1em); }
input[type="range"] {
appearance: none;
position: absolute;
top: 0; left: 0; z-index: 1;
margin: 0;
height: 100%; width: 100%;
box-sizing: border-box;
font: inherit;
background-color: transparent;
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
appearance: none;
display: block;
width: 2.5em; height: 2.5em;
border: none;
border-radius: 0.75em;
background-color: #99c7;
box-shadow: 0 0 0.125em 0 #282850dd, inset 0 0 0.125em 0.125em #282850dd;
transition: background-color 0.5s ease-out 0.5s;
}
input[type="range"]:active::-webkit-slider-thumb {
background-color: #fff8;
transition: background-color 0.5s ease-out;
}
.range-value {
position: absolute;
top: 0; left: 0; z-index: 2;
display: grid;
place-items: center;
height: 100%;
transform: translatex(-50%);
font: bold 12px/1em monospace !important;
text-shadow: 0 0 0.16666667em #fff;
opacity: 0;
pointer-events: none;
transition: opacity 1s ease-in;
}
input[type="range"]:focus-visible~.range-value,
input[type="range"]:active~.range-value,
input[type="range"]:hover~.range-value {
opacity: 1;
transition: opacity 0.5s ease-out;
}
body { margin: 0; height: 100vh; background-color: #42516c; display: flex; flex-flow: column nowrap; justify-content: center; align-items: center; }
<div class="range">
<input type="range" list="high">
<datalist id="high">
<option value="0">
<option value="2">
<option value="4">
<option value="6">
<option value="8">
<option value="10">
<option value="20">
<option value="30">
<option value="40">
<option value="50">
<option value="60">
<option value="70">
<option value="100">
</datalist>
</div>
<h3>With "ticks-only" attribute</h3>
<div class="range">
<input type="range" list="bass" ticks-only>
<datalist id="bass">
<option value="0">
<option value="10">
<option value="15">
<option value="20">
<option value="30">
<option value="40">
<option value="50">
<option value="60">
<option value="70">
<option value="72">
<option value="74">
<option value="76">
<option value="78">
<option value="80">
<option value="100">
<option value="175">
<option value="200">
</datalist>
</div>
Note! This code only works for "webkit" (tested in Chrome). Firefox does not work correctly with the "position" property when parent and child elements are set to "absolute". | unknown | |
d5487 | train | Demo Fiddle
How about the following:
div.cabinet{
border-right:5px solid #e7e8e1;
white-space:nowrap;
display:inline-block;
padding-right:5px;
}
Use inline-block to make the div fit the content, then add padding. If you only wish the child ul to do this, simply apply those properties to div.cabinet ul instead (as well as the border).
A: Add a Padding to your UL or LI tag,
ul{padding:5px;} /** Will be applicable to all li's or you can also give it seperately **/
you can change that 5px value, but it will be enough ! | unknown | |
d5488 | train | Here's a recursive example in JavaScript that seems to answer the requirements:
function getNextM(m, n){
if (n == 1)
return 1.5;
if (n == 2)
return 2;
if (n == 6)
return 2.5;
if (n == 10)
return 3;
return m;
}
function g(A, t, i, sum, m, comb){
if (sum * m == t)
return [comb];
if (sum * m > t || i == A.length)
return [];
let n = comb.length;
let result = g(A, t, i + 1, sum, m, comb);
const max = Math.ceil((t - sum) / A[i]);
let _comb = comb;
for (let j=1; j<=max; j++){
_comb = _comb.slice().concat(A[i]);
sum = sum + A[i];
m = getNextM(m, n);
n = n + 1;
result = result.concat(g(
A, t, i + 1, sum, m, _comb));
}
return result;
}
function f(A, t){
return g(A, t, 0, 0, 1, []);
}
var A = [25, 50, 100, 200, 450, 700, 1100, 1800, 2300, 2900, 3900, 5000, 5900, 7200, 8400];
var t = 300;
console.log(JSON.stringify(f(A, t)));
A: I wrote a small script in Python3 that may solve this problem.
multiply_factor = [0,1,1.5,2,2,2,2,2.5,2.5,2.5,2.5,3]
def get_multiply_factor(x):
if x< len(multiply_factor):
return multiply_factor[x]
else:
return multiply_factor[-1]
numbers = [25, 50, 100, 200, 450, 700, 1100, 1800, 2300, 2900, 3900, 5000, 5900, 7200, 8400]
count_of_numbers = len(numbers)
# dp[Count_of_Numbers]
dp = [[] for j in range(count_of_numbers+1)]
#Stores multiplying_factor * sum of numbers for each unique Count, See further
sum_found =[set() for j in range(count_of_numbers+1)]
# Stores Results in Unordered_Map for answering Queries
master_record={}
#Initializing Memoization Array
for num in numbers:
dp[1].append(([num],num*get_multiply_factor(1)))
for count in range(2,count_of_numbers+1): # Count of Numbers
for num in numbers:
for previous_val in dp[count-1]:
old_factor = get_multiply_factor(count-1) #Old Factor for Count Of Numbers = count-1
new_factor = get_multiply_factor(count) #New Factor for Count Of Numbers = count
# Multiplying Factor does not change
if old_factor==new_factor:
# Scale Current Number and add
new_sum = num*new_factor+previous_val[1]
else:
#Otherwise, We rescale the entire sum
new_sum = (num+previous_val[1]//old_factor)*new_factor
# Check if NEW SUM has already been found for this Count of Numbers
if new_sum not in sum_found[count]:
# Add to current Count Array
dp[count].append(([num]+previous_val[0],new_sum))
# Mark New Sum as Found for Count Of Numbers = count
sum_found[count].add(new_sum)
if new_sum not in master_record:
# Store Seected Numbers in Master Record for Answering Queries
master_record[new_sum] = dp[count][-1][0]
# for i in dp:
# print(i)
print(master_record[1300])
print(master_record[300])
print(master_record[2300])
print(master_record[7950])
print(master_record[350700.0])
Output :-
[100, 100, 450]
[100, 100]
[25, 25, 1100]
[25, 50, 3900]
[1800, 5900, 8400, 8400, 8400, 8400, 8400, 8400, 8400, 8400, 8400, 8400, 8400, 8400, 8400]
[Finished in 0.3s]
My Algo in a nutshell.
Iterate over Count[2, Limit], I've considered limit = Number of Elements
Iterate over List of Numbers
Iterate over Sums found for previous count.
Calculate New Sum,
If it does not exist for current count, update.
I am assuming that the number of queries will be large so that memorization pays off. The upper limit for count may break my code as the possibilities may grow exponentially. | unknown | |
d5489 | train | Some issues:
*
*Spelling of this.hour: should be this.hours
*By calling updateDisplay you don't pass on the expected value for this. It is better to just keep the original name of the method, and use this.updateTimerDisplay.
*Don't convert the 0-prefixed string back to number: you are interested in something to display, so keep the string format.
Without changing too much else in your code, the above corrections make it work:
let timer = {
hours: 0,
minutes: 1,
seconds: 30,
updateTimerDisplay() {
// Use textContent, not innerHTML (that is for HTML content)
document.getElementById('hour').textContent = this.hours; // spelling!
// The function format returns a string, so no need to call String on it:
document.getElementById('minute').textContent = format(this.minutes, 'minute');
document.getElementById('second').textContent = format(this.seconds, 'second');
},
startTimer() {
// Don't read a function reference into a variable, as you'll lose the this-binding
// --------- const { updateTimerDisplay: updateDisplay } = this;
let update = setInterval(_ => {
this.seconds -= 1;
if (this.seconds < 0) {
this.seconds = 59;
this.minutes -= 1;
}
if (this.minutes < 0) {
this.minutes = 59;
this.hours -= 1;
}
// By having `this.` here, you pass that this-reference to the function
this.updateTimerDisplay();
}, 1000);
}
};
timer.updateTimerDisplay();
timer.startTimer();
function format(input, unit) {
// RegExp is overkill here. Just use includes:
if (['minute', 'second'].includes(unit.toLowerCase())) {
// Don't convert with Number: it must be a string:
if (String(input).length === 1) return `0${input}`;
else return String(input);
}
}
<span id="hour"></span>:<span id="minute"></span>:<span id="second"></span> | unknown | |
d5490 | train | These are the correct semantics. Prometheus deals with metrics and metrics don't go away just because they haven't changed in a while. What you should be doing is keeping the gauge up to date.
It sounds like you might want a logs-based monitoring system, such as provided by the ELK stack. | unknown | |
d5491 | train | const [toggleMenu, setToggleMenu] = useState(false);
should be...
const [toggleMenu, setToggleMenu] = React.useState(false);
Worked for me. | unknown | |
d5492 | train | =IF(B1-A1 < 0, 1-(A1-B1),( B1-A1))
Assuming that cell A1 contains start, B1 contains end time.
Let me know, if it helps OR errors.
Time without date is not enough to do the subtraction considering the start can be the night before today.
Are you OK to try VBA?
EDIT: The formula is meaningful within 12 hour limit. I will see if it can be made simpler.
A: Given start time in B5 and end time in C5 this formula will give you the decimal number of hours that fall in the range 19:00 to 04:00
=MOD(C5-B5,1)*24-(C5<B5)*(19-4)-MEDIAN(C5*24,4,19)+MEDIAN(B5*24,4,19)
format result cell as number
A: just substract the two dates to get the difference in days, and multiply by 24 to get the difference in hours
=(B1-A1)*24
this is correct when both B1 and A1 contain a datetime value, but in case your cells contain just a time value, with no day value, and given that the calculation spans the night (there is a day change in between) you need to add one day to the difference:
=IF(B1<A1,1+B1-A1,B1-A1)*24 | unknown | |
d5493 | train | Set stdoutlogEnabled to true and stdoutLogFile to \?\%home%\LogFiles\stdout like below:
If the LogFiles folder is not present Stdoutlog is not written so please create it explicitly.
Set environment variables ASPNETCORE_DETAILEDERRORS = 1 in to see more information around the http 500.0 error and debug it. | unknown | |
d5494 | train | time.sleep() doesn't prevent events from being accepted, it simply prevents them from being processed. Every time you click while your app is sleeping the events are simply added to the queue, and processed when the sleep is done sleeping.
You should almost never call sleep in a GUI. What you should do instead is set the state to disabled, then schedule resetting the state for ten seconds later:
def re_enable(self):
self._their_grid.config(state=NORMAL)
...
self.after(10000, self.re_enable) | unknown | |
d5495 | train | From the callback, you need to pass the value and not the string
setCloudClick(evt) {
this.setState({
value: evt.target.value,
}, function () {
this.props.setCloud(this.state.value); // pass this.state.value here
});
}
However, when you are storing value in store, you need not store it locally. You can dispatch the value like
index.js
setCloudClick(evt) {
this.setState({
value: evt.target.value,
}, function () {
this.props.setCloud(this.state.value);
});
}
render(){
return(
<select onChange={this.setCloudClick} value={this.state.value}>
<option value="zscaler.net">zscaler.net</option>
<option value="zscalerOne.net">zscalerOne.net</option>
<option value="zscaler.net">ZscalerTwo.net</option>
<option value="Zscaler Private Access">Zscaler Private Access</option>
</select>
);
}
container/header/index.js
const changeCloud = () => {
return ('hello');
}
const mapStateToProps = () => ({
cloud: changeCloud(),
menuItems: menuItems,
})
const mapDispatchToProps = (dispatch) => ({
setCloud: (value) => {
dispatch(setCloud(value));
},
})
const Header = connect(
mapStateToProps,
mapDispatchToProps
)(HeaderPresentational); | unknown | |
d5496 | train | Yes you can append a meta tag, but no you can't force reparsing of the html. The browser is going to ignore any changes you make. | unknown | |
d5497 | train | Your browser caches it, You need to add header to force your browser not to force it
A: Make sure that you don't cache the last page before you log out. You could do something like:
response.setHeader("Cache-Control","no-cache,no-store,must-revalidate");
response.setHeader("Pragma","no-cache");
response.setDateHeader("Expires", 0); | unknown | |
d5498 | train | This is caused by ngAnimate. Try to remove it, if you are not using it.
If you don't want to remove ngAnimate, add the following css to your app.
.ng-leave {
display:none !important;
}
For more detailed answer angular ng-if or ng-show responds slow (2second delay?)
A: ng-cloak works using CSS, so you'll need to add this to your styles:
[ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
display: none !important;
}
On a side note, ng-bind (and ng-class for the btn-primary/btn-danger) may be a better solution for this type of problem. You can bind the button's contents to a JS variable or function like so:
<button class="btn drop_shadow"
ng-class="getButtonClass()"
ng-bind="getButtonText()"
ng-click="vm.ingestReady = !vm.ingestReady"></button>
And then, in the button's scope, you'd just have to add the two referenced JS functions (cleaner than putting this logic inline):
$scope.getButtonClass = function() {
return vm.ingestReady ? 'btn-primary' : 'btn-danger';
};
$scope.getButtonText = function() {
return vm.ingestReady ? 'Start Ingest' : 'Cancel Ingest';
}; | unknown | |
d5499 | train | As you see, the DefineLiteral method returns a FieldBuilder (fb1, fb2, fb3). You can use SetCustomAttribute on the FieldBuilder to set an attribute. The linked MSDN article has an example on how to use it. The gist of it though, would be to use a CustomAttributeBuilder to build your attribute, then give it to SetCustomAttribute.
A: Not exactly sure but something like this:
Type myType = typeof(DataContract);
ConstructorInfo myInfo = myType.GetConstructor();
eb.SetCustomAttribute(myInfo); | unknown | |
d5500 | train | Use a for loop or a list comprehension in that case.
latitude = [50.224832, 50.536422, 50.847827, 51.159044, 51.470068]
longitude = [108.873007, 108.989510, 109.107829, 109.228010, 109.350097]
density = [.15,.25,.35,.45,.55]
output = [(latitude[i], longitude[i], density[i]) for i in range(len(latitude))]
print(output)
[(50.224832, 108.873007, 0.15), (50.536422, 108.98951, 0.25), (50.847827, 109.107829, 0.35), (51.159044, 109.22801, 0.45), (51.470068, 109.350097, 0.55)] | unknown |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.