_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d9101 | train | select val_id
,-val_sum as val_sum
,2 as val_type
,val_date
from (select val_id
,val_sum
,val_type
,val_date
,sum (case when val_type = -1 then 1 else -1 end) over
(
partition by val_id,-abs (val_sum)
) as occurrences
,row_number () over
(
partition by val_id,val_sum
order by val_date desc
) as rn
from mytable
) t
where val_type = -1
and rn <= occurrences
and occurrences > 15
;
Execution results (without and occurrences > 15)
+--------+---------+----------+------------+
| val_id | val_sum | val_type | val_date |
+--------+---------+----------+------------+
| 1 | -3 | 2 | 2017-02-17 |
+--------+---------+----------+------------+
| 1 | -6 | 2 | 2017-02-05 |
+--------+---------+----------+------------+ | unknown | |
d9102 | train | To my understanding
stringList.toArray( new String[stringList.size()] ) )
is more efficient. The reason:
The argument is needed to have an actual type (String) for a generic List<String>, where the generic type parameter is erased at run-time.
The argument is used for the resulting array if its size matches the list size.
If the size is 0, the passed array is discarded.
So passing a correct array saves one object creation.
Of course list.size() is called extra. So it might be slower. I doubt it.
Correction
See Arrays of Wisdom of the Ancients.
A correct benchmark shows the inverse: new String[0] being faster.
I just overflew the very interesting analysis, and it seems:
*
*(an extra short lived new String[0] is irrelevant;)
*doing the array copying local in the toArray method allows a different, faster array copy;
*(and then there is the extra call to size.)
Mind, I did not sufficiently thorough read the article; it really is interesting.
Conclusion (counter-intuitively): new T[0] is faster.
Mind that:
*
*code checkers might still think differently and issue a warning;
*this is with warming up: till the hotspot JIT kicks in, it may be the other way around.
A: builder(stringList.toArray(new String[0])) is slightly less efficient since you create an empty array that will be discarded and never used after the method returns. toArray will have to create a new array in order to store the elements of the List.
On the other hand, builder(stringList.toArray(new String[stringList.size()])) passes an array of the required length to the toArray method, and therefore that method will use that array instead of creating a new array.
A: There is a difference and it's mainly outlined by the Alexey Shipilev. Long story short:
toArray(new T[0]) seems faster, safer, and contractually cleaner, and therefore should be the default choice now
A: I thought that c.toArray(new String[c.size()])) is more efficient, because we define here an array with required size.
BUT!!
IntelliJ IDEA has Collection.toArray() inspection, which is on by default. This is description:
There are two styles to convert a collection to an array: either using
a pre-sized array (like c.toArray(new String[c.size()])) or using an
empty array (like c.toArray(new String[0]).
In older Java versions
using pre-sized array was recommended, as the reflection call which is
necessary to create an array of proper size was quite slow. However
since late updates of OpenJDK 6 this call was intrinsified, making the
performance of the empty array version the same and sometimes even
better, compared to the pre-sized version. Also passing pre-sized
array is dangerous for a concurrent or synchronized collection as a
data race is possible between the size and toArray call which may
result in extra nulls at the end of the array, if the collection was
concurrently shrunk during the operation.
This inspection allows to follow the uniform style: either using an
empty array (which is recommended in modern Java) or using a pre-sized
array (which might be faster in older Java versions or non-HotSpot
based JVMs).
So it seems, that after JDK6, we should use c.toArray(new String[0]). My personal opinion, is that it doesn't matter what aporoach to use this time. Only if profiler says that this is a bottle neck, then we should worry about it. | unknown | |
d9103 | train | EDIT:
It looks like the issue is now solved using an external command called brew rmdeps or brew rmtree.
To install and use, issue the following commands:
$ brew tap beeftornado/rmtree
$ brew rmtree <package>
See the above link for more information and discussion.
[EDIT] see the new command brew autoremove in https://stackoverflow.com/a/66719581/160968
Original answer:
It appears that currently, there's no easy way to accomplish this.
However, I filed an issue on Homebrew's GitHub page, and somebody suggested a temporary solution until they add an exclusive command to solve this.
There's an external command called brew leaves which prints all packages that are not dependencies of other packages.
If you do a logical and on the output of brew leaves and brew deps <package>, you might just get a list of the orphaned dependency packages, which you can uninstall manually afterwards. Combine this with xargs and you'll get what you need, I guess (untested, don't count on this).
EDIT: Somebody just suggested a very similar solution, using join instead of xargs:
brew rm FORMULA
brew rm $(join <(brew leaves) <(brew deps FORMULA))
See the comment on the issue mentioned above for more info.
A: brew rmtree doesn't work at all. From the links on that issue I found rmrec which actually does work. God knows why brew doesn't have this as a native command.
brew tap ggpeti/rmrec
brew rmrec pkgname
A: You can just use a UNIX pipe for this
brew deps [FORMULA] | xargs brew rm
A: A More-Complete Bourne Shell Function
There are a number of good answers already, but some are out of date and none of them are entirely complete. In particular, most of them will remove dependencies but still leave it up to you to remove the originally-targeted formula afterwards. The posted one-liners can also be tedious to work with if you want to uninstall more than one formula at a time.
Here is a Bourne-compatible shell function (without any known Bashisms) that takes a list of formulae, removes each one's dependencies, removes all copies of the formula itself, and then reinstalls any missing dependencies.
unbrew () {
local formula
for formula in "$@"; do
brew deps "$formula" |
xargs brew uninstall --ignore-dependencies --force
brew uninstall --force "$formula"
done
brew missing | cut -f2 -d: | sort -u | xargs brew install
}
It was tested on Homebrew 1.7.4.
Caveats
This works on all standard formulae that I tested. It does not presently handle casks, but neither will it complain loudly if you attempt to unbrew a cask with the same name as a standard formula (e.g. MacVim).
A: The goal here is to remove the given package and its dependencies without breaking another package's dependencies. I use this command:
brew deps [FORMULA] | xargs brew remove --ignore-dependencies && brew missing | xargs brew install
Note: Edited to reflect @alphadogg's helpful comment.
A: Other answers didn't work for me, but this did (in fish shell):
brew remove <package>
for p in (brew deps <package>)
brew remove $p
end
Because brew remove $p fails when some other package depends on p.
A: By the end of 2020, the Homebrew team added a simple command brew autoremove to remove all unused dependencies.
First, uninstall the package:
brew uninstall <package>
Then, remove all the unused dependencies:
brew autoremove
A: Based on @jfmercer answer (corrections needed more than a comment).
Remove package's dependencies (does not remove package):
brew deps [FORMULA] | xargs brew remove --ignore-dependencies
Remove package:
brew remove [FORMULA]
Reinstall missing libraries:
brew missing | cut -d: -f2 | sort | uniq | xargs brew install
Tested uninstalling meld after discovering MeldMerge releases.
A: Using this answer requires that you create and maintain a file that contains the package names you want installed on your system. If you don't have one already, use the following command and delete the package names what you don't want to keep installed.
brew leaves > brew_packages
Then you can remove all installed, but unwanted packages and any unnecessary dependencies by running the following command
brew_clean brew_packages
brew_clean is available here: https://gist.github.com/cskeeters/10ff1295bca93808213d
This script gets all of the packages you specified in brew_packages and all of their dependancies and compares them against the output of brew list and finally removes the unwanted packages after verifying this list with the user.
At this point if you want to remove package a, you simply remove it from the brew_packages file then re-run brew_clean brew_packages. It will remove b, but not c.
A: Save the following script as brew-purge
#!/bin/bash
#:Usage: brew purge formula
#:
#:Removes the package and all dependancies.
#:
#:
PKG="$1"
if [ -z "$PKG" ];then
brew purge --help
exit 1
fi
brew rm $PKG
[ $? -ne 0 ] && exit 1
while brew rm $(join <(brew leaves) <(brew deps $PKG)) 2>/dev/null
do :
done
echo Package $PKG and its dependancies have been removed.
exit 0
Now install it with the following command
sudo install brew-purge /usr/local/bin
Now run it
brew purge package
Example using gpg
$ brew purge gpg
Uninstalling /usr/local/Cellar/gnupg/2.2.13... (134 files, 11.0MB)
Uninstalling /usr/local/Cellar/adns/1.5.1... (14 files, 597.5KB)
Uninstalling /usr/local/Cellar/gnutls/3.6.6... (1,200 files, 8.9MB)
Uninstalling /usr/local/Cellar/libgcrypt/1.8.4... (21 files, 2.6MB)
Uninstalling /usr/local/Cellar/libksba/1.3.5... (14 files, 344.2KB)
Uninstalling /usr/local/Cellar/libusb/1.0.22... (29 files, 508KB)
Uninstalling /usr/local/Cellar/npth/1.6... (11 files, 71.7KB)
Uninstalling /usr/local/Cellar/pinentry/1.1.0_1... (12 files, 263.9KB)
Uninstalling /usr/local/Cellar/libassuan/2.5.3... (16 files, 444.2KB)
Uninstalling /usr/local/Cellar/libtasn1/4.13... (59 files, 436KB)
Uninstalling /usr/local/Cellar/libunistring/0.9.10... (54 files, 4.4MB)
Uninstalling /usr/local/Cellar/nettle/3.4.1... (85 files, 2MB)
Uninstalling /usr/local/Cellar/p11-kit/0.23.15... (63 files, 2.9MB)
Uninstalling /usr/local/Cellar/gmp/6.1.2_2... (18 files, 3.1MB)
Uninstalling /usr/local/Cellar/libffi/3.2.1... (16 files, 296.8KB)
Uninstalling /usr/local/Cellar/libgpg-error/1.35... (27 files, 854.8KB)
Package gpg and its dependancies have been removed.
$
A: The answer of @jfmercer must be modified slightly to work with current brew, because the output of brew missing has changed:
brew deps [FORMULA] | xargs brew remove --ignore-dependencies && brew missing | cut -f1 -d: | xargs brew install
A: Slightly refined; can supply multiple packages; has usage when none supplied.
#!/bin/bash
# Removes the package and all dependancies.
if [ $# -eq 0 ]; then
echo "$(basename $0) <pkg> [<pkg> [...]]"
exit 1
fi
function tree() {
pkg="$1"
join <(brew leaves) <(sort <(brew deps ${pkg}; echo ${pkg}))
}
let e=0
for pkg in "$@"; do
printf "Purging %s and its dependencies...\n" "${pkg}"
deps=( $(tree ${pkg}) )
while (( ${#deps[@]} > 0 )); do
brew rm "${deps[@]}"
deps=( $(tree ${pkg}) )
done
done | unknown | |
d9104 | train | Various versions of Node.js are using a same file (one from apt install, one from manually download), which caused the conflict, resulting the error.
Remove your Node.js 12.22.9 first. | unknown | |
d9105 | train | There's at least one common case where full laziness is "safe" and an optimization.
g :: Int -> Int
g z = f (z+1)
where f 0 = 0
f y = 1 + f (y-1)
This really means g = \z -> let {f = ...} in f (z+1) and, compiled that way, will allocate a closure for f before calling it. Obviously that's silly, and the compiler should transform the program into
g_f 0 = 0
g_f y = 1 + g_f (y-1)
g z = g_f (z+1)
where no allocation is needed to call g_f. Happily the full laziness transformation does exactly that.
Obviously programmers could refrain from making these local definitions that do not depend on the arguments of the top-level function, but such definitions are generally considered good style...
Another example:
h :: [Int] -> [Int]
h xs = map (+1) xs
In this case you can just eta reduce, but normally you can't eta reduce. And naming the function (+1) is quite ugly. | unknown | |
d9106 | train | You can calculate the duration and request the value in days.
const
diffInDays = (start, end) => moment.duration(end.diff(start)).asDays(),
dateFormat = 'DD MM YYYY',
nextWeek = moment().add(1, 'weeks').format(dateFormat),
post = { validTill: nextWeek },
diff = diffInDays(moment(), moment(post.validTill, dateFormat));
console.log('Start of next week:', nextWeek);
console.log('Days until:', diff); // 6.xxx (days)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script> | unknown | |
d9107 | train | Have you called the "AcceptChanges" method on the DataSet? | unknown | |
d9108 | train | I think the first problem is that it is hard to link what you are trying to achieve with what your code says thus far. Therefore, this feedback maybe is not exactly what you are looking for, but might give some ideas. Let's structure the problem into the common elements: (1) input, (2) process, and (3) output.
*
*Input
You mentioned that L will be a file, but I assume it is a line in a file, where each line can be one of the 3 (three) samples. In this regard, the samples also do not have consistent pattern.For this, we can build a function to convert each line of the file into Erlang term and pass the result to the next step.
*Process
The question also do not mention the specific logic in parsing/processing the input. You also seem to care about the data type so we will convert and display the result accordingly. Erlang as a functional language will naturally be handling list, so on most cases we will need to use functions on lists module
*Output
You didn't specifically mention where you want to display the result (an output file, screen/erlang shell, etc), so let's assume you just want to display it in the standard output/erlang shell.
Sample file content test1.txt (please note the dot at the end of each line)
[["name "," col"," dist"," a"," angv"," r "],["apollo11 ","white","0.1"," 0"," 77760"," 0.15"]].
["planets ","earth","venus "].
["a","b"].
Howto run: solarSystem:process_file("/Users/macbook/Documents/test1.txt").
Sample Result:
(dev01@Macbooks-MacBook-Pro-3)3> solarSystem:process_file("/Users/macbook/Documents/test1.txt").
apollo11 = ["white",0.1,0,77760,0.15]
planets = ["earth","venus"]
a = ["b"]
Done processing 3 line(s)
ok
Module code:
-module(solarSystem).
-export([process_file/1]).
-export([process_line/2]).
-export([format_item/1]).
%%This is the main function, input is file full path
%%Howto call: solarSystem:process_file("file_full_path").
process_file(Filename) ->
%%Use file:consult to convert the file content into erlang terms
%%File content is a dot (".") separated line
{StatusOpen, Result} = file:consult(Filename),
case StatusOpen of
ok ->
%%Result is a list and therefore each element must be handled using lists function
Ctr = lists:foldl(fun process_line/2, 0, Result),
io:format("Done processing ~p line(s) ~n", [Ctr]);
_ -> %%This is for the case where file not available
io:format("Error converting file ~p due to '~p' ~n", [Filename, Result])
end.
process_line(Term, CtrIn) ->
%%Assume there are few possibilities of element. There are so many ways to process the data as long as the input pattern is clear.
%%We basically need to identify all possibilities and handle them accordingly.
%%Of course there are smarter (dynamic) ways to handle them, but below may give you some ideas.
case Term of
%%1. This is to handle this pattern -> [["name "," col"," dist"," a"," angv"," r "],["apollo11 ","white"," 0.1"," 0"," 77760"," 0.15"]]
[[_, _, _, _, _, _], [Name | OtherParams]] ->
%%At this point, Name = "apollo11", OtherParamsList = ["white"," 0.1"," 0"," 77760"," 0.15"]
OtherParamsFmt = lists:map(fun format_item/1, OtherParams),
%%Display the result to standard output
io:format("~s = ~p ~n", [string:trim(Name), OtherParamsFmt]);
%%2. This is to handle this pattern -> ["planets ","earth","venus "]
[Name | OtherParams] ->
%%At this point, Name = "planets ", OtherParamsList = ["earth","venus "]
OtherParamsFmt = lists:map(fun format_item/1, OtherParams),
%%Display the result to standard output
io:format("~s = ~p ~n", [string:trim(Name), OtherParamsFmt]);
%%3. Other cases
_ ->
%%Display the warning to standard output
io:format("Unknown pattern ~p ~n", [Term])
end,
CtrIn + 1.
%%This is to format the string accordingly
format_item(Str) ->
StrTrim = string:trim(Str), %%first, trim it
format_as_needed(StrTrim).
format_as_needed(Str) ->
Float = (catch erlang:list_to_float(Str)),
case Float of
{'EXIT', _} -> %%It is not a float -> check if it is an integer
Int = (catch erlang:list_to_integer(Str)),
case Int of
{'EXIT', _} -> %%It is not an integer -> return as is (string)
Str;
_ -> %%It is an int
Int
end;
_ -> %%It is a float
Float
end. | unknown | |
d9109 | train | You have to draw the image each time at the start of your event hanling routine instead of inside the last if condition.
THEN draw the sizer rectangle. Otherwise the previous rectangle is not deleted. Image is progressively destroyed.
The higher the refresh rate, the greener your image becomes.
A possible optimization is to use a XOR mode so if you draw previous rectangle again it restores the image (but rectangle cannot be plain green in that case) but it is more complex | unknown | |
d9110 | train | You have some issue with your syntax in the documentation. You should use @link instead of @see.
/**
* @see http://php.net/manual/en/function.ucfirst.php ucfirst
*/
Change your documentation code to
/**
* @link http://php.net/manual/en/function.ucfirst.php ucfirst
*/
I have tested it and is working on my editor i.e. phpStorm
Note: It only works in the functions and class names. You cannot use it on comments. | unknown | |
d9111 | train | Don't use the -g flag when installing. The -g flag allows you to access the installed npm package via command line, but is not a part of your local project files.
If you need it both locally and globally, npm install it twice (once with the -g flag and once without).
A: If you are using Typescript, I don't think there's a type file for that package, so the compiler may give a warning even if the package is available. | unknown | |
d9112 | train | While it's difficult to fully understand what you are asking, it seems that you simply don't have anything pulling messages off of the queue in question.
In general, RabbitMQ will hold on to a message in a queue until a listener pulls it off and successfully ACKs, indicating that the message was successfully processed. You can configure queues to behave differently by setting a Time-To-Live (TTL) on messages or having different queue durabilities (eg. destroyed when there are no more listeners), but the default is to play it safe. | unknown | |
d9113 | train | The answer
Both compilers are correct!
Explanation
The Standard doesn't distinguish between an error and a warning, both go under the category of Diagnostics.
1.3.6 diagnostic message [defns.diagnostic]
message belonging to an implementation-defined subset of the implementation's output messages
Since the Standard says that a diagnostic is required in case a program is ill-formed, such as when a narrowing-conversion takes place inside a braced-initializer, both compilers are confirming.
Even if the program is ill-formed from the Standards point of view, it doesn't mandate that a compiler halts compilation because of that; an implementation is free to do whatever it wants, as long as it issues a diagnostic.
The reason for gcc's behavior?
Helpful information was provided by @Jonathan Wakely through comments on this post, below are a merge of the two comments;
he exact reason is that GCC made it an error at one point and it broke ALL THE PROGRAMS so it got turned into a warning instead. Several people who turned on the -std=c++0x option for large C++03 codebases found harmless narrowing conversions to cause most of the porting work to go to C++11See e.g. PR 50810 where Alisdair reports narrowing errors were >95% of the problems in Bloomberg's code base.In that same PR you can see that unfortunately it wasn't a case of "let's just issue a warning and be done with it" because it took a lot of fiddling to get the right behaviour. | unknown | |
d9114 | train | You can directly unpack the elements to print function. By default print function insert space between the values(this can be controlled via sep argument)
>>> p = ('180849', '104735')
>>> print(*p)
180849 104735
>>> print(*p, sep='-')
180849-104735
A: How about this, it is the easier way!
tup = ('this', 'is', 'a', 'tuple')
res = " ".join(tup)
I hope you like it. | unknown | |
d9115 | train | A dplyr option:
D %>%
group_by(group) %>%
mutate_at(c("V1", "V2"), ~./first(.))
# A tibble: 6 x 3
# Groups: group [2]
V1 V2 group
<dbl> <dbl> <dbl>
1 1 1 1
2 1.25 2 1
3 1.5 2.5 1
4 1 1 2
5 0.667 0.875 2
6 2.33 1.12 2
A: Here is a one-liner base R solution,
D[-3] <- sapply(D[-3], function(i) ave(i, D$group, FUN = function(i)i / i[1]))
D
# V1 V2 group
#1 1.0000000 1.000 1
#2 1.2500000 2.000 1
#3 1.5000000 2.500 1
#4 1.0000000 1.000 2
#5 0.6666667 0.875 2
#6 2.3333333 1.125 2
A: A dplyr way:
library(dplyr)
D %>%
group_by(group) %>%
mutate_all(~ round(. / first(.), 1))
A data.table approach:
library(data.table)
setDT(D)[, lapply(.SD, function(x) round(x / x[1], 1)), by = group]
A: A base R solution:
split(D, D$group) <- lapply(split(D, D$group),
function(.) {
.[,1:2] <- as.data.frame(t(t(.[, 1:2]) / unlist(.[1,1:2])))
.
})
D
# V1 V2 group
# 1 1.0000000 1.000 1
# 2 1.2500000 2.000 1
# 3 1.5000000 2.500 1
# 4 1.0000000 1.000 2
# 5 0.6666667 0.875 2
# 6 2.3333333 1.125 2
A: An option with base R
by(D[-3], D[3], FUN = function(x) x/unlist(x[1,])[col(x)]) | unknown | |
d9116 | train | After some chat room traversing and playing around with jsfiddle, I found that droppable areas have problems with the css margin property, not position: absolute. What happens is, if you set a margin-top or a margin-left or any other value for the margin property, only the element will move -- the drop area will not.
I hope this helps someone!
A: This issue was reported four years ago here: http://bugs.jqueryui.com/ticket/6876
It was recently fixed in jquery-ui 1.11.2 | unknown | |
d9117 | train | Android’s Near Field Communication documentation page states that it is indeed possible.
Android-powered devices with NFC simultaneously support three main modes of operation:
*
*Reader/writer mode, allowing the NFC device to read and/or write passive NFC tags and stickers.
. . .
A: Android will in the default setup automagically read any NDEF message and deliver it to your activity by invoking onNewIntent(..). Your app is then free to write to the tag - and can do so within the within the invokation to onNewIntent(..) or the following call to onResume(..).
A: i'm note sure if looking for react native for example, but you can do that from once inside a scope of a function that returns you the message and you can write immediately what you want.
The package is this one:
https://github.com/whitedogg13/react-native-nfc-manager
The feature is in the branch (tag-tech) open to discussion and sooner or later will be at master. | unknown | |
d9118 | train | Add this in you img class
img {
display: block; /*Add this*/
height: auto;
margin: 0 auto;/*Add this*/
max-width: 100%;
}
Hope it will helps you.
A: it is because of the <br /> at the end of the first 2 images, I solved it by putting a <br /> at the end of the last image and it worked.
div.a {
margin: 0;
overflow: auto;
padding: 0;
text-align: center;
word-wrap: break-word;
}
ul.b {
list-style-type: none;
margin: 0;
padding: 0;
text-align: center;
}
<div class="a">
<img src="http://www.gloryhood.com/images/free-will-1.png" alt="free will determinism and indeterminism" />
<br />
<img src="http://www.gloryhood.com/images/free-will-1.png" alt="free will determinism and indeterminism" />
<br />
<img src="http://www.gloryhood.com/images/free-will-1.png" alt="free will determinism and indeterminism" /> <br />
</div>
<br />
<ul class="b">
<li><img src="http://www.gloryhood.com/images/free-will-2.png" alt="daniel wegner's conditions of human action" /></li>
<li><img src="http://www.gloryhood.com/images/free-will-2.png" alt="daniel wegner's conditions of human action" /></li>
</ul>
A: I found another solution! You can just div each individual image.
<div>
<img src="link" alt="" />
</div>
<div>
<img src="link" alt="" />
</div>
<div>
<img src="link" alt="" />
</div> | unknown | |
d9119 | train | 6.5.7 Bitwise shift operators:
If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.
The compiler is at license to do anything, obviously, but the most common behaviors are to optimize the expression (and anything that depends on it) away entirely, or simply let the underlying hardware do whatever it does for out-of-range shifts. Many hardware platforms (including x86 and ARM) mask some number of low-order bits to use as a shift-amount. The actual hardware instruction will give the result you are observing on either of those platforms, because the shift amount is masked to zero. So in your case the compiler might have optimized away the shift, or it might be simply letting the hardware do whatever it does. Inspect the assembly if you want to know which.
A: according to the standard, shifting for more than the bits actually existing can result in undefined behavior. So we cannot blame the compiler for that.
The motivation probably resides in the "border meaning" of 0x80000000 that sits on the boundary of the maximum positive and negative together (and that is "negative" having the highmost bit set) and on certain check that should be done and that the compiled program doesn't to to avoid to waste time verifying "impossible" things (do you really want the processor to shift bits 3 billion times?).
A: It's very probably not attempting to shift by some large number of bits.
INT_MAX on your system is probably 2**31-1, or 0x7fffffff (I'm using ** to denote exponentiation). If that's the case, then In the declaration:
int b = 0x80000000;
(which was missing a semicolon in the question; please copy-and-paste your exact code) the constant 0x80000000 is of type unsigned int, not int. The value is implicitly converted to int. Since the result is outside the bounds of int, the result is implementation-defined (or, in C99, may raise an implementation-defined signal, but I don't know of any implementation that does that).
The most common way this is done is to reinterpret the bits of the unsigned value as a 2's-complement signed value. The result in this case is -2**31, or -2147483648.
So the behavior isn't undefined because you're shifting by value that equals or exceeds the width of type int, it's undefined because you're shifting by a (very large) negative value.
Not that it matters, of course; undefined is undefined.
NOTE: The above assumes that int is 32 bits on your system. If int is wider than 32 bits, then most of it doesn't apply (but the behavior is still undefined).
If you really wanted to attempt to shift by 0x80000000 bits, you could do it like this:
unsigned long b = 0x80000000;
unsigned long a = 1 >> b; // *still* undefined
unsigned long is guaranteed to be big enough to hold the value 0x80000000, so you avoid part of the problem.
Of course, the behavior of the shift is just as undefined as it was in your original code, since 0x80000000 is greater than or equal to the width of unsigned long. (Unless your compiler has a really big unsigned long type, but no real-world compiler does that.)
The only way to avoid undefined behavior is not to do what you're trying to do.
It's possible, but vanishingly unlikely, that your original code's behavior is not undefined. That can only happen if the implementation-defined conversion of 0x80000000 from unsigned int to int yields a value in the range 0 .. 31. IF int is smaller than 32 bits, the conversion is likely to yield 0.
A: well read that maybe can help you
expression1 >> expression2
The >> operator masks expression2 to avoid shifting expression1 by too much.
That because if the shift amount exceeded the number of bits in the data type of expression1, all the original bits would be shifted away to give a trivial result.
Now for ensure that each shift leaves at least one of the original bits,
the shift operators use the following formula to calculate the actual shift amount:
mask expression2 (using the bitwise AND operator) with one less than the number of bits in expression1.
Example
var x : byte = 15;
// A byte stores 8 bits.
// The bits stored in x are 00001111
var y : byte = x >> 10;
// Actual shift is 10 & (8-1) = 2
// The bits stored in y are 00000011
// The value of y is 3
print(y); // Prints 3
That "8-1" is because x is 8 bytes so the operacion will be with 7 bits. that void remove last bit of original chain bits | unknown | |
d9120 | train | Update your Html with below code
<table>
<tr>
<th *ngFor="let row of tableMockData; let i = index">{{row.header}}
</th>
</tr>
<tr *ngFor="let row of tableMockData; let i = index">
<td *ngFor="let row1 of row.rows">
{{row1}}
</td>
</tr>
</table>
You do not properly bind your JSON. | unknown | |
d9121 | train | Darn I fixed it within 5 seconds of posting the question, heres how I did it
Instead of using the baud rate to reset it I pressed the reset switch and run the exact same code
So the error is here
stty -F /dev/ttyACM0 speed 1200
stty -F /dev/ttyACM0 speed 57600
But I am not sure what exactly about it is wrong, and clarification would be appreciated anyway :) | unknown | |
d9122 | train | You need to read the response stream from the web server.
Use the response.GetResponseStream() function.
If the response contains Unicode text, you can read that text using a StreamReader. | unknown | |
d9123 | train | You can also create div's so you can enter letters when the user inputs a character. I've attached an example below.
UPDATE: Added example code to update the dashes with letters based on word
var elem = document.getElementById('container');
var guess = document.getElementById('guess');
var word = "Hello";
// draw empty dashes
var drawDashes = function(numberOfDashes) {
for (var i = 0; i < numberOfDashes; i++) {
var el = document.createElement('div');
el.classList = 'dash';
// we draw an empty character inside so that the element
// doesn't adjust height when we update the dash later with a
// letter inside
el.innerHTML = ' ';
elem.appendChild(el);
}
}
// update dash with a letter based on index
var updateDash = function(index, letter) {
elem.children[index].innerHTML = letter;
}
guess.addEventListener('keyup', function(evt) {
// split the word up into characters
var splitWord = word.split('');
// check to see if the letter entered matches any of the
// words characters
for (var i = 0; i < splitWord.length; i++ ) {
// it is important we convert them to lowercase or
// else we might get a mismatch because of case-sensitivity
if (evt.key.toLowerCase() === splitWord[i].toLowerCase()) {
// update dash with letter based on index
updateDash(i, evt.key.toLowerCase());
}
}
// clear out the value
this.value = '';
});
drawDashes(word.length);
body {
font-family: sans-serif;
}
.dash {
height: 50px;
width: 50px;
margin: 0 10px;
display: inline-block;
border-bottom: 2px solid black;
font-size: 32px;
font-weight: bold;
text-align: center;
}
#guess {
height: 50px;
width: 50px;
padding: 0;
font-size: 32px;
text-align: center;
}
<div id="container"></div>
<h4>Type a letter</h4>
<input id="guess" type="text"/>
A: Say your word is in some variable named myWord.
Get the length of the word by doing:
var myWordLen = myWord.length;
Then you can create HTML elements using Javascript createElement method and appending child elements, information etc as needed. But since you want as many elements as the length of a word, use a loop. Eg:
for(var i=0; i < myWordLen; i++)
{
var tr1 = document.createElement("hr");
var someEle = document.getElementById("someID");
someEle.appendChild(tr1);
}
A: What about this way?
myElement.innerHTML = `<...>`.repeat(words.length) | unknown | |
d9124 | train | They are parameters, not attributes, use ServletRequest#getParameter instead:
String login = request.getParameter("login");
String password = request.getParameter("password")
A: You can use the getParameter method getParameter
String login = request.getParameter("login");
String password = request.getParameter("password"); | unknown | |
d9125 | train | You already know how to use a constructor initializer list as you do it in the Date constructor.
You "call" a parent class constructor just the same way. In your case
DateISO::DateISO(short day, short month, short year)
: Date(day, month, year) // "Call" the parent constructor
{}
A: In addition to Some Programmer Dude's answer, it is also possible to inherit a constructor with 'using' like so:
class DateISO : public Date
{
using Date::Date;
};
This will redeclare all the base classes constructors in the child class, and all arguments will be forwarded to the base constructor, so this probably wouldn't be suitable if your base class had multiple constructors and you only wanted to inherit one of them, nor if your child class has additional members which must be initialised, but for your case where all members are in the base class and the child class only adds methods this should be okay. See the section on 'Inheriting Constructors' for more information. | unknown | |
d9126 | train | Use element.text() where element is your Element. | unknown | |
d9127 | train | The reason can be in FetchType.EAGER try to remove it:
@Entity(name = "production_order")
public class ProductionOrder {
....
@OneToMany(mappedBy ="productionOrder", cascade = {CascadeType.ALL})
@Cascade({org.hibernate.annotations.CascadeType.ALL})
private List<ProdOrderItem> items; | unknown | |
d9128 | train | yes, there are few issues with local vs. hosted. One of the important things to remember is the max_execution time for php script. You may need to reset the timer once a while during the data upload.
I suppose you have some loop which takes the data row by row from CSV file for example and uses SQL query to insert it into WP database. I usually put this simple snippet into my loop so it will keep the PHP max_exec_time reset:
$counter = 1;
// some upload query
if (($handle = fopen("some-file.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
mysql_query..... blablabla....
// snippet
if($counter == '20') // this count 20 loops and resets the counter
{
set_time_limit(0);
$counter = 0;
}
$counter = $counter + 1;
} //end of the loop
.. also BTW 512MB room is not much if the database is big. Count how much resources is taking your OS and all running apps. I have ove 2Gb WO database and my MySql needs a lot of RAM to run fast. (depends on the query you are using as well) | unknown | |
d9129 | train | Seems like you have forgotten to provide the access for the tableView1 in Vad_tycker.
Or You should do a crosscheck whether you have assigned the correct instance in tableView delegate's and also make sure to provide the implementation for the method of delegate's in their respect target classes.
A: I think you forgot to connect the tableView Datasource and Delegate methods in the vad_tycker controller.
Also check that the instance of UITableView i.e. in your case tableView1 is also connected with the TableView. on the view.
Thanks | unknown | |
d9130 | train | For storing just application's name and version and organization's name and domain you can use QCoreApplications's properties applicationName, applicationVersion, organizationDomain and organizationName.
I usually set them in main() function:
#include <QApplication>
#include "MainWindow.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
// These functions are member of QCoreApplication, QApplication's
// parent class:
app.setApplicationName("My Application");
app.setApplicationVersion("3.5.2");
app.setOrganizationName("My Company, or just My Name");
app.setOrganizationDomain("http://example.com/");
MainWindow window;
window.show();
return app.exec();
}
And I can use them to show a nice about message:
#include "MainWindow.h"
#include <QCoreApplication>
...
// Slot called when ? -> About menu is clicked.
void MainWindow::on_aboutAction_triggered()
{
QString message = tr("<strong>%1</strong> %2<br />"
"Developed by %3")
.arg(QCoreApplication::applicationName())
.arg(QCoreApplication::applicationVersion())
.arg(QString("<a href=\"%1\">%2</a>")
.arg(QCoreApplication::organizationDomain())
.arg(QCoreApplication::organizationName()))
;
QMessageBox::about(this, tr("About"), message);
} | unknown | |
d9131 | train | In Zend_Soap_Server you can attach/set an object like in SoapServer
/**
* Attach an object to a server
*
* Accepts an instanciated object to use when handling requests.
*
* @param object $object
* @return Zend_Soap_Server
*/
public function setObject($object) | unknown | |
d9132 | train | Set a CSS property for .ms-Checkbox where display: flex; This will default to a row layout which will make the children of .ms-Checkbox to be displayed inline.
.ms-CheckBox {
display: flex;
}
<link href="https://static2.sharepointonline.com/files/fabric/office-ui-fabric-js/1.4.0/css/fabric.components.min.css" rel="stylesheet"/>
<link href="https://static2.sharepointonline.com/files/fabric/office-ui-fabric-js/1.4.0/css/fabric.min.css" rel="stylesheet"/>
<div class="ms-CheckBox">
<input tabindex="-1" type="checkbox" class="ms-CheckBox-input">
<label role="checkbox" class="ms-CheckBox-field" tabindex="0" aria-checked="false" name="checkboxa">
<span class="ms-Label">Checkbox</span>
</label>
</div> | unknown | |
d9133 | train | You to need escape all the parameters (UrlEncode). At the moment it is unescaped and has a whole bunch of new lines too.
Before you do that, I suggest you just append "hello world" parameter and re-display that to ensure your redirect page is working | unknown | |
d9134 | train | You basically have two options:
*
*Modify your Tomcat configuration to mount the WAR at the root. How this is done depends on how exactly you're deploying your application. This is the cleaner approach unless there's some preventing factor.
*Handle the problem on the Apache side by using mod_rewrite to rewrite URLs starting with / to /foo, at which point it will be passed through your JkMount to Tomcat
For the second option, your Apache configuration would look something like this:
# Turn on mod_rewrite
RewriteEngine On
# This is the rule. Use regexp to match any URL beginning with /, and rewrite it to
# /foo/remaining_part_of_URL. The [PT] (pass-through) is necessary to make rewritten
# requests go through JkMount
RewriteRule ^/(.*) /foo/$1 [PT]
# Forward all URLs starting with foo to Tomcat
JkMount /foo/* worker
(this isn't actually tested, hope it works as is!). You may also need to enable mod_rewrite in your Apache (check out your distribution, a mods-enabled directory might be the answer).
And if you need to know more about mod_rewrite (quite a powerful beast), go here:
http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html#rewriterule
A: Here is a Mod Rewrite Solution
WORKERS.PROPERTIES
worker.list=worker1
worker.worker1.port=8009
worker.worker1.host=localhost
worker.worker1.type=ajp13
worker.worker1.mount=/foo/* #THIS IS THE APP NAME: "FOO"
HTTPD.CONF
<VirtualHost *:80>
RewriteEngine On
RewriteRule ^/(.*)/Foo/$1 [PT]
ServerName example.com #DOMAIN NAME: "example.com"
ServerAlias www.example.com
JkMount /foo/* worker1
</VirtualHost> | unknown | |
d9135 | train | If you don't see even the plain color, the first I'd recommend to check how it was discarded. There are no so many options:
*
*glColorMask. Highly likely it's not your case, since pass 1 works;
*Wrong face culling and polygon winding order (CW, CCW). By your geometry shader, it looks like CW;
*Blending options;
*Depth-stencil state. I see you use glNamedRenderbufferStorage(mix_renderbuffer, GL_DEPTH24_STENCIL8, 1000, 800); What are depth-stencil settings?
If everything above looks good, any glGetError messages? If it's ok, try to remove MRT for a debugging purposes and output the only color in the second pass. If it would work, probably some error in MRT + Depth buffer setup. | unknown | |
d9136 | train | I'm not too sure that your data is in the best format, but given what you have the following code will work:
students = [{'123': [{'course1': 2}, {'course2': 2}]},
{'124': [{'course1': 3}, {'course2': 4}]},
{'125': [{'course1': 24}, {'course2': 12}]},
{'126': [{'course1': 2}, {'course2': 24}]}]
finals = [{'student_number':'123', 'exam':'passed'},
{'student_number':'124', 'exam':'ungraded'},
{'student_number':'125', 'exam':'failed'}]
studentIDs = [i.keys()[0] for i in students]
passed_students=[]
other_students=[]
for row in finals:
snum = row['student_number']
status = row['exam']
if status=='passed' and snum in studentIDs:
passed_students.append(snum)
elif status!='passed' and snum in studentIDs:
other_students.append(snum)
else:
print 'Student ID {0} not found in list.'.format(snum)
A: A little exercise for list comprehensions:
students = [{'123': [{'course1': 2}, {'course2': 2}]},
{'124': [{'course1': 3}, {'course2': 4}]},
{'125': [{'course1': 24}, {'course2': 12}]},
{'126': [{'course1': 2}, {'course2': 24}]}]
finals = [{'student_number':'123', 'exam':'passed',},
{'student_number':'124', 'exam':'ungraded',},
{'student_number':'125', 'exam':'failed',},]
# Extract student id numbers.
student_ids = set(
student_data.keys()[0]
for student_data in students)
# Restrict finals to the students that exist in students.
students_with_finals = [
final
for final in finals
if final['student_number'] in student_ids]
passed_students = [
final['student_number']
for final in students_with_finals
if final['exam'] == 'passed']
other_students = [
final['student_number']
for final in students_with_finals
if final['exam'] != 'passed']
print('Passed students: {}'.format(passed_students))
print('Other students: {}'.format(other_students))
Result:
Passed students: ['123']
Other students: ['124', '125']
It looks like that the data structures could be simplified by using dictionaries with the student ids as keys:
students = {
'123': [{'course1': 2}, {'course2': 2}],
'124': [{'course1': 3}, {'course2': 4}],
'125': [{'course1': 24}, {'course2': 12}],
'126': [{'course1': 2}, {'course2': 24}],
}
finals = {
'123': {'exam':'passed', 'points': 100},
'124': {'exam':'ungraded'},
'125': {'exam':'failed'},
}
A: >>> students = {'123':{'name':'Bonnie','course_1':2, 'course_2':2},
... '124':{'name':'Jerry', 'course_1':3, 'course_2':4},
... '125':{'name':'Bob', 'course_1':24, 'course_2':12},
... '126':{'name':'Jill', 'course_1':2, 'course_2':24}}
>>> finals = [{'num':'123', 'exam':'passed'},
... {'num':'124', 'exam':'ungraded'},
... {'num':'125', 'exam':'failed'}]
>>> student_results = {'passed':[], 'ungraded':[], 'failed':[]}
>>>
>>> for final in finals:
... student_results[final['exam']].append(students[final['num']])
>>>
>>> # Print student results.
>>> for result in ['passed', 'ungraded', 'failed']:
... print "Students %s:" % result
... for student in student_results[result]:
... print " " + student['name']
...
Students passed:
Bonnie
Students ungraded:
Jerry
Students failed:
Bob | unknown | |
d9137 | train | Every time you ask a question try to include some data so people can play with in order to find correct answers.
In this case, you shouldn't use a "," in the brackets:
PrePost_NJ <-data10$NormalizedJerk[data10$trial=="102"]
Take a look to the 'tidyverse' package, it will make your data manipulation easier. | unknown | |
d9138 | train | Wrong logic use just this (direct assignation):
v=$?
A: Instead of v = echo $?
Either write
v=`echo $?`
OR
v=$? | unknown | |
d9139 | train | If the path could be arbitrary , you can split the the strings using \\ removing any '' you may get along the way and then do os.path.join , Example -
>>> import os.path
>>> l = "Google\Drive\\\\ Temp"
>>> os.path.join(*[s for s in l.split('\\') if l != ''])
'Google\\Drive\\ Temp'
Then you can use that in os.listdir() to list the directories. | unknown | |
d9140 | train | My best guess is that date is really a datetime and it has a time component. To get just the date, use the date() function:
SELECT date(`date`) as `date`, COUNT(*)
FROM `sales_flat_table`
GROUP BY date(`date`); | unknown | |
d9141 | train | size_t endpos = str.find_last_not_of( L”\\/” ); // no
size_t endpos = str.find_last_not_of( L"\\/" ); // yes
Beware of code that you copied off a website, maybe a blog post. The author may well have used a word processor, one that implements 'smart quotes'. If you look closely at the first and the second line you'll see the difference. Your compiler will only like the straight double-quotes.
It doesn't quite explain your problem with the Immediate Window, it works when I try your string as shown. Maybe it doesn't quite look like it either. | unknown | |
d9142 | train | I believe directly manipulating the address bar to a completely different url without moving to that url isn't allowed for security reasons, if you are happy with it being
www.mysite.com/products/#{selectedCat}
i.e. an anchor style link within the same page then look into the various history/"back button" scripts that are now present in most javascript libraries.
The mention of update panel leads me to guess you are using asp.net, in that case the asp.net ajax history control is a good place to start
A: To add to what the guys have already said edit the window.location.hash property to match the URL you want in your onclick function.
window.location.hash = 'category-name'; // address bar would become http://example.com/#category-name
A: I don't think this is possible (at least changing to a totally different address), as it would be an unintuitive misuse of the address bar, and could promote phishing attacks.
A: With HTML5 you can modify the url without reloading:
If you want to make a new post in the browser's history (i.e. back button will work)
window.history.pushState('Object', 'Title', '/new-url');
If you just want to change the url without being able to go back
window.history.replaceState('Object', 'Title', '/another-new-url');
The object can be used for ajax navigation:
window.history.pushState({ id: 35 }, 'Viewing item #35', '/item/35');
window.onpopstate = function (e) {
var id = e.state.id;
load_item(id);
};
Read more here: http://www.w3.org/TR/html5-author/history.html
A fallback sollution: https://github.com/browserstate/history.js
A: This cannot be done the way you're saying it. The method suggested by somej.net is the closest you can get. It's actually very common practice in the AJAX age. Even Gmail uses this.
A:
"window.location.hash"
as suggested by sanchothefat should be the one and only way of doing it. Because all the places that I have seen this feature, it's all the time after the # in URL. | unknown | |
d9143 | train | You could do get all the filenames for which you want to apply this using list.files, loop over each filename, read it, match it with csv2 dataframe and get corresponding value to multiply.
filenames <- list.files('path/of/files', full.names = TRUE, pattern = "\\.csv$")
list_df <- lapply(filenames, function(x) transform(read.csv(x, header = FALSE),
V3 = V3 * csv2$V3[match(
tools::file_path_sans_ext(basename(x)), csv2$V2)]))
This will return you updated list of dataframes that can be accessed like list_df[[1]], list_df[[2]] etc.
where csv2 is
csv2 <- structure(list(V1 = structure(c(1L, 3L, 2L), .Label = c("hey",
"mat", "sol"), class = "factor"), V2 = c(318L, 497L, 498L), V3 = c(0.08,
0.22, 0.06)), class = "data.frame", row.names = c(NA, -3L)) | unknown | |
d9144 | train | Here
if(left[i]<= right[j])
arr[k++]=left[i++];
else
arr[k++]=left[j++];
last left should be right.
Anyway, where do you free the memory you malloc-ed...?
A: It is a very bad idea to malloc a new buffer for each sub-array on every recursive call. Remember, malloc is quite expensive action, and free costs even much more than malloc!
The subarrays resulting from recursive splitting do not overlap (except for the result of merge spans over two merged parts). So you never need more than one buffer at a time for the merge result and that merge does not interfere with any other merge (except with those for which it is a sub-range). As a result it's enough to create just a single copy of the whole input array and use both arrays alternatively as a source place and destination place for recursive merges:
void merge( int dst[], int src[], int idx1, int idx2, int end2)
{
int idx = idx1;
int end1 = idx2;
while(idx1 < end1 && idx2 < end2)
dst[idx++] = src[idx1] <= src[idx2] ? src[idx1++] : src[idx2++];
while(idx1 < end1)
dst[idx++] = src[idx1++];
while(idx2 < end2)
dst[idx++] = src[idx2++];
}
void mrgsrt( int dst[], int src[], int begin, int len)
{
if(len == 1)
dst[begin] = src[begin];
if(len > 1) {
int mid = len/2;
mrgsrt(src, dst, begin, mid);
mrgsrt(src, dst, begin+mid, len-mid);
merge(dst, src, begin, begin+mid, begin+len);
}
}
void sort( int a[], int len)
{
int *tmp;
if((tmp = malloc(len*sizeof(*a))) != NULL) {
memcpy(tmp, a, len*sizeof(*a));
mrgsrt(a, tmp, 0, len);
free(tmp);
}
} | unknown | |
d9145 | train | fmul, fdiv, fadd edit data in floating stack directly, so instead of pulling from stack to register, do operation directly in floating stack.
Correct usage of floating point stack in conversion.asm:
.DATA
five DWORD 5.0
nine DWORD 9.0
ttw DWORD 32.0
.CODE
C2F proc
fmul nine
fdiv five
fadd ttw
ret
C2F ENDP
For reading float and writing float I used Irvine library, which uses floating point stack:
Include Irvine32.inc
Include conversion.asm
.data
Celprompt BYTE "Enter a value in C:",0
Cel DWORD 0
Resprompt BYTE "In Farenheit that value is - "
Faren DD ?
.code
main PROC
mov edx, OFFSET Celprompt
call WriteString
call Crlf
call ReadFloat
call C2F
call Crlf
mov edx, OFFSET Resprompt
call WriteString
call WriteFloat
main ENDP
END main | unknown | |
d9146 | train | In MSTest you usually use ExpectedException like this:
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void TestMethod1()
{
DoWhatEverThrowsAnArgumentNullException();
}
If you don't like it that way then you can look at this project on GitHub: MSTestExtensions | unknown | |
d9147 | train | You can Try this
*Simply Override Empty onBackPressed *
@Override
public void onBackPressed(){
// do nothing.
}
A: You can Try this
*Simply Override Empty onBackPressed *
@Override
public void onBackPressed(){
// do nothing.}
A: You have to write an override method
@Override
public void onBackPressed() {
\\you can do whatever you want to here.
\\don't call **super**, if u want disable back button in current screen.
}
A: In your Activity you have to override method:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
return !disableBackKey ;
}
return super.onKeyDown(keyCode, event);
}
And make disableBackKey True/False depend upon your requirement.
A: If you are using Activity, please add below function to your activity
@Override
public void onBackPressed() {
//super.onBackPressed();
}
if you are using Fragment, please add below function to your fragment
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
return true
}
return false;
}
A: Answer for Ionic 2 or 3
Call the below method at the end of constructor.
Registration in the below code is your class name of current page or component.
if you don't want to do anything on back button, simply remove the code in IF condition below.
overrideHardwareBackButton() {
this.platform.ready().then(() => {
this.platform.registerBackButtonAction(() => {
let activeView:ViewController = this.navCtrl.getActive();
if (activeView != null && ((<any> activeView).instance instanceof Registration)) {
console.log("Registration -> Home");
this.nav.setRoot(HomePage);
} else {
console.log("Somthing is wrong");
}
});
});
} | unknown | |
d9148 | train | In case you're not already doing that I'd like to say that the best option would be to use a proper connection pool on the server instead of reusing a single connection.
Now, increasing the timeout SHOULD be safe, but MySQL might have memory leaks (of sorts) that are tied to the connection, so dropping the connection from time to time might be much safer.
For example, if you're using dynamically generated prepared queries (some APIs do that to make the queries safe from the SQL injection attacks) then MySQL might have a problem caching all the prepared queries in memory.
You might have to implement such eviction yourself, unfortunately. | unknown | |
d9149 | train | Your solution above would also return documents where the field is null, which you don't want I guess. So the correct solution would be this one:
GET memoire/_search/?
{
"query": {
"bool": {
"filter": {
"exists": {
"field": "test"
}
},
"must_not": {
"term": {
"test.keyword": ""
}
}
}
}
}
A: Here is a solution. Use must_not with term query. This should work:
GET memoire/_search/?
{
"query": {
"bool": {
"must_not": {
"term": {"IMG.keyword": ""}
}
}
}
} | unknown | |
d9150 | train | See this, using fsockopen:
http://www.jonasjohn.de/snippets/php/post-request.htm
Fsockopen is in php standard library, so all php fron version 4 has it :)
A: try file_get_contents() and stream
$opts = array( 'http'=>array('method'=>"POST", 'content' => http_build_query(array('status' => $message)),));
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
$file = file_get_contents('http://www.example.com/', false, $context); | unknown | |
d9151 | train | Add the page as a parameter on redirect for remove and edit :
@RequestMapping("edit/{id}")
public String editUser(@PathVariable("id") int id, @RequestParam(value="page", required = false) Long page, Model model) {
if (null == page) page = 1L;
model.addAttribute("user", userService.getUser(id));
model.addAttribute("searcheduser", new User());
model.addAttribute("listUsers", userService.getUsers(page));
model.addAttribute("page", page);
return "redirect:/users?page="+page;
}
The same for remove . | unknown | |
d9152 | train | From your text it sounds like you want to use the and operator:
Do While headingStart <> -1 And count <= 3
...[Statement]...
count = count + 1
Loop
That way the loop will only execute when both criteria are met. In other words, you will jump out of the loop if headingStart equals -1 OR when count > 3. | unknown | |
d9153 | train | This is a known issue with ORM. Here I outline the solutions I know about and give a few pointers.
1 Surrogate/primary key: auto-generated
As you mentionned, if the object has not been saved, this doesn't work.
2 Surrogate/primary key: assigned value
You can decide to assign the value of the PK in the code, this way the object has always an ID and can be used for comparison. See Don't let hibernate steal your identity.
3 Natural key
If the object has another natural key, other than the primary key, you can use this one. This would be the case for a client entity, which has a numeric primary key and a string client number. The client number identifies the client in the real world and is a natural key which won't change.
4 Object values
Using the object values for equality is possible. But is has other shortcomings has you mentioned. This can be problematic if the values changes and the object is in a collection. For instance, if you have a Set with two objects that were different at first, but then you change the values while they are reference in the set so that they become equal. Then you break the contract of the Set. See Hibernate equals and hashcode.
5 Mixed: value + autogenerate primary/surrogate keys
If the objects to compare have an ID already, use it. Otherwise, use the object values for comparison.
All have some pros and cons. IMHO, the best is 3, if it is possible with your domain model. Otherwise, I've used 5 and it worked, though there are still some trap when using collections. I never used 2 but that sounds also a sensible solution, if you find a way to generate the PK in the code. Maybe other people have pointers for this one. | unknown | |
d9154 | train | In discord.py, you must call the .start() method on every loop that you create. In this case, add_seconds.start(). Also, try adding global secondsUp to the top of your function definition. | unknown | |
d9155 | train | To remove a DisplayObject ( the text field in your case ) from its parent DisplayObjectContainer, you can use the removeChild() method :
myTextField_txt.parent.removeChild(myTextField_txt);
Then to free the associated memory, you can add :
myTextField_txt = null;
You can also remove all event listeners added to your URLLoader object like this :
myTextLoader.removeEventListener(Event.COMPLETE, onLoaded);
Hope that can help. | unknown | |
d9156 | train | To only download the HTML of a specific element, change the logic to select that element instead of the entire body, like this:
document.querySelector('#save-btn').addEventListener('click', e => {
e.preventDefault();
let html = document.querySelector('div').outerHTML; // update this selector in your local version
download('index.html', html);
});
function download(filename, text) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
Working example | unknown | |
d9157 | train | You need to add the following:
#nav ul li:hover a {
color: #fff;
}
This styles the a tag within the hovered li. Hope that makes sense!
A: The reason is you have the :hover that changes the color applied to the <a>, not the <li>.
You should have a hover on the <li> style the <a> and it will work correctly.
CSS:
#nav ul li:hover a{
color:#FFF;
}
JSFiddle Demo | unknown | |
d9158 | train | Solution found. For people wondering what was wrong:
I guess that the GeometryReader in CardView gets the size of the ScrollView of the parent CardNavigatorView, which is in turn considered as empty. Since GeometryReader closures allows to expand outside of its border, I got the effect I tried to explain.
The tip is to provide a frame(width:geometry.size.width) modifier to the CardView instance! (to be tuned up to your need) | unknown | |
d9159 | train | You could try making a JToolBar and then add buttons to it.
A: You should use JTabbedPane and for each element one tab.
UPDATE:
Here you find a simple example of tabs with icons
A: One option is to just horizontally align buttons. But make it your own horizontal menu component with dynamic itens and a flexible interface. | unknown | |
d9160 | train | I don't know exactly how the Philips TV browser works, but the most logical thing to try out first would be the og:image tag and see if the TV picks it up.
<meta property="og:image" content="http://example.com/image.png"/>
If not, then the TV is probably using some screen capture library. You could try this workaround to get the desired behaviour:
First, find out your TV's user agent. For example, browse to http://whatsmyuseragent.com/ from your TV.
Then on your page, create a small script that checks the user agent, and if it's the TV, show your preview picture as an overlay for a few seconds.
Hopefully the TV will take a screenshot of the initial render of the page, and then your TV splash will show.
function hideSplash() {
document.getElementById("tv-splash").style.display = "none";
}
// Remove '|Mozilla' when development is ready
if (/Philips|Mozilla/.test(navigator.userAgent)) {
setTimeout(hideSplash, 2000);
} else {
hideSplash();
}
#tv-splash {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: #f00 url(http://i.imgur.com/IonCAf7.jpg) center center no-repeat;
background-size: 50%;
z-index: 1;
}
<div id="tv-splash"></div>
<h1>My website</h1> | unknown | |
d9161 | train | Your are overriding the auth functionality by your view function auth.
For example if I import sys and create a same function name as sys then it overrides its functionality in the local namespace.
>>> import sys
>>> sys.path[0]
''
>>> sys.path[1]
'/usr/local/lib/python2.7/dist-packages'
>>> def sys():
... return "Hello"
...
>>> sys.path
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'function' object has no attribute 'path'
So just change your view function name auth to some other name.
OR
Try to import your auth feature with different name.
from django.contrib import auth as django_auth
def auth(request):
username = request.POST.get('username', '')
password = request.POST.get('password', '')
user = django_auth.authenticate(username=username, password=password)
if user is not None:
django_auth.login(request, user)
return HttpResponseRedirect('polls/create')
else:
return HttpResponseRedirect('polls/login')
A: Your function name is 'auth' and this clashes with the 'auth' module you are importing. Change your function name or you could use the 'as' import syntax:
from django.contrib import auth as django_auth
and then use it in your function:
user = django_auth.authenticate(username=username, password=password) | unknown | |
d9162 | train | Pass the data not the graph. You can pass the data as so:
Intent i = new Intent(getApplicationContext(), NewActivity.class);
i.putExtra("new_variable_name","value");
startActivity(i);
and get it it new activity this way:
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("new_variable_name");
}
You might have to pass the data as parcelable or serializable depending on what kind of data you have.
Then you can draw the graph on the new activity with the data you passed.
A: In my opinion your overall design approach needs a little refinement.
First, I recommend you avoid using a splash Activity to 'contain' the network operations. From a user experience perspective this could be poor, because the splash screen could be in view for an indeterminate amount of time from one use to the next. If the splash screen stays for more than, say, two seconds, then the application might appear to have become unresponsive. If you insist on doing it this way, I recommend that the splash screen at least contains dynamic status information to inform the user what's going on.
Next, be sure to perform your networking operation on a dedicated Thread, not on the main UI thread.
For the MainActivity to reference the fetched data, I suggest you look at the singleton pattern to hold it in memory. That is, either use a dedicated singleton object, or hold it in a subclass of Application. This way, the networking operation sets the data in that singleton, and the MainActivity obtains it from the singleton. Optionally, when you create the Intent for the MainActivity, the Bundle could perhaps contain a String which acts as a key to obtain the data. The reason I'm suggesting this strategy is because I am assuming that there might be a large amount of data involved. If on the other hand it's a very small amount of data, perhaps you might be able to get away with putting the data itself into the Bundle, perhaps as JSON in a String, or something.
Do keep in mind that if the application goes to the background and is then later resumed, you might be in a situation where your Activity stack is resumed, but all of your application's 'global' state is gone. This means that your MainActivity would be resumed, but the data you expected to be in your singleton class isn't there any more. Your MainActivity should have the means to cope with this, perhaps by setting off a fresh network request. | unknown | |
d9163 | train | You have access to more tabBarOptions that might help. Here's how we style ours:
{
tabBarPosition: 'bottom',
tabBarOptions: {
showLabel: false,
showIcon: true,
activeTintColor: black,
inactiveTintColor: gray,
activeBackgroundColor: white,
inactiveBackgroundColor: white,
style: {
backgroundColor: white,
},
tabStyle: {
backgroundColor: white,
},
},
}
as far as adding the bottom bar, you can toggle icons when they are focused like this:
HOME: {
screen: HomeScreen,
navigationOptions: {
tabBarIcon: ({ tintColor, focused }) => <HomeIcon focused={focused ? UnderlinedIcon : RegularIcon } />,
},
},
So maybe in one of the icons you add a line at the bottom and in the other you don't, and then they'll toggle when focused. Hope this helps!! | unknown | |
d9164 | train | It’s sort of a hack, but it can be done. The solution is nicely explained in the WWDC 2012 Session #223: Enhancing User Experience with Scroll Views. The main trick is to place a regular UIScrollView over your content, watch for the offset changes reported by the scrollViewDidScroll: delegate call and adjust your custom view’s content accordingly. The only catch is accepting other touch input (as the scroll view covers your real content view and swallows the input), but even this is reasonably easy to solve, as shown in the WWDC video. | unknown | |
d9165 | train | The best way to do that that doesn't involve the headache of making sure that everything is positioned exactly correctly is using Selenium IDE. Selenium provides a very robust browser automation toolkit, and the IDE version is fairly easy to use although it may require some tweaking. You can download the Firefox plugin here, under Selenium IDE. | unknown | |
d9166 | train | You have some options: for example:
*
*move the labels differently depending on the texfield tapped (less if the first field, more for the last)
*change your Interface so that all your text fields use just the space available when keyboard is up
A: There are many third party libraries available like https://github.com/hackiftekhar/IQKeyboardManager or https://github.com/michaeltyson/TPKeyboardAvoiding.
You can use any of them, and forgot about keyboard handling by yourself. These cool libraries take care of most of the things. | unknown | |
d9167 | train | Tested it myself, it returns aaa properly (after removing in.next() at the bottom of the method and replacing it with in.nextLine()). When you do a return call, you need to send it somewhere. Such as System.out or to a variable like int x = getUserFromInput("test: ");
public class Tester {
private static Scanner in = new Scanner(System.in);
private static int getIntFromUser(String aa) {
int aaa = 0;
while (true && aaa <= 0) {
try {
System.out.println(aa + ": ");
aaa = in.nextInt();
if (aaa <= 0) {
System.out.println("Please enter a positive number.");
}
} catch (Exception e) {
System.out.println("Please enter an integer: ");
in.next();
}
}
in.nextLine();
return aaa;
}
public static void main(String[] a) {
System.out.println(getIntFromUser("test123"));
}
}
Output | unknown | |
d9168 | train | This seems to be a bug in Chrome 25. I tested it in virtualbox with Chrome 24 and updated to Chrome 25.
Chrome 24 => No dialog
Chrome 25 => Dialog
Maybe you should file a bug. :-)
A: You can try proxy-redirect to script with different URI
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
header('Location: proxy.php?uri='.$_SERVER['REQUEST_URI'], true, 303);
}
then come back
# proxy.php
if (!empty($_GET['uri'])) {
// maybe some validation here
header('Location: '.$_GET['uri'], true, 303);
}
A: When a user tries to restore the pages which have been unexpectedly shut down, then the browser will display this error 'err_cache_miss'. Watch the video proof for main source of the error
https://www.youtube.com/watch?v=6c9ztzqlthE
A: this will help you more better way
just put this in any file that include all files
header("Cache-Control: no-cache, must-revalidate");
if not then try this
session_cache_limiter('private, must-revalidate');
session_cache_expire(60); | unknown | |
d9169 | train | This can be done without using ajax with help of jQuery.
Define jade like this
input.addTxtBox(type='text')
#rows
and then in javascript
jQuery(document).ready(function() {
// initiate layout and plugins
$('.addTxtBox').keyup(function (e) {
var value = $('.addTxtBox').val();
var str = '<input type="text">';
for(var i=0; i < parseInt(value) ; i++){
$("#rows").append(str);
}
});
});
check this jsfiddle | unknown | |
d9170 | train | Add it to the where clause and put the ors in braces:
select * from songs where status = 1 and ( name LIKE '%search%' or author LIKE '%search%' or tags LIKE '%search%');
A: You can use parentheses to combine conditions and have an 'and' at the end so that either of the current conditions are true, and the condition you are about to add:
select *
from songs
where
(name LIKE '%search%' or
author LIKE '%search%' or
tags LIKE '%search%'
) and
status=1; | unknown | |
d9171 | train | Is there an API that will return how many results there are based your query search?
I'm not aware of any ES API that will return an exact count. At high values, it becomes very approximate.
array is empty when you paginate beyond 10,000 results.
First, returning >10k search results is highly unusual. It sounds like you're trying to use ElasticSearch as a database, which you can do for some things, but don't go depending on ACID or anything like that.
To page over large result sets in ElasticSearch, create a point in time and pass that to the search API with the search_after parameter. | unknown | |
d9172 | train | i tried the syntax .... | int | abs on ansible 2.5 and got the same error, while on ansible 2.4 it works.
i think you are affected by this bug | unknown | |
d9173 | train | The only way is that you pre parse the xml file so you understand the class to create.
You could also write somewhere (in the file extension? in an attribute of the first element of the doc?) the class type.
When you have the class type you can create the right class via a switch statement (converting a string to a type) or via reflection (better). | unknown | |
d9174 | train | the geolocation service is asynchronous, you need to use the data (pos2) in the callback function when/where it is available. Currently you are calling the geocoder before that value is set.
proof of concept fiddle
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
pos2 = pos;
latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(pos);
infoWindow.setPosition(pos);
infoWindow.setContent('La tua posizione.');
// call reverse geocoder with location returned by geolocation service
var geocoder = new google.maps.Geocoder;
geocoder.geocode({
'latLng': pos2
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
map.setZoom(11);
var marker = new google.maps.Marker({
position: pos2,
map: map
});
infoWindow.setContent('La tua posizione.<br>'+ results[0].formatted_address);
} else {
document.getElementById('msg').innerHTML = 'results[1].formatted_address';
window.alert('No results found');
}
} else {
document.getElementById('msg2').innerHTML = JSON.stringify(pos2);
window.alert('Geocoder failed due to: ' + status);
}
});
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
code snippet:
div#mapdiv {
width: 500px;
height: 300px;
margin: 10px auto;
}
<div id="mapdiv"></div>
<div id="msg"></div>
<div id="msg2"></div>
<script type="text/javascript">
function initMap() {
var pos2;
var map = new google.maps.Map(document.getElementById('mapdiv'), {
center: {
lat: -34.397,
lng: 150.644
},
zoom: 12
});
var infoWindow = new google.maps.InfoWindow({
map: map
});
var latLng;
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
pos2 = pos;
latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(pos);
infoWindow.setPosition(pos);
infoWindow.setContent('La tua posizione.');
var geocoder = new google.maps.Geocoder;
geocoder.geocode({
'latLng': pos2
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
map.setZoom(11);
var marker = new google.maps.Marker({
position: pos2,
map: map
});
infoWindow.setContent('La tua posizione.<br>'+ results[0].formatted_address);
} else {
document.getElementById('msg').innerHTML = 'results[1].formatted_address';
window.alert('No results found');
}
} else {
document.getElementById('msg2').innerHTML = JSON.stringify(pos2);
window.alert('Geocoder failed due to: ' + status);
}
});
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}
</script>
<script async defer src="https://maps.google.com/maps/api/js?callback=initMap"></script> | unknown | |
d9175 | train | Your animation changes view hierarchi params so you should apply new layout params (lp) to ImageView.
Create custom animation which will apply new lp to ImageView setting different width/height on every frame. So your image view will increase it's size and move other views. There are a lot examples how to implement this. Take a look at this one.
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
android.view.ViewGroup.LayoutParams lp = mContent.getLayoutParams();
lp.height = (int) (mStartHeight + mDeltaHeight * interpolatedTime);
mContent.setLayoutParams(lp);
} | unknown | |
d9176 | train | Give your elements class names, e.g
@Html.EditorFor(m=> m.QuoteDetail[i].Amount, new { htmlAttributes = new { @class = "form-control amount"} })
and change the container to <div class="row">
(ditto for discount, listprice and price)
Then your script becomes
$('.amount, .discount').change(function() {
// Get container
var row = $(this).closest('.row');
// Get values
var amount = Number(row.find('.amount').val());
var listprice = Number(row.find('.listprice').val());
var discount = Number(row.find('.discount').val());
// Validate
if (isNaN(amount) || isNaN(listprice) || isNaN(discount))
{
return; // may want to display an error message?
}
// Calculate
var finalPrice = amount * listprice * ((100 - discount) / 100)
// Update
row.find('.price').val(finalPrice);
})
A few things to note:
*
*Duplicate id attributes are invalid html - remove all your new {
@id = ".." code.
*Because of your class names, you can now style the widths - e.g.
.price { width: 95px; }
*Convert the values to a Number and check
that the value is valid using isNaN before doing the calculation
*Since Price is a calculated field, it should not be editable in the
view (or have a setter in the model. Use a <div> or similar
element to display it (and then use
row.find('.price').text(finalPrice); to set it
Note also that .on() is not necessary unless your dynamically adding those elements after the view has been first generated. | unknown | |
d9177 | train | I guess you can join these tables and create a view into which the data obtained fom the joined tables can be saved. Now the search must be conducted on this view which will speed up the search.
For eg.
mysql> SELECT CONCAT(UPPER(supplier_name), ' ', supplier_address) FROM suppliers;
+-----------------------------------------------------+
| CONCAT(UPPER(supplier_name), ' ', supplier_address) |
+-----------------------------------------------------+
| MICROSOFT 1 Microsoft Way |
| APPLE, INC. 1 Infinate Loop |
| EASYTECH 100 Beltway Drive |
| WILDTECH 100 Hard Drive |
| HEWLETT PACKARD 100 Printer Expressway |
+-----------------------------------------------------+
CREATE VIEW suppformat AS
SELECT CONCAT(UPPER(supplier_name), ' ', supplier_address) FROM suppliers;
mysql> SELECT * FROM suppformat;
+-----------------------------------------------------+
| CONCAT(UPPER(supplier_name), ' ', supplier_address) |
+-----------------------------------------------------+
| MICROSOFT 1 Microsoft Way |
| APPLE, INC. 1 Infinate Loop |
| EASYTECH 100 Beltway Drive |
| WILDTECH 100 Hard Drive |
| HEWLETT PACKARD 100 Printer Expressway |
+-----------------------------------------------------+
Please check this link which will give you some idea of views
[http://www.techotopia.com/index.php/An_Introduction_to_MySQL_Views][1]
[1]: http://www.techotopia.com/index.php/An_Introduction_to_MySQL_Views | unknown | |
d9178 | train | I figured out where I was missing. In the User Defined Java Class, in the Parameters tab below, I need to explicitly define the field name and it's alias, such as: | unknown | |
d9179 | train | The accepted answer at Saving Android Activity state using Save Instance State is the way to go.
Use onSaveInstanceState to save a boolean flag indicating whether the spinner is disabled, then read the flag in onCreate (or onRestoreInstanceState) and disable the spinner as necessary.
If you give your views an android:id in the XML layout and don't explicitly set android:saveEnabled to false, their "state" will be saved and restored automatically. For example, for text views, this includes the text currently in the view and the position of the cursor. It appears the enabled/disabled status is not part of this "state", however.
A: How does System retains ListView scroll posion automatically?
You may have noticed that some data does not get affected during rotation even if you have not handled it onSaveInstanceState method. For example
*
*Scrollposition Text in EditText
*Text in EditText etc.
What happens when the screen rotates?
When the screen rotates System kills the instance of the activity and recreates a new instance. System does so that most suitable resource is provided to activity for different configuration. Same thing happens when a full activity goes in multipane Screen.
How does system recreates a new Instance?
System creates a new instance using old state of the Activity instance called as "instance state". Instance State is a collection of key-value pair stored in Bundle Object.
By default System saves the View objects in the Bundle for example.
eg Scroll position EditText etc.
So if you want to save additional data which should survive orientation change you should override onSaveInstanceState(Bundle saveInstanceState) method.
Be careful while overriding onSaveInstance method!!!
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
Always call the super.onSaveInstanceState(savedInstanceState) ekse the default behavior will not work. ie EditText value will not persist during orientation. Dont beleive me ? Go and check this code.
Which method to use while restoring data?
*
*onCreate(Bundle savedInstanceState)
OR
*
*onRestoreInstanceState(Bundle savedInstanceState)
Both methods get same Bundle object so it does not really matter where you write your restoring logic. The only difference is that in onCreate(Bundle savedInstanceState) method you will have to give a null check while it is not needed in the latter case.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTextView = (TextView) findViewById(R.id.main);
if (savedInstanceState != null) {
CharSequence savedText = savedInstanceState.getCharSequence(KEY_TEXT_VALUE);
mTextView.setText(savedText);
}
}
OR
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can restore the view hierarchy
super.onRestoreInstanceState(savedInstanceState);
// Restore state members from saved instance
mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
}
Always call super.onRestoreInstanceState(savedInstanceState) so that
System restore the View hierarchy by default.
A: <activity
android:name="com.rax.photox.searchx.MainActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
It worked for me perfectly | unknown | |
d9180 | train | write may return partial write especially using operations on sockets or if internal buffers full. So good way is to do following:
while(size > 0 && (res=write(fd,buff,size))!=size) {
if(res<0 && errno==EINTR)
continue;
if(res < 0) {
// real error processing
break;
}
size-=res;
buf+=res;
}
Never relay on what usually happens...
Note: in case of full disk you would get ENOSPC not partial write.
A: You need to check errno to see if your call got interrupted, or why write() returned early, and why it only wrote a certain number of bytes.
From man 2 write
When using non-blocking I/O on objects such as sockets that are subject to flow control, write() and writev() may write fewer bytes than requested; the return value must be noted, and the remainder of the operation should be retried when possible.
Basically, unless you are writing to a non-blocking socket, the only other time this will happen is if you get interrupted by a signal.
[EINTR] A signal interrupted the write before it could be completed.
See the Errors section in the man page for more information on what can be returned, and when it will be returned. From there you need to figure out if the error is severe enough to log an error and quit, or if you can continue the operation at hand!
This is all discussed in the book: Advanced Unix Programming by Marc J. Rochkind, I have written countless programs with the help of this book, and would suggest it while programming for a UNIX like OS.
A: Writes shouldn't have any reason to ever write a partial buffer afaik. Possible reasons I could think of for a partial write is if you run out of disk space, you're writing past the end of a block device, or if you're writing to a char device / some other sort of device.
However, the plan to retry writes blindly is probably not such a good one - check errno to see whether you should be retrying first. | unknown | |
d9181 | train | To get an external caller of Tcl to see a result code, you need exit and not return:
# In Tcl
exit 2
Then your caller can use the exit code handling built into it to detect. For example with bash (and most other Unix shells):
# Not Tcl, but rather bash
tclsh foo.tcl
echo "exit code was $?"
On Windows, I think it's something to do with ERRORLEVEL but it's a long time since I used that platform for that sort of thing. I just remember it being annoying…
A: It appears %ERRORLEVEL% is what you want:
C:\Users\glennj>tclsh
% exit 3
C:\Users\glennj>echo %ERRORLEVEL%
3 | unknown | |
d9182 | train | As a matter of fact there are. Here is the first hit for a Google search:
*
*Cocoa Dev Central: Wrapping UNIX Commands
What you're looking for is the NSTask class. Check out the documentation for all the information you need.
A: For very simple scripts, I recommend Platypus. For more complicated scenarios, you could try something like Pashua. | unknown | |
d9183 | train | To frameless window in linux use Qt::FramelessWindowHint like this :
QDialog *dialog = new QDialog();
dialog->setWindowFlags( Qt::FramelessWindowHint );
dialog->show();
Tested on :
Qt Creator 4.3.1
Based on Qt 5.9.0 (GCC 5.3.1 20160406 (Red Hat 5.3.1-6), 64 bit)
Ubuntu 16.04 LTS | unknown | |
d9184 | train | try {
PdfReader pdfReader = new PdfReader(String.valueOf(file));
pdfReader.isEncrypted();
} catch(IOException) {
e.printStackTrace();
}
A: Starting from iText 2.0.0 you need the BouncyCastle jars. You need to download it from its site. More info can be found from here:
java.lang.NoClassDefFoundError | unknown | |
d9185 | train | Doing composer update fixed this for me.
Apparently there is an issue in version 5.5.7 of laravel/framework
Update to 5.5.8^ to fix this.+
https://github.com/laravel/framework/pull/21261 | unknown | |
d9186 | train | No, I wouldn't recommend regex, I strongly recommend build on what you have right now with the use of this beautiful HTML Parser. You could use ->replaceChild in this case:
$dom = new DOMDocument;
$dom->loadHTML($getVal);
$xPath = new DOMXPath($dom);
$spans = $xPath->query('//span');
foreach ($spans as $span) {
$class = $xPath->evaluate('string(./@class)', $span);
if(strpos($class, 'ice-ins') !== false || $class == '') {
$span->parentNode->removeChild($span);
} elseif(strpos($class, 'ice-del') !== false) {
$span->parentNode->replaceChild(new DOMText($span->nodeValue), $span);
}
}
$newString = $dom->saveHTML();
A: More generic solution to delete any HTML tag from a DOM tree use this;
$dom = new DOMDocument;
$dom->loadHTML($getVal);
$xPath = new DOMXPath($dom);
$tagName = $xPath->query('//table'); //use what you want like div, span etc.
foreach ($tagName as $t) {
$t->parentNode->removeChild($span);
}
$newString = $dom->saveHTML();
Example html:
<html>
<head></head>
<body>
<table>
<tr><td>Hello world</td></tr>
</table>
</body>
</html>
Output after process;
<html>
<head></head>
<body></body>
</html> | unknown | |
d9187 | train | If you want to apply usergroup access rights to all subpages of a page, there is a built in function the page properties already: Extend to Subpages.
This works in all TYPO3 versions you mentioned:
If you really want to do it with an SQL query, you need to create a small PHP script to recursively change the access rights. | unknown | |
d9188 | train | I've seen this kind of thing before. This error could be happening in the AdvancedDataGrid itself, not the itemRenderer.
See http://www.judahfrangipane.com/blog/?p=196 for more information.
If you simply want to draw something on specific rows, you might try extending the AdvancedDataGrid to override two functions:
override protected function drawHorizontalLine(s:Sprite, rowIndex:int, color:uint, y:Number):void {
// do some drawing
}
override protected function drawRowBackground(s:Sprite, rowIndex:int, y:Number, height:Number, color:uint, dataIndex:int):void {
// do some drawing
}
A: Here's the answer if anyone was looking at this..
I'm still not exactly sure what the problem was, but the AdvancedDataGrid certainly did not like me adding a Label as a child to the renderer. Here's how I got around it.. add a TextField as a child to the sprite, as shown:
var newLabel:TextField = new TextField();
newLabel.text = plan.planner.label;
newLabel.rotationZ = 270;
newLabel.visible = true;
newLabel.x = curX - (dividerWidth / 2) - ((newLabel.textHeight) / 1.5);
newLabel.y = height - (RADIUS * 2.5);
newLabel.antiAliasType = AntiAliasType.ADVANCED;
sprite.addChild(newLabel);
Hope this helps someone! | unknown | |
d9189 | train | The memory limit is hit because you are trying to load the whole csv in memory. An easy solution would be to read the files line by line (assuming your files all have the same structure), control it, then write it to the target file:
filenames = ["file1.csv", "file2.csv", "file3.csv"]
sep = ";"
def check_data(data):
# ... your tests
return True # << True if data should be written into target file, else False
with open("/path/to/dir/result.csv", "a+") as targetfile:
for filename in filenames :
with open("/path/to/dir/"+filename, "r") as f:
next(f) # << only if the first line contains headers
for line in f:
data = line.split(sep)
if check_data(data):
targetfile.write(line)
Update: An example of the check_data method, following your comments:
def check_data(data):
return data[n] == 'USA' # < where n is the column holding the country
A: Here is the elegant way of using pandas to combine a very large csv files.
The technique is to load number of rows (defined as CHUNK_SIZE) to memory per iteration until completed. These rows will be appended to output file in "append" mode.
import pandas as pd
CHUNK_SIZE = 50000
csv_file_list = ["file1.csv", "file2.csv", "file3.csv"]
output_file = "./result_merge/output.csv"
for csv_file_name in csv_file_list:
chunk_container = pd.read_csv(csv_file_name, chunksize=CHUNK_SIZE)
for chunk in chunk_container:
chunk.to_csv(output_file, mode="a", index=False)
But If your files contain headers than it makes sense to skip the header in the upcoming files except the first one. As repeating header is unexpected. In this case the solution is as the following:
import pandas as pd
CHUNK_SIZE = 50000
csv_file_list = ["file1.csv", "file2.csv", "file3.csv"]
output_file = "./result_merge/output.csv"
first_one = True
for csv_file_name in csv_file_list:
if not first_one: # if it is not the first csv file then skip the header row (row 0) of that file
skip_row = [0]
else:
skip_row = []
chunk_container = pd.read_csv(csv_file_name, chunksize=CHUNK_SIZE, skiprows = skip_row)
for chunk in chunk_container:
chunk.to_csv(output_file, mode="a", index=False)
first_one = False
A: You can convert the TextFileReader object using pd.DataFrame like so: df = pd.DataFrame(chunk), where chunk is of type TextFileReader. You can then use pd.concat to concatenate the individual dataframes. | unknown | |
d9190 | train | I solved the issue by adding type="audio/mpeg" to the audio tag. | unknown | |
d9191 | train | Your list item layout file name is list_item but i think you are not giving the correct id for textview. Here
TextView textView = (TextView) rowView.findViewById(R.id.list_item);
Make double sure you text view id in xml file is list_item (i dont think so).
In that case just change it to correct id and it will work hopefully.
A: The error is a NullPointerException on Line 77 is ( Please, avoid using an image for share the error log, text is better ). That line is:
textView.setText(values[position]);
I assumed that you don't pass a null array to constructor, so the other possible NullExcepction problem is in textView. I would said that textView is null. Can you check that? | unknown | |
d9192 | train | I found solution in placing this code before </body> tag:
<script type="text/javascript">
const head = document.head, link = document.createElement("link");
link.type = "text/css";
link.rel = "stylesheet";
link.href = "/dist/vendor.css";
head.appendChild(link);
</script>
But it does not explain Chrome (possible other browsers too) behaviour I described in question. | unknown | |
d9193 | train | This paragraph recently added to our Quarkus documentation should help you with this: https://quarkus.io/guides/reactive-sql-clients#transactions .
It specifically explains how to deal with transactions when using the Reactive SQL clients. | unknown | |
d9194 | train | In my opinion the GET params are the simplest way to do it, and I don't think there are important security implications.
A: You should assume anything that web app A puts in the redirect can be read/stolen/modified/spoofed before it gets to web app B (unless you are using SSL on both app A and B). If this isn't a problem then putting the params on the redirect URL should do you fine.
A secure way would be for app A to generate a unique ID (non guessable and short lived) and to store the info against this ID. The ID is passed with the request to app B. Server B then accesses the data from server A using the ID in a private secure way, for example be calling a web service on server A that is not publically accessible. | unknown | |
d9195 | train | You can achieve that using custom IEqualityComparer<byte[]> (or even better, generic one: IEqualityComparer<T[]>) implementation:
class ArrayComparer<T> : IEqualityComparer<T[]>
{
public bool Equals(T[] x, T[] y)
{
return x.SequenceEqual(y);
}
public int GetHashCode(T[] obj)
{
return obj.Aggregate(string.Empty, (s, i) => s + i.GetHashCode(), s => s.GetHashCode());
}
}
I'm pretty sure GetHashCode could be implemented much better, but it's just an example!
Usage:
var grouped = source.GroupBy(i => i.Item3, new ArrayComparer<byte>()) | unknown | |
d9196 | train | List<> isn't a great choice in concurrency - there are out of the box alternatives, like ConcurrentBag, ConcurrentQueue which already have a lot of hard work done for you.
Here's an implementation of a producer-consumer pattern, using a BlockingCollection implementation as per MSDN,
*
*The BlockingCollection is backed with a ConcurrentQueue, assuming that we are serially pull data in sequence on the consumer.
*Methods which iterate over BlockingCollection block (with little overhead) until an item is available (i.e. your 'pause' is inherent - no need for a looped check with Thread.Sleeps on the consumer).
*Termination is inherently built in, when the producer calls CompletedAdding
*If you have more than one concurrent (competing) consumer, only one consumer will get an item, i.e. the duplication condition shouldn't be a concern (unless you mean the producer actually adds duplicates in the first place).
var queue = new BlockingCollection<string>(new ConcurrentQueue<string>());
var producer = Task.Run(() =>
{
// Produce some random messages, with delays in between
queue.Add("Hello!");
Thread.Sleep(1000);
queue.Add("World!");
Thread.Sleep(2000);
Enumerable.Range(0, 100)
.ToList()
.ForEach(x => queue.Add(x.ToString()));
queue.CompleteAdding();
});
var consumer = Task.Run(() =>
{
while (!queue.IsCompleted)
{
try
{
Debug.WriteLine(queue.Take());
}
catch (InvalidOperationException)
{
}
}
});
Task.WaitAll(producer, consumer); | unknown | |
d9197 | train | I would use shutil. Is there a problem with that ?
Personally I tend to use:
shutil.copytree(src, dst, symlinks=False, ignore=None)
as it takes subdirs
update------
To get the current working directory use
os.getcwd() | unknown | |
d9198 | train | In my case, the old audience network plugin caused the problem. Build failed when both Audience network and AdMob were present. After removing the audience network plugin (as I am not using it), the build was successful.
Update SDK, and other plugins. Resolve, and then try again.
A: Solution
The AdMob SDK requires use of the <queries> tag which for Unity 2018 and higher needs a newer Gradle feature which doesn't come with the Gradle version Unity packages.
Here is another post with the same issue.
A: Tested : Unity 2020.3.11f1 and GoogleMobileAds-v6.1.2
Step 01 : Install GoogleMobileAds plugin and setup and Asset > External Dependency Manager > Android Resolver > resolve.
Step 02 : Set Target API Level 30 in Player Setting.
enter image description here
Step 03 : Tick in Custom Main Gradle Template and Custom Launcher Gradle Template.
enter image description here
Step 04: How mainTemplate and launcherTemplate files generating. [If not view then first build ignore the errors]
enter image description here
Step 05 : Added below code into mainTemplate.gradle file with your favorite editor.
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
// Must be Android Gradle Plugin 3.6.0 or later. For a list of
// compatible Gradle versions refer to:
// https://developer.android.com/studio/releases/gradle-plugin
classpath 'com.android.tools.build:gradle:3.6.0'
}
}
allprojects {
repositories {
google()
mavenCentral()
flatDir {
dirs 'libs'
}
}
}
//Look like that
enter image description here
Step 06 : Download Gradle gradle-5.6.4-all.zip from grdale.org. Download from https://services.gradle.org/distributions/
After download extract the file and set gradle path into Edit > Preference > External Tools > Gradle Install with Unity(recommended) UnChecked
enter image description here
Step 07 : Build
Helpful Link : https://developers.google.com/ar/develop/unity-arf/android-11-build | unknown | |
d9199 | train | regarding your first question
if i have reloaded the website except of root url, i got an error "cannot get /... "
this is expected since when you navigate through the router links then Javascript runs and manipulates the URL in the address bar, without causing a page refresh, which in turn does a page transition
the solution is to do a "catch-all" route
just set up a catch-all on the server that sends all request to the index index.html
something like this
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname, '/../../client/build', 'index.html'));
});
but make sure to do this route after your rest api
regarding the second question it quite unclear and if i want to take a guess i think the handler of the request get stuck and does not respond to the client until you end it | unknown | |
d9200 | train | As per our discussion below are my Steps:
*
*Override Role with company OR you can keep this at Super Admin level.
http://127.0.0.1:8000/admin/auth/role/
*Add separate table for permissions with pk, client ID, RoleID , add, edit, view, delete, model, action (URL) columns
*Add decorator for each of the action or Model and check permissions for that particular action or model.
*Check roles and permission in Admin using common function something like check_role_permissions_admin
//Add below function in separate / common function file.
def check_role_permissions_admin(request, url=None):
if not hasattr(request.user,"client"):
return {
'clientwise': False,
'add': False,
'change': False,
'delete': False,
'view': False,
'icon': ''
}
super_admin_role = Role.objects.get(pk=1)
all_roles = request.user.groups.all()
try:
action = Actions.objects.get(
url=url
)
except:
action = None
if super_admin_role in all_roles:
return {
'clientwise': False,
'add': True,
'change': True,
'delete': True,
'view': True,
'icon': str(action.icon) if action else ''
}
// Write Logic here for Role and Permissions of requested action(s)
roles = [group for group in request.user.groups.all()]
permissions = ActionPermissions.objects.filter(
client=request.user.client,
role__in=roles,
action__url=url
)
if permissions.exists():
permobj = permissions[0]
return {
'clientwise': True if permobj.client else False,
'add': True if permobj.add else False,
'change': True if permobj.change else False,
'delete': True if permobj.delete else False,
'view': True if permobj.view else False,
'icon': permobj.action.icon
}
else:
return {
'clientwise': False,
'add': False,
'change': False,
'delete': False,
'view': False,
'icon': ''
}
//Add below code in admin.py, for every admin action you need to do following //thing and need
//to make sure that similar entry is added in table permissions.
from module.function import check_role_permissions_admin
@admin.register(ConfigRuleMaster)
class ModelMasterAdmin(admin.ModelAdmin):
action_form=CustomActionForm
form = ModelMasterForm
fields=(('title','template'))
list_display=('title','template')
search_fields = ('title','template',)
list_display_links = []
def get_model_perms(self, request):
perms = decorators.check_role_permissions_admin(request, '/admin/lmt/modelmaster/')
perms['clientwise'] = False
return perms
def has_add_permission(self, request):
perms = decorators.check_role_permissions_admin(request, '/admin/lmt/modelmaster/')
return perms['add']
def has_change_permission(self, request, obj=None):
perms = decorators.check_role_permissions_admin(request, '/admin/lmt/modelmaster/')
return perms['change']
*Another work is to handle actions through decorators.
But this is very raw version of code I found in my repository, you need to make this logic at very high level to make your client happy and to have full secured code. | unknown |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.