text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: Get Recent App Button Clicked in Launcher App I am writing a launcher application which will launch other apps on its OnCreate method. Following is the code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
......
Intent i = PckManager.getLaunchIntentForPackage("com.app.myApp");
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS | Intent.FLAG_ACTIVITY_NO_ANIMATION);
LaunchMe.this.startActivity(i);
Now on OnResume of LauncherApp, I am restarting my desired app to be remain at top using following code:
protected void onResume() {
Intent i = PckManager.getLaunchIntentForPackage("com.yego.motodriver");
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS | Intent.FLAG_ACTIVITY_NO_ANIMATION);
i.setAction(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_LAUNCHER);
LaunchMe.this.startActivity(i);
super.onResume();
}
This ensures that MyApp will always remain on top of the activities when user clicked Home or Back button of device.
But when user clicks RecentApp button of device, I could not get any event fire in LauncherApp Neither OnResume nor OnPause or OnWindowFocusedChanged.
I need to stop the user to get into the Recent Acitivities tab and want MyApp to always remain on the top of the activities.
I have Checked some apps like SureLock and GoKiosk able to prevent the user from going into Recent App tab. How do they manage this?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43994971",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: C++ throw() optimization According to Optimizing C++,
Use the empty exception specification (that is, append throw() to the declaration) for the functions you are sure will never throw exceptions.
What if I know that 90% of my methods won't throw an exception? It seems unconventional and verbose to append throw() to all of those methods. If not, what are the advantages? Or am I misunderstanding something here?
A: C++11 has introduced noexcept, throw is somewhat deprecated (and according to this less efficient)
noexcept is an improved version of throw(), which is deprecated in C++11. Unlike throw(), noexcept will not call std::unexpected and may or may not unwind the stack, which potentially allows the compiler to implement noexcept without the runtime overhead of throw().
When an empty throw specification is violated, your program is terminated; this means you should only declare your functions as non throwing, only when they have a no throw exception guarantee.
Finally you need a move constructor to be non throwing (specified with noexcept) to be able to use the r-value ref version of std::vector<T>::push_back (see a better explanation here)
A: The standard throw() doesn't enhance optimizability.
If a method is marked as throw() then the compiler is forced to check if an exception is thrown from the method and unwind the stack - just like if the function is not marked as throw(). The only real difference is that for a function marked throw() the global unexpected_handler will be called (which generally calls terminate()) when the exception leaves the function, unwinding the stack to that level, instead of the behavior for functions without an exception specification which will handle the exception normally.
For pre-C++11 code, Sutter & Alexandrescu in "C++ Coding Standards" suggested:
Avoid exception specifications.
Take exception to these specifications: Don’t write exception
specifications on your functions unless you’re forced to (because
other code you can’t change has already introduced them; see
Exceptions).
...
A common but nevertheless incorrect belief is that exception
specifications statically guarantee that functions will throw only
listed exceptions (possibly none), and enable compiler optimizations
based on that knowledge
In fact, exception specifications actually do something slightly but
fundamentally different: They cause the compiler to inject additional
run-time overhead in the form of implicit try/catch blocks around the
function body to enforce via run-time checking that the function does
in fact emit only listed exceptions (possibly none), unless the
compiler can statically prove that the exception specification can
never be violated in which case it is free to optimize the checking
away. And exception specifications can both enable and prevent further
compiler optimizations (besides the inherent overhead already
described); for example, some compilers refuse to inline functions
that have exception specifications.
Note that in some versions of Microsoft's compilers (I'm not sure if this behavior has changed in more recent versions, but I don't think so), throw() is treated in a non-standard way. throw() is equivalent to __declspec(nothrow) which does allow the compiler to assume that the function will not have an exception thrown and undefined behavior will result if one is.
C++11 deprecates the C++98 style exception specification and introduced the noexcept keyword. Bjarne Stroustup's C++11 FAQ says this about it:
If a function declared noexcept throws (so that the exception tries to
escape, the noexcept function) the program is terminated (by a call to
terminate()). The call of terminate() cannot rely on objects being in
well-defined states (i.e. there is no guarantees that destructors have
been invoked, no guaranteed stack unwinding, and no possibility for
resuming the program as if no problem had been encountered). This is
deliberate and makes noexcept a simple, crude, and very efficient
mechanism (much more efficient than the old dynamic throw()
mechanism).
In C++11 if an exception is thrown from a function marked as noexcept the compiler is not obligated to unwind the stack at all. This affords some optimization possibilities. Scott Meyers discusses the new noexcept in his forthcoming book "Effective Modern C++".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26789046",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Does the global keyword inline the global exactly as a local variable declaration in python? So are these two exactly equivalent vis a vis performance (that is, is the generated code exactly equivalent):
class A(object):
const = 'abc'
def lengthy_op(self):
const = self.const
for i in xrange(AVOGADRO):
# do something which involves reading const
and:
const = 'abc'
class A(object):
def lengthy_op(self):
global const
for i in xrange(AVOGADRO):
# do something which involves reading const
A: No they are not exactly equivalent, although the difference is unlikely to be significant.
class A(object):
const = 'abc'
def lengthy_op(self):
const = self.const
for i in xrange(AVOGADRO):
# do something which involves reading const
This creates a local variable so any access of const will use the LOAD_FAST opcode.
const = 'abc'
class A(object):
def lengthy_op(self):
# global const
for i in xrange(AVOGADRO):
# do something which involves reading const
This, with or without the redundant global const uses LOAD_GLOBAL to access the value of the global variables const, xrange, and AVOGADRO.
In C Python LOAD_GLOBAL will perform a fast dictionary lookup to access the variable (fast because the global variables are in a dictionary using only string keys and the hash values are pre-calculated). LOAD_FAST on the other hand simply accesses the first, second, third etc. local variables which is an array indexing operation.
Other versions of Python (e.g. PyPy) may be able to optimise accessing the global variable in which case there may not be any difference at all.
The first code (with n=i+const as the loop body) disassembles to:
>>> dis.dis(A.lengthy_op)
5 0 LOAD_FAST 0 (self)
3 LOAD_ATTR 0 (const)
6 STORE_FAST 1 (const)
6 9 SETUP_LOOP 30 (to 42)
12 LOAD_GLOBAL 1 (xrange)
15 LOAD_GLOBAL 2 (AVOGADRO)
18 CALL_FUNCTION 1
21 GET_ITER
>> 22 FOR_ITER 16 (to 41)
25 STORE_FAST 2 (i)
8 28 LOAD_FAST 2 (i)
31 LOAD_FAST 1 (const)
34 BINARY_ADD
35 STORE_FAST 3 (n)
38 JUMP_ABSOLUTE 22
>> 41 POP_BLOCK
>> 42 LOAD_CONST 0 (None)
45 RETURN_VALUE
while the second block gives:
>>> dis.dis(A.lengthy_op)
5 0 SETUP_LOOP 30 (to 33)
3 LOAD_GLOBAL 0 (xrange)
6 LOAD_GLOBAL 1 (AVOGADRO)
9 CALL_FUNCTION 1
12 GET_ITER
>> 13 FOR_ITER 16 (to 32)
16 STORE_FAST 1 (i)
7 19 LOAD_FAST 1 (i)
22 LOAD_GLOBAL 2 (const)
25 BINARY_ADD
26 STORE_FAST 2 (n)
29 JUMP_ABSOLUTE 13
>> 32 POP_BLOCK
>> 33 LOAD_CONST 0 (None)
36 RETURN_VALUE
Python won't make a local copy of the global because there is no easy way to be sure that the global value won't change while the code is running. Anything, even another thread or a debugger, could modify the value while the loop is executing.
A: Whether it is faster or slower actually depends on your scope, the scopes are stored in dictionaries and the smaller the dictionary is the (marginally) faster the access will be. Since dictionaries are implemented as hashsets the lookup performance is O(1).
Whenever you try to access a variable Python will walk the scopes in this order:
*
*Local. The local namespace which is the current function scope.
*Enclosing function locals. Depending on the amount of nested functions/lambda's there can be more of these.
*Global. The global scope which is just another dictionary (which you can access through globals())
*Built-ins. The standard Python built-ins that are available in all scopes such as list, int, etc..
Accessing a function/class attribute works in a similar fashion but involves:
*
*__getattribute__
*__dict__
*__getattr__
And that over all inherited classes as well.
The rest of your question was answered perfectly by Duncan
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36178330",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Instantiation of a template for local variable Is a template instantiated if a local automatic variable of that type is defined?
e.g.
template<typename T> class MyClass {
};
int main() {
MyClass<int> var; // Does this cause instantiation?
}
Edit:
the reason why I'm asking this is the following code:
template<typename T> class get_false { public:
static constexpr bool val = false;
};
template<typename T>
class MyClass_2 {
static_assert(get_false<T>::val, "Failure");
};
template<typename T, typename U = MyClass_2<T>>
class MyClass {};
int main() {
MyClass<bool> obj; // I suppose this isn't instantiated
}
A: Yes, it is instantiated.
#include <iostream>
template<typename T>
class MyClass {
public:
MyClass() {
std::cout << "instantiated" << std::endl;
}
};
int main() {
MyClass<int> var;
}
The program outputs "instantiated" ⇒ the MyClass constructor is called ⇒ the var object is instantiated.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30666863",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Tensorflow with Keras: sparse_categorical_crossentropy I'm new on StackOverflow and I also recently started to work with Tensorflow and Keras. Currently I'm developing an architecture using LSTM units. My question was partially discussed here:
What does the implementation of keras.losses.sparse_categorical_crossentropy look like?
However, in my model I have a predicted tensor, y_hat, of size (batch_size, seq_length, vocabulary_dimension) and the true labels, y, of size (batch_size, seq_length).
I would like to know how the value of the loss is computed when I call
loss = sparse_categorical_crossentropy(y,y_hat): how does the sparse_crossentropy function calculate the loss value starting from two tensors of different dimensions?
A: The cross entropy is a way to compare two probability distributions. That is, it says how different or similar the two are. It is a mathematical function defined on two arrays or continuous distributions as shown here.
The 'sparse' part in 'sparse_categorical_crossentropy' indicates that the y_true value must have a single value per row, e.g. [0, 2, ...] that indicates which outcome (category) was the right choice. The model then outputs the y_pred that must be like [[.99, .01, 0], [.01, .5, .49], ...]. Here, model predicts that the 0th category has a chance of .99 in the first row. This is very close to the true value, that is [1,0,0]. The sparse_categorical_crossentropy would then calculate a single number with two distributions using the above mentioned formula and return that number.
If you used a 'categorical_crossentropy' it would expect the y_true to be a one-hot encoded vector, like [[0,0,1], [0,1,0], ...].
If you would like to know the details in depth, you can take a look at the source.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63527580",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Enhance Localization performances? (ComponentResourceManager.ApplyResources) After experiencing some performances issues on my client side, we decided to give a try to some of the performance profilers to try to find the bottleneck or identify the guilty parts of the code.
Of course, as many performance investigations, the problems comes from various things, but something I find out is that the ComponentResourceManager.ApplyResources of my user controls takes way too much time in the construction of my forms: more than 24% of the construction time is spent in the ApplyResources inside the InitializeComponent().
This seems rather a lot for only "finding a resource string and putting it in it's container".
What is exactly done in the ComponentResourceManager.ApplyResources ? I guess more than searching the string, if not it wouldn't take that long.
Is there a way to enhance the performances of the localization? Our software is localized in several languages, so we do need to keep this multi-lingual feature.
Any recommendations regarding this issue?
Thanks!
PS: We are coding in C#, .NET 3.5 SP1.
A: The ApplyResources method uses reflection to find the properties which will be updated with the resource values:
property = value.GetType().GetProperty(name, bindingAttr);
Reflection is notoriously slow. Assign the resource values by hand to the properties (e.g using ResourceManager.GetString(...)). This is tedious to code, but should improve the performance.
A: I would grab Reflector and take a look at the ApplyResources method to see what it actually does.
I would also recommend profiling using JetBrains dotTrace 4 (currently in EAP but trials can be downloaded), as it can also show times spent inside system classes. This makes it much more transparent where the time is actually spent. For instance, you can find out whether the time is spent looking up keys in a dictionary, accessing files, etc.
You could also do a micro benchmark and measure the time it takes to look up X keys in a Y-sized dictionary of strings, with X being the number of localized resources on a particular form and Y being the total resource pool. It will at least give you an idea of how fast you could look up the resources if you were to cache them in a dictionary, which may help you decide whether it is worthwhile to write your own resource provider.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2604720",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: CSS problem with divs and inline components Imagine a code like this:
.div {
width: 100%;
height: 100px;
background-color: green;
}
.div1 {
width: 100px;
height: 100px;
background-color: red;
}
.div2 {
width: 100px;
height: 100px;
background-color: blue;
}
.main {
background-color: yellow;
}
<div class="main">
<div>
<div class="div"></div>
<div class="div1"></div>
</div>
<div class="div2"></div>
</div>
It will render something like this:
I want that the blue div comes up and stay on the right of the red div. Imagine that I can´t change the divs from where they are, so I need to do it in css. How can I do it?
A: Without changing the markup, if you set float: left to the red <div> then you could put the blue <div> to its right side
.div {
width: 100%;
height: 100px;
background-color: green;
}
.div1 {
width: 100px;
height: 100px;
background-color: red;
float: left;
}
.div2 {
width: 100px;
height: 100px;
background-color: blue;
display: inline-block;
vertical-align: top;
}
.main {
background-color: yellow;
}
<div class="main">
<div>
<div class="div"></div>
<div class="div1"></div>
</div>
<div class="div2"></div>
</div>
A: The previous solution which uses float on the red div works well, but here is another possible solution:
Apply position: relative; to the blue div (to be able to move it in relation to its default position) and add top: -100px; left: 100px; to move it up next to the red div:
.div {
width: 100%;
height: 100px;
background-color: green;
}
.div1 {
width: 100px;
height: 100px;
background-color: red;
}
.div2 {
width: 100px;
height: 100px;
background-color: blue;
position: relative;
top: -100px;
left: 100px;
}
.main {
background-color: yellow;
}
<div class="main">
<div>
<div class="div"></div>
<div class="div1"></div>
</div>
<div class="div2"></div>
</div>
A: This can also be done with the grid CSS. Here I used a named template box and then in the "chatty verbose" CSS I put the positional related for each "block". I added classes to the CSS just for clarity but you could update to your classes.
I added some color and things just for clarity and visual references but kept the "position relate" in separate CSS chunks.
.main {
font-size: 2rem;
display: grid;
grid-template: "box";
background-color: yellow;
}
.main *,
.main::before {
grid-area: box;
}
.green-block {
place-self: start;
}
.red-block {
width: 50%;
place-self: end start;
}
.blue-block {
width: 50%;
place-self: end end;
}
.green-block {
height: 3rem;
background-color: green;
}
.red-block {
height: 3rem;
background-color: red;
}
.blue-block {
background-color: blue;
}
.blue-block,
.green-block,
.red-block {
/* color for clarity and just to super center the text in the blocks */
display: grid;
color: cyan;
font-family: sans-serif;
text-transform: uppercase;
place-items: center;
}
<div class="main">
<div>
<div class="div green-block">green</div>
<div class="div1 red-block">red</div>
</div>
<div class="div2 blue-block">blue</div>
</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75364170",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Wordpress Customizer With External CSS File Is It possible Wordpress Customizer to create Dynamic CSS file and use it as external css file instead of Inlining it in header with function
add_action( 'wp_head', 'custom_css');
I need to make Header More Clean as it contains lots of CSS in header right now..
A: Some solution is to create PHP file which returns CSS code based on the variables provided via the GET parameters.
BUT:
1) You have to prepare a very strict sanitization as inproper value filtering can lead to security vulnerabilities,
2) The list of params cannot be too long as servers can have limits for the maximum URL length.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38922350",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: drools can't get the data I need for the or condition rule "151"
when
$master:BusinessMaster()
$map:HashMap() from $master.indexMap
$mapads_mst_bas_info:HashMap() from $map.get("ads_mst_bas_info")
$mapads_mst_order_mutl_stat4:HashMap() from $map.get("ads_mst_order_mutl_stat4")
$resultMap:HashMap((( $mapads_mst_bas_info.get("mst_integral") >= 500 && <= 5000 ) || ( $mapads_mst_order_mutl_stat4.get("current_mon_bad_rate_num") >= 1 && <= 2 )) && ($mapads_mst_bas_info.get("remain_amount")>=5000)) from $master.indexMap
then
$master.getMasterLabel().add("151");
insert($master);
end
This rule is the same as the following rule:
rule "151"
when
$master:BusinessMaster()
$map:HashMap() from $master.indexMap
$mapads_mst_bas_info:HashMap() from $map.get("ads_mst_bas_info")
$mapads_mst_order_mutl_stat4:HashMap() from $map.get("ads_mst_order_mutl_stat4")
$resultMap:HashMap((( $mapads_mst_bas_info.get("mst_integral") >= 500 && <= 5000 ) || $mapads_mst_order_mutl_stat4.get("current_mon_bad_rate_num") >= 1 && $mapads_mst_order_mutl_stat4.get("current_mon_bad_rate_num") <= 2 ) && ($mapads_mst_bas_info.get("remain_amount")>=5000)) from $master.indexMap
then
$master.getMasterLabel().add("151");
insert($master);
end
Both rules have the same result
A: Your rules are identical. The only difference is a set of parentheses ( ) that don't actually matter because of order of operations / operator precedence rules.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73403814",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to fix this Node controller function and send data from 2 different models? There are 2 models booking and listing. The point is that for creating a booking we need to use listing details too and send all the details through the Nodemailer after the saving details in DB. here is the code:
Listing model:
const listingSchema = new Schema({
bbusinessEmail: {
type: String,
},
title: { type: String, required: true, max: [128, 'Too long, max is 128 characters']},
city: { type: String, required: true, lowercase: true },
street: { type: String, required: true, min: [4, 'Too short, min is 4 characters']},
bookings: [{ type: Schema.Types.ObjectId, ref: 'Booking' }]
});
...
Booking model:
const bookingSchema = new Schema({
customerEmail: {
type: String,
match: [/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/]
},
days: Number,
listing: { type: Schema.Types.ObjectId, ref: 'Listing'},
Controller:
exports.bookListing = async (req, res) => {
if(!req.body.content) {
return res.status(400).send({
message: "Fields can not be empty"
});
}
const smtpTransport = nodemailer.createTransport({
service: 'Gmail',
port: 465,
auth: {
user: 'email',
pass: 'password'
}
});
const { customerEmail, businessEmail, customerPhone, startAt, listing,
totalPrice, days } = req.body;
const booking = new Booking({
customerEmail,
customerPhone,
startAt,
totalPrice,
days
});
let foundListing = await Listing.findById(listing._id).populate('bookings')
if (err) {
return res.status(422).send({message: "Error happened"});
}
booking.listing = foundListing;
foundListing.bookings.push(booking);
try {
let data = await booking.save(), foundListing.save();
var mailOptions = {
from: data.customerEmail,
to: data.businessEmail,
subject: 'Listing Request',
html: `<p>${data.startAt}</p>
<p>${data.totalPrice}</p>
<p>${data.customerPhone}</p>
<p>${data.days}</p>`
};
await smtpTransport.sendMail(mailOptions);
smtpTransport.close();
res.send(data);
} catch(err) {
res.status(500).send({
essage: err.message || "Some error occurred while creating the listing."
});
}
};
The controller gets data that includes fields from both Listing and booking models then it should save data inside the DB for both Listing and booking and then send the data through the email. How can this controller be fixed?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58267043",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Unexpected token '<' when loading coreui.bundle.min.js Every time I load the following:
<script src="~/vendor/@@coreui/coreui-pro/js/coreui.bundle.min.js"></script>
either before or after:
<script type="text/javascript"
src="~/lib/jquery/dist/jquery.min.js"></script>
I got this:
Uncaught SyntaxError: Unexpected token '<'
any suggestion?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71996369",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Ajax OnFailure function I have an AJAX.RouteLink which has the following AJAXOptions
new AjaxOptions
{
HttpMethod = "POST",
OnFailure = "OnFailure",
OnSuccess = "OnSuccess"
})
My OnFailure method looks like this
function OnFailure(ajaxContext) {
var response = ajaxContext.get_response();
var statusCode = response.get_statusCode();
var elem = document.getElementById('message');
elem.innerHTML = 'Sorry, the request failed with status code' + statusCode;
}
Problem is, when it gets called I get this error
TypeError: ajaxContext.get_response is not a function
In the watch list I can see that the responseText in ajaxContext is html.
What am I doing wrong here?
A: The problem was that ajaxContext doesn't have a get_response method. It must be an old version of the object whose example I was looking at.
Since I wanted the status code, I just used the ajaxContext.status property.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21160980",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Javascript: using a while loop to repeat a function Let's say I have a collection of divs with the class "Foo" and I want to change the colors of the text incrementally over and over. Each forEach should run this change one time but I need to run the function again to change them again.
If I want to repeat to continually run this function, what are my best options? Should I throw it in a while loop?
function colorWords() {
let textBoxes = document.querySelectorAll(".foo");
let colors = ["yellow","blue","green","red"];
textBoxes.forEach((word, index) => {
setTimeout(() => {
word.style.color = colors[Math.floor(Math.rand()*colors.length)]
}, 500 + index*250);
},
}
A: You may need setInterval.
Also replace Math.rand() with Math.random()
let colors = ["yellow", "blue", "green", "red"];
let interval
setInterval(() => {
let textBoxes = document.querySelectorAll(".foo");
textBoxes.forEach((word, index) => {
interval = index;
word.style.color = colors[Math.floor(Math.random() * colors.length)]
}, 500 + interval * 250)
})
<div class='foo'>1</div>
<div class='foo'>1</div>
<div class='foo'>1</div>
<div class='foo'>1</div>
<div class='foo'>1</div>
A: You can use setInterval to control the loop segment time. Below I've set intervals to 250ms to get an idea of how frequent the updates occur:
let INTERVAL_IDS = []
document.querySelector('#start').addEventListener('click',start)
document.querySelector('#stop').addEventListener('click',stop)
function start(){
let colors = ["yellow", "blue", "green", "red"];
let textBoxes = document.querySelectorAll(".foo");
INTERVAL_IDS.push(setInterval(function(){
textBoxes.forEach(word =>
word.style.color = colors[Math.floor(Math.random() * colors.length)]
)
},250))
}
function stop(){
clearInterval(INTERVAL_IDS.pop())
}
<button id="start">start</button><button id="stop">stop</button>
<span class='foo'>H</span>
<span class='foo'>e</span>
<span class='foo'>l</span>
<span class='foo'>l</span>
<span class='foo'>o</span>
A: Yeah, a while loop with a counter sounds reasonable. All inside of a setInterval function to fire at so many seconds.
let counter = 0
while( counter >= 10){
*your code*;
counter++
}```
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54192541",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Last-Of Type and Last-Of-Child HTML:
<div class="plan-box">
<h3>...</h3>
<p>...</p>
</div>
<div class="plan-box">
<h3>...</h3>
<p>...</p>
</div>
CSS:
.plan-box:last-of-type {
...
}
In the above CSS code if I use last-of-type or last-child css selector on .plan-box will that select the last-child in both the .plan-box div which is the paragraph or will it select the second .plan-box div in the HTML code?
A: .plan-box:last-child Selects last of plan.box element
.plan-box :last-child Selects last elements in all of plan.box elements
Css Selectors
A: It will select second .plan-box div in the HTML code.
See the Link here
Again you can easily select any child div with CSS .Example is Here
I have used here .plan-box:nth-child(2) {} for select second div.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34410927",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SVG does not fit on Iphone - (.htaccess is the problem) I am getting crazy with the animated SVG of my website ( https://finbizimpactinvesting.com ). On the desktop it works well and the SVG fits in the middle of the monitor (chrome, safari, mac, windows all the combination) as well as android devices, but on Iphone mobile devices it does not fit whatever the browser it is.
I tried to play with the viewBox but it is almost impossible to make it fit on different devices with the same output.
<div class = "logo">
<svg version="1.1" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 100 100">
<circle class="r" cx="41%" cy="41%" r="8" ></circle>
<circle class="r" cx="59%" cy="41%" r="8" ></circle>
<circle class="r" cx="41%" cy="59%" r="8" ></circle>
<circle class="r" cx="59%" cy="59%" r="8" ></circle></svg>
</div>
.logo {
position: absolute;
top: -150px;
z-index: -1;
display: inline-block;
max-width: 1225px;
height: 250px;
bottom: 0;
right: 0;
left: 0;
margin: auto;
}
.logo svg {
position: relative;
left: 0px;
top: -150px;
right: 0;
bottom: 0;
width: 250px;
margin: auto;
fill: transparent;
overflow: overlay;
}
.r {
opacity: 0;
stroke: #000000;
stroke-width: 1px;
stroke-dasharray: 130;
-webkit-animation-name: vladi;
-o-animation-name: vladi;
animation-name: vladi;
-webkit-animation-duration: 3s;
-o-animation-duration: 3s;
animation-duration: 3s;
-webkit-animation-iteration-count: 1;
-o-animation-iteration-count: 1;
animation-iteration-count: 1;
-webkit-animation-direction: alternate;
-o-animation-direction: alternate;
animation-direction: alternate;
-webkit-animation-timing-function: ease-in;
-o-animation-timing-function: ease-in;
animation-timing-function: ease-in;
-webkit-transform-origin: center center;
-o-transform-origin: center center;
transform-origin: center center;
}
@keyframes vladi {
0% {
stroke-dashoffset: 130;
stroke: #000000;
opacity: 1;
}
60% {
fill: transparent;
stroke-dashoffset: 0;
stroke: #000000;
stroke-width: 1px;
opacity: 1;
}
70% {
fill: #000000;
}
91% {
-webkit-transform: scale(1);
-o-transform: scale(1);
transform: scale(1);
opacity: 1;
}
92% {
-webkit-transform: scale(0.9);
-o-transform: scale(0.9);
transform: scale(0.9);
}
100% {
-webkit-transform: scale(2);
-o-transform: scale(2);
transform: scale(2);
fill: #000000;
}
}
Many Thanks!!!
A: I got the problem!! the issue is the .htaccess file that i am using to force the http into htpps. I don't know why but with it the Svg does not work and without it the SVG works great.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57469450",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: TypeError: config.headers.has is not a function Getting errors when executing test cases in Redux Tool Kit query,
*
*Used React Native Testing Library for rendering components.
An unhandled error occurred processing a request for the endpoint "getProducts".
In the case of an unhandled error, no tags will be "provided" or "invalidated". TypeError: config.headers.has is not a function
jestSetup.ts:
jest.useFakeTimers()
jest.mock('react-native/Libraries/Animated/NativeAnimatedHelper');
jest.mock('node-fetch');
require('jest-fetch-mock').enableMocks()
Tried with mocking node-fetch
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74347687",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to create multiple links from a single array of strings Rails - Ruby I know it might seem simple but I've tried to create multiple links from this array in Rails
array = ["/uploads/content/attachment/folder/file1.pdf/file2.pdf/file3.pdf"]
What I want to do is create a link for file1 and another for file2 and so on.
I've tried to use the join and separate method, image_tag, content_tag and many many different cycles in Rails but every single one ends up like the link above.
A: Something like this if I understood correctly:
array = ["/uploads/content/attachment/folder/file1.pdf/file2.pdf/file3.pdf"]
base = "https://www.example.com/" #the first part of the link, that's same for all links
links = array.first[1..-1].split("/").map{|a| base + a}
puts links
#=> "https://www.example.com/uploads",
# "https://www.example.com/content",
# "https://www.example.com/attachment",
# "https://www.example.com/folder",
# "https://www.example.com/file1.pdf",
# "https://www.example.com/file2.pdf",
# "https://www.example.com/file3.pdf"
A: The question is not clear.
I assume the array will be like this:
array = [
"/uploads/content/attachment/folder/file1.pdf/file2.pdf/file3.pdf",
"/uploads/content/attachment/folder/file12.pdf/file23.pdf/fildf34.pdf",
"/foo/boo/folder/file1.doc/file2.docx/file11.pdf"
]
It splits links for folder/
links = array.map{ |a| a.split('folder/') }.flat_map do |path, files|
files.split('/').map{ |file| path + "folder/" + file }
end
p links
#=> [
"/uploads/content/attachment/folder/file1.pdf",
"/uploads/content/attachment/folder/file2.pdf",
"/uploads/content/attachment/folder/file3.pdf",
"/uploads/content/attachment/folder/file12.pdf",
"/uploads/content/attachment/folder/file23.pdf",
"/uploads/content/attachment/folder/fildf34.pdf",
"/foo/boo/folder/file1.doc",
"/foo/boo/folder/file2.docx",
"/foo/boo/folder/file11.pdf"
]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58456941",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Bitmap 16bpp A1R5G5B5 to 32bpp I need to read the values R, G and B image with a bit mask for 16bpp A1R5G5B5 in PHP, I know you have to understand Bitwise, but I'm not very good in this matter, so does anyone could show me how to do this?
Sorry for the English, is that I am Brazilian and I am using a translator.
A: A1R5G5B5 Bitmasks:
ARRR RRGG GGGB BBBB
ALPHA: 1000 0000 0000 0000 - 0x8000
RED: 0111 1100 0000 0000 - 0x7c00
GREEN: 0000 0011 1110 0000 - 0x3e0
BLUE: 0000 0000 0001 1111 - 0x1f
Use the bitmask with the bitwise AND operator to obtain the value:
$word = /* two-byte (two octets) value per pixel */
$alpha = $word & 0x8000;
$red = $word & 0x7c00;
...
Hope this helps. A PHP function that gives you the integer value for a binary number in PHP is bindec, a function to convert an integer to a hexadecimal number is dechex. Those functions are helpful to create a hexadecimal bitmask number from within PHP.
You can use as well a calculator to convert between binary, decimal and hexadecimal numbers, e.g. with a calculator like gcalctool.
Example code:
/**
* unpack a binary string word of a
* A1R5G5B5 color into an array of
* RGBA integer 8bit values.
*
* @param string $word
* @return array('red' => int, 'green' => int, 'blue' => int, 'alpha' => int)
*/
function wordA1R5G5B5ToArrayRGBA($word)
{
// unpack values from bit-fields
list(, $dec) = unpack('n', $word);
$blue = ($dec & 0x1F);
$green = ($dec & 0x3E0) >> 5;
$red = ($dec & 0x7C00) >> 10;
$alpha = ($dec & 0x8000) >> 15;
// map 5bit to 8bit (alpha: 1bit to 8bit)
$blue = ($blue << 3) | ($blue * 0x7 / 0x1F);
$green = ($green << 3) | ($green * 0x7 / 0x1F);
$red = ($red << 3) | ($red * 0x7 / 0x1F);
$alpha && $alpha = 0xFF;
return compact('red', 'green', 'blue', 'alpha');
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8185117",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: use tags only body part on Newsletter Email template in PHP I have been sending a Newsletter using Email Template, and it's working fine.
But I have a problem with Body part in my newsletter.
Because I have used strip_tags PHP function for removing <br> tags from Template,
Now I need <br> tags only for body parts, so any way I will use <br> tags for only body part?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17563986",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Javascript - Change page style without showing previous one I have a website that I want to add different styles to. The user may choose any style he wants, I store it in localStorage and display it. I have this code:
<link href="default.css" type="text/css" rel="stylesheet" onload="this.href = window.localStorage['webpage_style'];"/>
This works OK, but I have a problem with buttons. The default.css is white style - just like here on stack overflow. But the new one is dark style, with dark gray background and so on. My problem with the button is: on every page load with that new dark style, the button is white and then changes to dark rapidly, but the white moment is clearly visible and it looks awful. What can I do to stop the effect on page load?
Here are both CSS:
button {
width: 88%;
padding: 1.5em;
background-color: white;
border: 1px solid black;
margin: 1.8%;
margin-bottom: 0.2%;
cursor: pointer;
transition: background-color 0.3s ease-in-out;
}
button:hover {
background-color: #e8e8e8;
}
button:focus {
outline: none;
}
<button>Sample - Default CSS</button>
button {
width: 88%;
padding: 1.5em;
background-color: white;
border: 1px solid #c8c8c8;
/* Change here */
margin: 1.8%;
margin-bottom: 0.2%;
cursor: pointer;
transition: background-color 0.3s ease-in-out;
background-color: #272323;
/* Change here */
color: #c8c8c8;
/* Change here */
}
button:hover {
background-color: #3b3636;
/* Change here */
}
button:focus {
outline: none;
}
<button>Sample - Dark CSS</button>
What can I do to not show that effect? The button turns from white to black in like 0.3s. Is there any way to do it? Or should I just remove the transition line in CSS (that stops the effect, but is there any other way)?
A: You're telling the browser to wait for the load-event, this (from the aforementioned MDN-docs):
...fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images, scripts, links and sub-frames have finished loading.
Hence, don't use onload if you don't need to wait for the DOM to be ready.
<link href="default.css" type="text/css" rel="stylesheet" id="dynamic_stylesheet" />
<script>
if (window.localStorage['webpage_style']) {
var styleLink = document.getElementById("dynamic_stylesheet");
styleLink.href = window.localStorage['webpage_style'];
}
</script>
Or if that still introduces a flash you could write the style link conditionally in JS.
<script>
if (window.localStorage['webpage_style']) {
document.write("<link href=\""+window.localStorage['webpage_style']+"\" type=\"text/css\" rel=\"stylesheet\" />");
} else {
document.write("<link href=\"default.css\" type=\"text/css\" rel=\"stylesheet\" />");
}
</script>
<noscript>
<link href="default.css" type="text/css" rel="stylesheet" />
</noscript>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46002188",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Escaping quotes and html in a data- attribute JSON object Using the HTML5 data- attribute, one can store JSON in HTML as shown in the HTML below. This works great with string key:value pairs but I can't figure out how to make the values include special characters or HTML.
The part of the JSON object that is giving problems is this: Can't vote on <b>own</b> review (also interested in more complicated HTML chunks like this: <span style="text-decoration:underline" own</span>. Here's a JSFiddle for the code below.
JS:
$('button').on('click', function () {
var $this=$(this), data=$this.data('data');
$('#output').html(data.message);
});
HTML:
<button type='button' data-data='{"type": "voting", "message": "Can't vote on <span style="text-decoration:underline" own</span> review"}'></button>
<div id='output'></div>
A: You need to escape the HTML and specifically in this example, & and the character used to quote the attribute value (either " or '):
<button type='button' data-data='{"type": "voting", "message": "Can't vote on <b>own</b> review"}'></button>
or:
<button type='button' data-data='{"type": "voting", "message": "Can't vote on <span style='text-decoration:underline'>own</span> review"}'></button>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13705473",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Why does this binding display a class name? What might cause the value of a Silverlight 4 DataGridTextColumn.Header to display as System.Windows.Data.Binding rather than the resolved bound value? It seems like a ToString is happening somewhere that displays a class name rather than the formatted value of the class.
The binding looks like this
Header="{Binding Path=Dummy,Source={StaticResource languagingSource},Converter={StaticResource languagingConverter},ConverterParameter=vehicleDescription}"
and the problem doesn't lie anywhere within the binding as identical bindings, with different ConverterParameter values, work fine for Button.Content and TextBlock.Text properties within the same XAML page.
Even creating a simple string property like this within the local data context has the same result.
public string DataGridHeaderDescription { get { return "Description"; } }
Header="{Binding DataGridHeaderDescription}"
I've even tried adding a string format
Header="{Binding DataGridHeaderDescription,StringFormat=\{0\}}"
but this has no effect either.
A: It is now possible to using bindings even on elements that aren't derived from FrameworkElement however the property of the element being bound must be defined as a DependencyProperty which Header is not.
Since Header is simply a place marker for any content to be placed in the header you could simply do this:-
<DataGridTextColumn.Header>
<TextBlock Text="{Binding Path=Dummy,Source={StaticResource languagingSource},Converter={StaticResource languagingConverter},ConverterParameter=vehicleDescription}" />
</DataGridTextColumn.Header>
A: After some further searching I found this thread that answers the question and gives some suggested solutions.
Dynamically setting the Header text of a Silverlight DataGrid Column
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3625378",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to use IF and ELSE statement for MS query
Databasename: PEMS
Table name: AccountInfo
columns: AccountID, SubscriberID, Location,Passwords,AccountStatus
AccountStatus values inside are 'Activated' and 'Deactivated'
Accepts or rejects an accountID based on their AccountStatus.
Example: if an account has an AccountStatus of 'Deactivated' it will prompt that AccountID is blocked.
AcctID 48 and AccountStatus Deactivated it will reject when attempting to log in
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28667911",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: My Ajax is trying to render a view that it shouldn't So everything works. But if a user has firebug's console open, they'll see a bug. :D
When my AJAX is sent :
$(".remove_qf").live("click", function(){
$.ajax({type: "POST", url: $(this).attr("href"), data: { '_method': 'delete' }, dataType: "script"});
return false;
})
And my controller fires it :
def destroy
@quick_fact = @organization.quick_facts.find(params[:id])
@quick_fact.destroy
end
A view is fired and errors out on a 500 :
Missing template quick_facts/destroy.erb in view path app/views:vendor/plugins/rails-ckeditor/app/views
Strange though, because I don't need a destroy view, and I shouldn't add any code to what I have already to tell it to render false. I say this because I have something similar working my project with the same premise.
Anyone know what might be causing this?
Update
Routes.rb
map.resources :organizations,
:collection => {:live_validation => :post, :search => :get, :send_invitation_code_request => :post} do |organization|
organization.resources :quick_facts
A: I am not an expert in this area, however, I think that 1.) you need to add a handler to your ajax call to determine if the delete was successful & 2.) you may need to add some sort of success status message from the controller's destroy action.
A: The following solved the same problem for me.
respond_to do |format|
format.js { head :ok }
end
I'm unsure if this is better practice than using render :nothing => true or render :text => "".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3495986",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: grails JSON binding to LinkedHashSet instead of JSONArray for deeply nested relation I have three levels deep of a hierarchy that I am binding in a JSON request:
Group -> Zone -> Segment
(1) -> (n) -> (n)
In my command object I have:
class GroupCommand {
Long id
Set zones
}
When binding the JSON request the zones get bound properly and I get a LinkedHashSet that I can get the properties of and use with my domain object. However when I get to iterating over the segments in my service:
groupCommand.zones.each { zone ->
zone.segments.each { segment ->
//Would like to get LinkedHashMap here also
//but get JSONArray
}
}
As noted above, I'd ideally like the deeply nested Segments to also bind to a LinkedHashMap but it's bound to a JSONArray.
Any suggestions how to get it bound to a LinkedHashMap as I'd like to avoid having to manipulate JSONArray in my service and thereby coupling my service with the JSON format.
If there's a way to do the conversion at the command level using a getter I'm all for that also.
thanks
EDIT:
Using
List zones = org.apache.commons.collections.list.LazyList.decorate(new ArrayList(), new org.apache.commons.collections.functors.InstantiateFactory(ZoneCommand.class))
appears to work but the underlying objects are still JSON elements. I then tried using:
List<RateZoneCommand> zones = org.apache.commons.collections.list.LazyList.decorate(new ArrayList(), new org.apache.commons.collections.functors.InstantiateFactory(ZoneCommand.class))
and at least I got an error indicating it trying to convert:
Validation error: ... org.codehaus.groovy.grails.web.json.JSONArray to required type java.util.List for property zones; nested exception is java.lang.IllegalStateException: Cannot convert value of type [org..JSONObject] to required type [ZoneCommand] for property zones[0]: no matching editors or conversion strategy found.
A: Create a command class for each level. Mark Zone- and Segment-command as @Validateable.
To your GroupCommand, add:
List zones = org.apache.commons.collections.list.LazyList.decorate(new ArrayList(), new org.apache.commons.collections.functors.InstantiateFactory(ZoneCommand.class))
To your ZoneCommand, add:
List segments = org.apache.commons.collections.list.LazyList.decorate(new ArrayList(), new org.apache.commons.collections.functors.InstantiateFactory(SegmentCommand.class))
In your form just use group.zones[0].segments[0]. If you change a field type of your command class, remember to restart the grails server.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11513416",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Clock not updating every second using moment.js First time using moment.js and I am struggling to implement a clock to show the time in CET and PST. My code is as follows:
function cetClock() {
var cet = moment.tz("Europe/London");
var today = new Date(cet);
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkCetTime(m);
s = checkCetTime(s);
$rootScope.cetTime = h + ":" + m + ":" + s;
var t = setTimeout(cetClock, 300);
}
function checkCetTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
cetClock()
<div class="col-md-6">
<p>CET: {{$root.cetTime}}</p>
</div>
The issue I have is that the time in the view is only being updated every 4-5 seconds. If I log the h, m, s within the function, it shows every 500 milliseconds the time being updated.
Question
Why is the clock in the viiew failing to update every second?
A: I suggest using $timeout instead of setTimeout which will automatically trigger a digest cycle.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46367847",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to convert the topics into just a list of the top 20 words in each topic in LDA in python I am currently working on LDA logarithm in python. I want to covert the topics into just a list of the top 20 words in each topic. I tried below code but got different output.
I want my output in following format: topic=2,words=20.
['men', 'kill', 'soldier', 'order', 'patient', 'night', 'priest', 'becom', 'new', 'speech', 'friend', 'decid', 'young', 'ward', 'state', 'front', 'would', 'home', 'two', 'father']
["n't", 'go', 'fight', 'doe', 'home', 'famili', 'car', 'night', 'say', 'next', 'ask', 'day', 'want', 'show', 'goe', 'friend', 'two', 'polic', 'name', 'meet']
I got below output:
["(u'ngma', 0.034841332255132154)", "(u'video', 0.0073756817356584745)", "(u'youtube', 0.006524039676605746)", "(u'liked', 0.0065240394176856644)",]
["(u'ngma', 0.024537057880333127)", "(u'photography', 0.0068263432438681482)", "(u'tvallwhite', 0.0029535361359022566)", "(u'3', 0.0029252727655122079)"]
My code:
`ldamodel = Lda(doc_term_matrix, num_topics=2, id2word = dictionary,passes=50)
lda=ldamodel.print_topics(num_topics=2, num_words=3)
f=open('LDA.txt','w')
f.write(str(lda))
f.close()
topics_matrix = ldamodel.show_topics(formatted=False,num_words=10)
topics_matrix = np.array((topics_matrix),dtype=list)
topic_words = topics_matrix[:, 1]
for i in topic_words:
print([str(word) for word in i])
print()`
edit-1:
topic_words = []
for i in range(3):
tt = ldamodel.get_topic_terms(i,10)
topic_words.append([pair[0] for pair in tt])
print topic_words
resulted in non expected output:
[[1897, 135, 130, 127, 70, 162, 445, 656, 608, 1019], [1897, 364, 56, 1236, 181, 172, 449, 48, 15, 18], [1897, 163, 11, 70, 166, 345, 480, 9, 60, 351]]
A: Try this-
from gensim import corpora
import gensim
from gensim.models.ldamodel import LdaModel
from gensim.parsing.preprocessing import STOPWORDS
# example docs
doc1 = """
Java (Indonesian: Jawa; Javanese: ꦗꦮ; Sundanese: ᮏᮝ) is an island of Indonesia.\
With a population of over 141 million (the island itself) or 145 million (the \
administrative region), Java is home to 56.7 percent of the Indonesian population \
and is the most populous island on Earth.[1] The Indonesian capital city, Jakarta, \
is located on western Java. Much of Indonesian history took place on Java. It was \
the center of powerful Hindu-Buddhist empires, the Islamic sultanates, and the core \
of the colonial Dutch East Indies. Java was also the center of the Indonesian struggle \
for independence during the 1930s and 1940s. Java dominates Indonesia politically, \
economically and culturally.
"""
doc2 = """
Hydrogen fuel is a zero-emission fuel when burned with oxygen, if one considers water \
not to be an emission. It often uses electrochemical cells, or combustion in internal \
engines, to power vehicles and electric devices. It is also used in the propulsion of \
spacecraft and might potentially be mass-produced and commercialized for passenger vehicles \
and aircraft.Hydrogen lies in the first group and first period in the periodic table, i.e. \
it is the first element on the periodic table, making it the lightest element. Since \
hydrogen gas is so light, it rises in the atmosphere and is therefore rarely found in \
its pure form, H2."""
doc3 = """
The giraffe (Giraffa) is a genus of African even-toed ungulate mammals, the tallest living \
terrestrial animals and the largest ruminants. The genus currently consists of one species, \
Giraffa camelopardalis, the type species. Seven other species are extinct, prehistoric \
species known from fossils. Taxonomic classifications of one to eight extant giraffe species\
have been described, based upon research into the mitochondrial and nuclear DNA, as well \
as morphological measurements of Giraffa, but the IUCN currently recognizes only one \
species with nine subspecies.
"""
documents = [doc1, doc2, doc3]
document_wrd_splt = [[word for word in document.lower().split() if word not in STOPWORDS] \
for document in documents]
dictionary = corpora.Dictionary(document_wrd_splt)
print(dictionary.token2id)
corpus = [dictionary.doc2bow(text) for text in texts]
lda = LdaModel(corpus, num_topics=3, id2word = dictionary, passes=50)
num_topics = 3
topic_words = []
for i in range(num_topics):
tt = lda.get_topic_terms(i,20)
topic_words.append([dictionary[pair[0]] for pair in tt])
# output
>>> topic_words[0]
['indonesian', 'java', 'species', 'island', 'population', 'million', '(the', 'java.', 'center', 'giraffe', 'currently', 'genus', 'city,', 'economically', 'administrative', 'east', 'sundanese:', 'itself)', 'took', '1940s.']
>>> topic_words[1]
['vehicles', 'fuel', 'hydrogen', 'periodic', 'table,', 'i.e.', 'uses', 'form,', 'considers', 'zero-emission', 'internal', 'period', 'burned', 'cells,', 'rises', 'pure', 'atmosphere', 'aircraft.hydrogen', 'water', 'engines,']
>>> topic_words[2]
['giraffa,', 'even-toed', 'living', 'described,', 'camelopardalis,', 'consists', 'extinct,', 'seven', 'fossils.', 'morphological', 'terrestrial', '(giraffa)', 'dna,', 'mitochondrial', 'nuclear', 'ruminants.', 'classifications', 'species,', 'prehistoric', 'known']
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45711628",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to make SELECT more faster without NESTED LOOP Hello i'm making a website for webshop for t-shirts. Every product (from all 1400) has own ID (idedro), but every ID has different colors, sometimes one, sometimes twenty.
I need to show every product in own picture with all colors it has below, but i think a loop inside of a loop takes too much CPU time. Is there any way to make it with one loop may or enter image description herebe with JOIN or prepared statments?
$querycount = mysqli_query($link,"SELECT DISTINCT (idedro)
FROM megadb WHERE catteniskiipotnici=1 ORDER BY idedro ASC");
while ($rowcounts = mysqli_fetch_assoc($querycount)) {
$result1 = mysqli_query($link,"SELECT color
FROM megadb WHERE idedro='$rowcounts[idedro]'");
while ($row1=mysqli_fetch_array($result1)) { echo $row1[color]; }
}
A: This should do what you want using GROUP_CONCAT():
SELECT idedro, group_concat(color)
FROM megadb
WHERE catteniskiipotnici=1
GROUP BY idedro
ORDER BY idedro ASC
SQL Fiddle
MySQL 5.6 Schema Setup:
CREATE TABLE megadb
(`idedro` int, `color` varchar(5), `catteniskiipotnici` int)
;
INSERT INTO megadb
(`idedro`, `color`, `catteniskiipotnici`)
VALUES
(1, 'blue', 1),
(2, 'blue', 1),
(2, 'red', 1),
(3, 'blue', 1),
(3, 'red', 1),
(3, 'white', 1),
(4, 'blue', 0)
;
Query 1:
SELECT idedro, group_concat(color)
FROM megadb
WHERE catteniskiipotnici=1
GROUP BY idedro
ORDER BY idedro ASC
Results:
| idedro | group_concat(color) |
|--------|---------------------|
| 1 | blue |
| 2 | blue,red |
| 3 | blue,red,white |
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46632011",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: React firebase doesn't await I want to get data from firebase and map it and render a table with it but the firebase function returns data after the page loads.
const [datas, setData] = useState();
var ref = db.ref("something");
useEffect(() => {
const fetchData = async () => {
await ref.once("value").then((snapshot) => {
const fetched = snapshot.val();
var feed = {'name':'shoe','remark':'remarka','price':'pricea','photo':'photo','amount':'350'};
console.log('fetched', fetched)
setData(feed);
});
};
fetchData();
}, []);
now if I make a var here
let's say var text= datas
and console.log it it will return undefined
the feed var is just some dummy text
{dummy.map((data, key) => {
//render table
})
is there any way to make the page wait for the function to finish the useState ?
A: Use the AND operator (&&) which only executes the right operand when the left operand is truthy. It is not necessary to make a variable called dummy.
{
datas && datas.map(data=>{
console.log(data);
});
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72727474",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to show numpy array imshow plotly as frames? Create an array and make a picture out of it
xg = np.random.rand(100, 22400)
fig = px.imshow(a,aspect="auto", color_continuous_scale='gray')
out1.show()
The problem is that the array is long and the graph does not work correctly, is it possible to display the array in frames (since each value is already a pixel)?
A: *
*you can use animations to split into frames
*have sliced numpy array to create frames
import numpy as np
import plotly.graph_objects as go
import plotly.express as px
xg = np.random.rand(100, 22400)
# xg = np.random.rand(10, 1200)
base = px.imshow(xg, aspect="auto", color_continuous_scale="gray")
frameSize = 400
frames = [
go.Frame(
data=px.imshow(
xg[:, x : x + frameSize], aspect="auto", color_continuous_scale="gray"
).data,
name=x,
)
for x in range(0, xg.shape[1], frameSize)
]
go.Figure(data=frames[0].data, frames=frames, layout=base.layout).update_layout(
updatemenus=[{
"buttons": [{"args": [None, {"frame": {"duration": 500, "redraw": True}}],
"label": "▶",
"method": "animate",
},],
"type": "buttons",
}],
sliders=[{
"steps": [{"args": [[d],
{"frame": {"duration": 0, "redraw": True},
"mode": "immediate",},],
"label": d,
"method": "animate",
}
for d in range(0, xg.shape[1], frameSize)
],
}],
)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68589418",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Prevent css media types from changing the print version Currently developing a website that uses responsive css to change it's layout for smaller devices / screens etc.
The client has asked to be able to print the website from anywhere how it appears on desktop, so whichever style of print you do then it would always print the desktop version.
We have thousands of lines of css (4,000+) so it's not as simple as just making a media print{}.
The following is an example of the current layout:
div.container{
font-size:16px;
}
@media (min-width: 991px) {
div.container{
font-size:18px;
}
}
@media (max-width: 991px) and (min-width: 768px){
div.container{
font-size:20px;
}
}
@media (max-width: 991px) {
div.container{
font-size:22px;
}
}
The problem is when you press ctrl + p for your print preview, the print area is smaller and thus the smaller media css is applied and we don't see the website as we do on a desktop screen.
Is there anyway to apply the @media css but prevent it from affecting the print version?
@media (max-width: 991px),
!print{
}
A: You could use @media screen instead of just @media so that the codes will work in screen but not in the print version.
Example:
@media screen and (min-width: 991px) {
div.container{
font-size:18px;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25507497",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Groupby multiple row and keep two columns in pandas I have dataframe in format name, actor_link, movie_link and I want to group it by actor link to format name, actor_link, list_of_movies_where_actor_appears
example input
Tom Hanks,https://www.csfd.cz/tvurce/330-tom-hanks/,https://www.csfd.cz/film/10135-forrest-gump/
Tom Hanks,https://www.csfd.cz/tvurce/330-tom-hanks/,https://www.csfd.cz/film/2292-zelena-mile/
example output
Tom Hanks,https://www.csfd.cz/tvurce/330-tom-hanks/,[https://www.csfd.cz/film/10135-forrest-gump/,https://www.csfd.cz/film/2292-zelena-mile/]
my code is giving output
Tom Hanks,https://www.csfd.cz/tvurce/330-tom-hanks/,"['Tom Hanks', 'https://www.csfd.cz/film/10135-forrest-gump/', 'Tom Hanks', 'https://www.csfd.cz/film/2292-zelena-mile/']
code
original_actor_df = pd.read_csv('actors.csv')
actor_movies_df = original_actor_df.set_index("actor_link").stack().groupby(level=0).apply(list).reset_index(name="movies")
original_actor_df.drop(['movie_link'], axis=1, inplace=True)
original_actor_df.drop_duplicates(inplace=True)
actor_df = pd.merge(original_actor_df, actor_movies_df, on="actor_link")
How can I get rid of actor name in column with movie links? Can I simplify this process with dataframe without so many steps? I think it could be possible with adjusting
original_actor_df.set_index("actor_link").stack().groupby(level=0).apply(list).reset_index(name="movies")
I tried, I failed ...
A: Hey there fellow Czech programmer! <3
This might get the job done, i think...
import pandas as pd
df = pd.read_csv('MOCK_DATA.csv')
# group by actor_link and count the number of movies
g = df.groupby(['actor','actor_link'])['movie'].apply(list).reset_index(name='list_of_movies')
# output res to a csv file
g.to_csv('actor_movies.csv', header=False, index=False)
Tested on this file:
actor,actor_link,movie
Yardley McGilroy,www.csfd/Yardley McGilroy.cz,Sharknado 2: The Second One
Woodman Meese,www.csfd/Woodman Meese.cz,The Amazing Catfish
Marijo Thorburn,www.csfd/Marijo Thorburn.cz,"Soldier, The"
Arron Rosenfield,www.csfd/Arron Rosenfield.cz,Barcelona
Olga Wainscot,www.csfd/Olga Wainscot.cz,Addicted
Bradan Ivashev,www.csfd/Bradan Ivashev.cz,Fury
Lu Manjin,www.csfd/Lu Manjin.cz,"Sea Inside, The (Mar adentro)"
Shelby Kitt,www.csfd/Shelby Kitt.cz,"Set-Up, The"
Barbaraanne Yakushkin,www.csfd/Barbaraanne Yakushkin.cz,"Princess Blade, The (Shura Yukihime)"
Abbey Munkton,www.csfd/Abbey Munkton.cz,Twin Peaks: Fire Walk with Me
Vittoria Clayal,www.csfd/Vittoria Clayal.cz,"Cider House Rules, The"
Vickie Ormrod,www.csfd/Vickie Ormrod.cz,Hustler White
Artemas Solomonides,www.csfd/Artemas Solomonides.cz,Satyricon
Lucita Whittick,www.csfd/Lucita Whittick.cz,"Exterminator, The"
Cullen Kear,www.csfd/Cullen Kear.cz,Non-Stop
Tine Slaney,www.csfd/Tine Slaney.cz,Measuring the World (Die Vermessung der Welt)
Allister Caulcott,www.csfd/Allister Caulcott.cz,Beat the Devil
Dannie Sheara,www.csfd/Dannie Sheara.cz,Casanova's Big Night
Montague Casetti,www.csfd/Montague Casetti.cz,Someone Like Him (Einer wie Bruno)
Dara French,www.csfd/Dara French.cz,Gozu (Gokudô kyôfu dai-gekijô: Gozu)
Debby Winterson,www.csfd/Debby Winterson.cz,Dr. Jekyll and Mr. Hyde
Phaedra Eneas,www.csfd/Phaedra Eneas.cz,Edges of the Lord
Obidiah Bastiman,www.csfd/Obidiah Bastiman.cz,Rendezvous
Lindy Lilbourne,www.csfd/Lindy Lilbourne.cz,Night Moves
Devon Obert,www.csfd/Devon Obert.cz,Rabbit Without Ears 2 (Zweiohrküken)
Conrade Urrey,www.csfd/Conrade Urrey.cz,Heavens Fall
Jaine Chasson,www.csfd/Jaine Chasson.cz,Jimi Hendrix: Hear My Train A Comin'
Filberte Southerton,www.csfd/Filberte Southerton.cz,"Capture of Bigfoot, The"
Ulric Hargitt,www.csfd/Ulric Hargitt.cz,Pilgrimage
Gal Pavia,www.csfd/Gal Pavia.cz,Big Hero 6
Niels Dannell,www.csfd/Niels Dannell.cz,More Than a Game
Kari Jobe,www.csfd/Kari Jobe.cz,Jimi: All Is by My Side
Tonia Hatton,www.csfd/Tonia Hatton.cz,Star Trek: Nemesis
Rozele Kaas,www.csfd/Rozele Kaas.cz,Captive (Cautiva)
Urson Bourdel,www.csfd/Urson Bourdel.cz,RKO 281
Teddi Mohammed,www.csfd/Teddi Mohammed.cz,Canvas
Blair Mosedale,www.csfd/Blair Mosedale.cz,Escape from Fort Bravo
Cleon Sloley,www.csfd/Cleon Sloley.cz,Survival Quest
Yasmin Snap,www.csfd/Yasmin Snap.cz,Strictly Sexual
Audy Rubinfeld,www.csfd/Audy Rubinfeld.cz,Queen of Montreuil
Shepperd Matusiak,www.csfd/Shepperd Matusiak.cz,"Dark Side of the Heart, The (Lado oscuro del corazón, El)"
Storm Harrowing,www.csfd/Storm Harrowing.cz,"Artist, The"
Vlad Geare,www.csfd/Vlad Geare.cz,Pleasure at Her Majesty's
Stacey Kiff,www.csfd/Stacey Kiff.cz,Marilyn in Manhattan
Darla Dongall,www.csfd/Darla Dongall.cz,Hometown Legend
Nathan Lythgoe,www.csfd/Nathan Lythgoe.cz,Tales of Terror
Krishnah Bernet,www.csfd/Krishnah Bernet.cz,Circus of Horrors
Elnore Haggett,www.csfd/Elnore Haggett.cz,"Thing About My Folks, The"
Wasn't able to get rid of the quotation marks because that would break the csv parsing, hope that's not too big of a problem...
A: I think you can get desired output using group by aggregation as follows.
import pandas as pd
import io
string = """name,actor_link,movie_link
Tom Hanks,https://www.csfd.cz/tvurce/330-tom-hanks/,https://www.csfd.cz/film/10135-forrest-gump/
Tom Hanks,https://www.csfd.cz/tvurce/330-tom-hanks/,https://www.csfd.cz/film/2292-zelena-mile/"""
df = pd.read_csv(io.StringIO(string), sep=",")
df = df.groupby(['name','actor_link']).agg(list_of_movies=('movie_link',list)).reset_index()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72623349",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: C# + WPF : text mode equivalent of old DOS libraries or curses The goal: For a personal project, I'd like to simulate an old-fashioned computer interface with full screen command line, hex editor, text editor, etc. All text, no graphics. (For a simulator/emulator of a hypothetical computer.)
The starting point: I've figured out that console mode can't be full-screened anymore but that I can easily go fullscreen in WPF with WindowState=Maximized and WindowStyle=None. So I can make a full-screen TextBox.
The problem: Is there an existing control, pattern, or library for basic writing to a screen of text and reading from the keyboard (not filling out and submitting a field on a form, like a TextBox is geared toward)?
I assume that I'll need to make my own custom control instead of a textbox, and build a large class of low-level methods to position the cursor, output characters, react to input, etc. But if there's a tried-and-true method or standard approach, I'd rather use that than burn time reinventing a commonly-used wheel.
In the olden DOS days, I would've used a library based off of direct BIOS video calls, PEEKs and POKEs to video RAM, and keyboard and mouse polling. Of course that doesn't apply anymore, but neither do the standard console routines. Is there something already out there that fills that niche?
[edit]
To clarify. In DOS days, we had libraries for things like:
Scroll(3);
Write(24,1, "Your command has been queued for execution");
input = Prompt(25, 1, "Enter a command>");
and in document edit mode we would do things like
key = WaitKey();
switch (key) {
case PGUP: Scroll(-24);
case PGDN: Scroll(24);
case LEFT: MoveCursor(-1,0);
case DOWN: MoveCursor(0,1);
// ...
}
etc... That's the sort of thing that I'm looking for. Something with functions like Write, Scroll, Prompt, etc.
A: It sounds like what you are developing is closer to a game than a standard Windows forms application - using a game development library (such as SDL or Microsoft XNA) might make things more straightfoward.
If you are already experienced with the way that the console functioned in the days of old then implementing this should be pretty straightforward - you have your behind-the-sceenes array of characters displayed on the screen + cursor position structure which should be easy to print to the screen each frame, plus a game library will give you the ability to intercept and handle all keyboard events.
If you were planning on routing the output of another process onto this "screen" then things might start to become a little more tricky - if this is the case then this might not be the best idea.
A: Trying to achieve the look and feel (and responsiveness) of a text mode application using a WPF TextBox will have disappointing results. Take a look at what Pete Brown did when he created a Commodore 64 emulator in WPF and Silverlight.
I believe his implementation actually used a writable bitmap to emulate a video card. So the peeks and pokes you refer to would actually take place in a memory buffer instead of the screen and then that would be turned into a screen image frame by frame.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5150821",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Comparison method violates its general contract in sorting method I get an error in my sorting method.
Comparison method violates its general contract
This is my sorting object with sort method
public abstract class ComparablePerson extends IDValueItem implements
Comparable<ComparablePerson> {
private int score;
private String itemID,itemName;
//setters and getters
public int compareTo(ComparablePerson another) {
if (score == another.getScore())
return this.getItemName().compareToIgnoreCase(another.getItemName());
else if ((score) > another.getScore())
return 1;
else
return -1;
}
@Override
public boolean equals(Object o) {
final ComparablePerson other = (ComparablePerson) o;
if (score == other.getScore() && this.getItemName().equalsIgnoreCase(other.getItemName()))
return true;
else
return false;
}
I just call
Collections.sort(ComparablePersonCollection);
What can be the cause of this?
A: The compareTo and equals method implementations seem to be inconsistent, the error is telling you that for the same two objects equals gives true while compareTo does not produce zero, which is incorrect. I suggest you invoke compareTo from equals to ensure consistency or otherwise define a custom Comparator<T>.
Simply do:
public abstract class ComparablePerson extends IDValueItem implements Comparable<ComparablePerson> {
private int score;
private String itemID,itemName;
//setters and getters
public int compareTo(ComparablePerson another) {
if (score == another.getScore())
return this.getItemName().compareToIgnoreCase(another.getItemName());
else if ((score) > another.getScore())
return 1;
else
return -1;
}
@Override
public boolean equals(Object o) {
return compareTo(o) == 0;
}
}
A: ComparablePerson is abstract, the comparison method is probably overloaded elsewhere...
Can you post the client (which owns the collection) and the concrete classes?
This code works well:
public class ComparablePerson implements Comparable< ComparablePerson > {
public ComparablePerson( int score, String name ) {
_score = score;
_itemName = name;
}
@Override public int compareTo( ComparablePerson another ) {
int delta = _score - another._score;
if( delta != 0 ) return delta;
return _itemName.compareToIgnoreCase( another._itemName );
}
@Override public boolean equals( Object o ) {
return 0 == compareTo((ComparablePerson)o);
}
@Override public int hashCode() {
return super.hashCode();
}
private final int _score;
private final String _itemName;
public static void main( String[] args ) {
List< ComparablePerson > oSet = new LinkedList<>();
oSet.add( new ComparablePerson( 5, "x" ));
oSet.add( new ComparablePerson( 5, "y" ));
oSet.add( new ComparablePerson( 5, "z" ));
oSet.add( new ComparablePerson( 6, "x" ));
oSet.add( new ComparablePerson( 6, "y" ));
oSet.add( new ComparablePerson( 6, "z" ));
Collections.sort( oSet );
System.err.println( "Ok" );
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13763604",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Web services error trapping(Jquery + asp.net web service) I am on the look out for an accepted solution for trapping errors in the following scenario:
i have an asp.net web services that interacts with the database. I interact with the web service through jquery's $ajax function.
I would like to know what is the accepted stable methodology for error trapping. When the data is received from the the web service there are two types of errors in my scenario:
*
*db errors
*ajax errors
Ajax errors can trapped inside error portion of $ajax function. I trap the database errors inside the web service and so far I could only come up with one idea how to pass them on to the user - pack them in the results array. But this solution is awkward. Are there any better ideas?
Here is the sample of code I use for accessing asp.net web service:
$.ajax({
type: "POST",
url: "http://localhost/WebServices/Service.asmx/GetBillingEntities",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
var results = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
DisplayResults();
},
error: function(xhr, status, error) {
// Display a generic error for now.
alert("AJAX Error!");
}
});
So should the database results go in to results array and unpacked there manually? Is there a better system?
Thanks!
A: got it:
$(document).ready(function() {
02 $.ajax({
03 type: "GET",
04 url: "AJAX/DivideByZero",
05 dataType: "json",
06 success: function(data) {
07 if (data) {
08 alert("Success!!!");
09 }
10 }, error: function(xhr, status, error) {
11 DisplayError(xhr);
12 }
13 });
14 });
15
16 function DisplayError(xhr) {
17 var msg = JSON.parse(xhr.responseText);
18 alert(msg.Message);
19 }
A: What you can do is throw an exception in your GetBillingEntities method of your webservice. Catch the exception, log some details and then re-throw it. If your method throws an exception it should get caught in the "error:" block.
So basically you handle the error data in your service and handle how to display an error to the user in your "error:" block.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2141359",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to access a webelement in other class in POM - Selenium I have 2 pages (landing page and registration page). In landing page, I am storing webelements using @FindBy annotations. I need to use the Webelements oflanding page in the registration page. How can I proceed?
A: You just need to create an object of the class and access it like variable
Suppose class A having @FindBy function and variable is suppose myelement
Then use (it is Java, try similar in whatever lang you are using):
A aobject= new A();
A.myelement;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45986374",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: logstash kv filter, converting strings to integers using dynamic mapping I have a log with a format similar to:
name=johnny amount=30 uuid=2039248934
The problem is I am using this parser on multiple log files with each basically containing numerous kv pairs.
Is there a way to recognize when values are integers and cast them as such without having to use mutate on every single key value pair?(Rather than a string)
I found this link but it was very vague in where the template json file was suppose to go and how I was to go about using it.
Can kv be told to auto-detect numeric values and emit them as numeric JSON values?
A: You can use ruby plugin to do it.
input {
stdin {}
}
filter {
ruby {
code => "
fieldArray = event['message'].split(' ');
for field in fieldArray
name = field.split('=')[0];
value = field.split('=')[1];
if value =~ /\A\d+\Z/
event[name] = value.to_i
else
event[name] = value
end
end
"
}
}
output {
stdout { codec => rubydebug }
}
First, split the message to an array by SPACE.
Then, for each k,v mapping, check whether the value is numberic, if YES, convert it to Integer.
Here is the sample output for your input:
{
"message" => "name=johnny amount=30 uuid=2039248934",
"@version" => "1",
"@timestamp" => "2015-06-25T08:24:39.755Z",
"host" => "BEN_LIM",
"name" => "johnny",
"amount" => 30,
"uuid" => 2039248934
}
Update Solution for Logstash 5:
input {
stdin {}
}
filter {
ruby {
code => "
fieldArray = event['message'].split(' ');
for field in fieldArray
name = field.split('=')[0];
value = field.split('=')[1];
if value =~ /\A\d+\Z/
event.set(name, value.to_i)
else
event.set(name, value)
end
end
"
}
}
output {
stdout { codec => rubydebug }
}
A: Note, if you decide to upgrade to Logstash 5, there are some breaking changes:
https://www.elastic.co/guide/en/logstash/5.0/breaking-changes.html
In particular, it is the event that needs to be modified to use either event.get or event.set. Here is what I used to get it working (based on Ben Lim's example):
input {
stdin {}
}
filter {
ruby {
code => "
fieldArray = event.get('message').split(' ');
for field in fieldArray
name = field.split('=')[0];
value = field.split('=')[1];
if value =~ /\A\d+\Z/
event.set(name, value.to_i)
else
event.set(name, value)
end
end
"
}
}
output {
stdout { codec => rubydebug }
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31031895",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Dataflow reading using PubSubIO is really slow I'm having some trouble with a Dataflow pipeline that reads from PubSub and writes to BigQuery.
I had to drain it to perform some more complex updates. When I rerun the pipeline it started reading fom PubSub at a normal rate, but then after some minutes it stopped and now it is not reading messages from PubSub anymore! Data watermark is almost one week delayed and not progressing. There are more than 300k messages in the subscription to be read, according to Stackdriver.
It was running normally before the update, and now even if I downgrade my pipeline to the previous version (the one running before update), I still doesn't get it to work.
I tried several configurations:
1) We use Dataflow autoscaling, and I tried starting the pipeline with more powerful workers (n1-standard-64), and limiting it to ten workers, but it won't improve performance neither autoscale (it keeps only the initial worker).
2) I tried providing more disk through diskSizeGb (2048) and diskType (pd-ssd), but still no improvement.
3) Checked PubSub quotas and pull/push rates, but it's absolutely normal.
Pipeline shows no errors or warnings, and just won't progress.
I checked instances resources and CPU, RAM, disk read/write rates are all okay, compared to other pipelines. The only thing a little higher is network rates: about 400k bytes/sec (2000 packets/sec) outgoing and 300k bytes/sec incoming (1800 packets/sec).
What would you suggest I do?
A: The Dataflow SDK 2.x for Java and the Dataflow SDK for Python are based on Apache Beam. Make sure you are following the documentation as a reference when you update. Quotas can be an issue for slow running pipeline and lack of output but you mentioned those are fine.
It seems there is a need to look at the job. I recommend to open an issue on the PIT here and we’ll take a look. Make sure to provide your project id, job id and all the necessary details.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45772189",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: java.io.IOException: Cannot run program "/bin/bash": error=24, Too many open files I am connecting wmic via terminal for every 5 seconds by using thread. But I got "java.io.IOException: Cannot run program "/bin/bash": error=24, Too many open files"
after 1 day.
Thread program:
public void run() {
try {
while (true) {
if (isStopIssued()) {
break;
}
setStatus("SLEEP");
Thread.sleep(5000);
if (isStopIssued()) {
break;
}
setStatus("ACTIVE");
process();
if (isStopIssued()) {
break;
}
}
}
catch (InterruptedException e) {
logger.error(this.getClass().getName() + ": " + e.getMessage(), e);
}
}
Process Method:
private void process() {
ProcessBuilder builder = new ProcessBuilder("/bin/bash");
Process p = null;
int exit = 0;
BufferedWriter p_stdin = null;
OutputStreamWriter osw = null;
String inDir = inputDir + "/" + inputFile;
String errDir = errorDir + "/" + errorFile;
String outDir = outputDir + "/" + outputFile;
logger.debug("[JWMILoader] - Input Directory ---> " + inDir);
logger.debug("[JWMILoader] - Output Directory ---> " + outDir);
logger.debug("[JWMILoader] - Error Directory ---> " + errDir);
File inFile = new File(inDir);
File errFile = new File(errDir);
try {
p = builder.redirectOutput(inFile).start(); **// Line Number : 194 **
p = builder.redirectError(errFile).start();
}
catch (IOException e) {
logger.error(this.getClass().getName() + ": " + e.getMessage(), e);
}
osw = new OutputStreamWriter(p.getOutputStream());
// get standard input of shell
p_stdin = new BufferedWriter(osw);
// execute the desired command (here: wmic) n times
try {
// single execution
p_stdin.write(wmiQuery);
p_stdin.newLine();
p_stdin.flush();
}
catch (IOException e) {
logger.error(this.getClass().getName() + ": " + e.getMessage(), e);
}
// finally close the shell by execution exit command
try {
p_stdin.write("exit");
p_stdin.newLine();
p_stdin.flush();
}
catch (IOException e) {
logger.error(this.getClass().getName() + ": " + e.getMessage(), e);
}
finally {
try {
p_stdin.close();
exit = p.waitFor();
logger.debug("[JWMILoader] - WQL Query Successfully Executed. Process Exit ---> " + exit);
}
catch (IOException | InterruptedException e) {
logger.error(this.getClass().getName() + ": " + e.getMessage(), e);
}
}
if (p != null) {
p.destroy();
}
}
Exception :
java.io.IOException: Cannot run program "/bin/bash": error=24, Too many open files
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1041)
at mavens.imlog.etl.loader.JWMILoader.remoteConnection(JWMILoader.java:194)
at mavens.imlog.etl.loader.JWMILoader.process(JWMILoader.java:156)
at mavens.imlog.etl.loader.JWMILoader.run(JWMILoader.java:64)
Caused by: java.io.IOException: error=24, Too many open files
at java.lang.UNIXProcess.forkAndExec(Native Method)
at java.lang.UNIXProcess.<init>(UNIXProcess.java:135)
at java.lang.ProcessImpl.start(ProcessImpl.java:130)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1022)
... 3 more
I am using CENT OS.
Please friends help me, how to solve this problem.
A: You start processes twice,
*
*First one running with output inFile,
*Second one running with output inFile & error errFile
Was it your original intension?
try {
p = builder.redirectOutput(inFile).**start()**; **// Line Number : 194 **
p = builder.redirectError(errFile).**start()**;
}
catch (IOException e) {
logger.error(this.getClass().getName() + ": " + e.getMessage(), e);
}
And destroy only the last one created.
if (p != null) {
p.destroy();
}
Fix this, and this should fix your error.
P.S.
Start it only once:
try {
builder = builder.redirectOutput(inFile);
p = builder.redirectError(errFile).start();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25029187",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to get the layer from namespace? I have a code with namespace like this:
namespace nameFile.Common.otherParameters
{
public interface IEntityManager : **ICommon**
{
}
}
And I want to get the layer name to a property (in C#).
How can I do that?
(see the interface inherit from the layer name + I)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56846808",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to add csv row to array in powershell I'm looking to import a csv file. Take the first row(with headers) and add it to an array in powershell.
$csv = Import-CSV "test.csv"
$array = @()
A: Would you need an explicit conversion to array when import-csv is giving you a nice enumerable array of System.Object instances?
When you use import-csv , PowerShell will read the header row and give you back an array of custom objects. Each of these objects will have properties which match the Header column.
Example of test.csv
Id,FirstName
1,Name001
2,Name002
Results after import-csv
You can iterate through the collection as shown below
$csv = Import-CSV "test.csv"
foreach($item in $csv)
{
$msg=("Id={0} , Name={1}" -f $item.Id, $item.FirstName)
Write-Host $msg
}
#Add the first item to your own array
$arrMy=@()
$arrMy+=$csv[0]
$arrMy
Output
Id=1 , Name=Name001
Id=2 , Name=Name002
Id FirstName
-- ---------
1 Name001
MSDN
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/import-csv?view=powershell-6
Getting deeper - what does import-csv actually return?
It returns an array with N objects of type System.Management.Automation.PSCustomObject. Here N=no of rows in the CSV file.
A: I'm not quite sure what you are asking here, but it looks to me that you want to get the headers of a CSV file as array: (Take the first row(with headers) and add it to an array in powershell)
If that is the case, here's a small function that can do that for you:
function Get-CsvHeaders {
# returns an array with the names of the headers in a csv file in the correct order
[CmdletBinding(DefaultParameterSetName = 'ByDelimiter')]
param(
[Parameter(ValueFromPipeline = $true, Mandatory = $true, Position = 0)]
[ValidateScript({Test-Path -Path $_ -PathType Leaf})]
[string]$Path,
[Parameter(Mandatory = $false)]
[ValidateSet ('ASCII', 'BigEndianUnicode', 'Default', 'OEM', 'Unicode', 'UTF32', 'UTF7', 'UTF8')]
[string]$Encoding = $null,
[Parameter(Mandatory = $false, ParameterSetName = 'ByDelimiter')]
[char]$Delimiter = ',',
[Parameter(Mandatory = $false, ParameterSetName = 'ByCulture')]
[switch]$UseCulture
)
$splatParams = @{ 'Path' = $Path }
switch ($PSCmdlet.ParameterSetName) {
'ByDelimiter' { $splatParams.Delimiter = $Delimiter; break }
'ByCulture' { $splatParams.UseCulture = $true; break }
}
if ($Encoding) { $splatParams.Encoding = $Encoding }
$data = Import-Csv @splatParams -ErrorAction SilentlyContinue
$data[0].PSObject.properties.name
}
Usage:
$headersArray = Get-CsvHeaders -Path 'test.csv'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54953266",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to calculate the average of the selected attribute in Power BI I am working on the Fifa 19 Kaggle Dataset. I want to create a Gauge chart that compares the Overall stat for a Player compared with the Overall Average of the club(target value) he plays for.
I tried to create a calculated column:
Club Overall = calculate(Average(data[Overall]); data[Club]= "FC Barcelona")
Instead of "FC Barcelona", I want it to be the Club the selected player plays in.
A: This measure should do what you want, by filtering all players, but leaving the club filter in place:
Club Overall Average =
IF (
HASONEVALUE ( data[Club] ),
CALCULATE (
AVERAGE ( data[Overall] ),
ALL ( data[Name] ),
data[Club] = VALUES ( data[Club] )
),
BLANK()
)
See https://pwrbi.com/2019/05/stack-overflow-56128872/ for worked example
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56128872",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Triggering an output task with NIDAQmx I'm having trouble carrying out what I think should be a pretty straightforward task on a NIDAQ usb6002: I have a low frequency sine wave that I'm measuring at an analog input channel, and when it crosses zero I would like to light an LED for 1 second. I'm trying to use the nidaqmx Python API, but haven't been able to clear up some of my basic questions with the documentation. https://nidaqmx-python.readthedocs.io/en/latest/
If anyone can offer any thoughts about the code or the basic logic of my setup, that would be hugely helpful.
Here's what I have tried so far. I start with some imports and the definition of my channels:
import matplotlib.pyplot as plt
from math import *
import nidaqmx
from nidaqmx import *
from nidaqmx.constants import *
import time
V_PIN = "Dev1/ai6"
LED_PIN = "Dev1/ao0"
I understand how tasks and things work generally- I can read and plot a signal of a given sampling rate and number of samples using task.ai_channels methods without any trouble. But here's my best guess at how to carry out "detect zero and trigger output":
writeLED = nidaqmx.Task('LED')
writeLED.ao_channels.add_ao_voltage_chan(LED_PIN)
writeLED.timing.cfg_samp_clk_timing(1)
writeLED.triggers.start_trigger.cfg_anlg_edge_start_trig(V_PIN,trigger_level = 0)
writeLED.write([5], auto_start=True)
This gives me the error below at the cfg_anlg_edge line
DaqError: Requested value is not a supported value for this property. The property value may be invalid because it conflicts with another property.
Property: DAQmx_StartTrig_Type
Requested Value: DAQmx_Val_AnlgEdge
Possible Values: DAQmx_Val_DigEdge, DAQmx_Val_None
I don't know why an analog input channel wouldn't be supported here. Page 245 of this document makes it sound like it should be: https://media.readthedocs.org/pdf/nidaqmx-python/latest/nidaqmx-python.pdf
I'm sure there are other problems with the code, too. For example, it seems like the sample clock manipulations are quite a bit more complicated than what I've written above, but I haven't been able to find anything that explains how it would work in this situation.
Thanks in advance for any help!
A: With NI, it's "RTFMs"
When programming NI devices, you usually need two manuals.
*
*NI-DAQmx Help (for the programming part)
*the device specification (for the device part)
You need both because the NI-DAQmx API supports every DAQ device NI makes, but not every device has the same capabilities. "Capabilities" includes more than how many channels of each kind, but also the timing and triggering subsystems as well as internal signal routing. A DAQmx application that runs with one device is not guaranteed to run with another because the application might use the API in a way the second device cannot support.
Finally, on the documentation front, any given NI DAQ device typically belongs to family of related devices and these families also have a manual called User Guide. These User Guides act as a bridge between the API and device spec, helping you understand how the device responds to commands. For the 6002, the family is "Low-Cost DAQ USB Device".
Analog trigger for analog output on NI 6002
Your determination is correct that
writeLED.triggers.start_trigger.cfg_anlg_edge_start_trig(V_PIN,trigger_level = 0)
is possible, just not for the USB 6002. This line is asking the analog output subsystem to use an analog edge trigger, but the analog output subsystem for the 6002 only has these trigger capabilities:
*
*software
*PFI 0
*PFI 1
For this device, you're only option is the software trigger because the PFI lines are digital triggers and their trigger level is specified to be between 0.8 V and 2.3 V.
Change your Python program to detect a zero-crossing from the analog input stream and, when it does, make it call stop() and then start() on the AO task.
The reason for the stop-start sequence is retriggering: you want to light the LED for each zero crossing, but a task cannot be restarted unless it has either been stopped (by the API or by completing its task) or configured for retriggering. Because the 6002 is in the low-cost family, this hardware feature isn't available, so you must use the API to stop the AO task or wait for the AO generation to complete before restarting the pulse for the LED
6002 AO Specification
A: Software triggering is not real-time, you will have non-deterministic delay before the led turns on. This depends on your program, interfaces, usb latencies, pc performances...
Otherwise, you can use a comparator (like lm393) to trigger a digital input (PFI0 or PFI1).
Though it's just an LED, it is probably not critical if the delay varies within milliseconds.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53356449",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: C# ASP.Net Menu control multiplies when click Static item (Ex. SMS) MenuItem menuTest2 = new MenuItem(); // Main Manu 2
menuTest2.Text = " SMS ";
//menuTest2.NavigateUrl = "something";
//menuTest2.Value = "something";
Menu1.Items.Add(menuTest2);
MenuItem child_SM1 = new MenuItem();
child_SM1.Text = "SMS Subcribe";
child_SM1.NavigateUrl = "~/20SMSsubscribe.aspx";
//child_SM1.Value = "something";
menuTest2.ChildItems.Add(child_SM1);
MenuItem child_SM2 = new MenuItem();
child_SM2.Text = "SMS Authorise";
child_SM2.NavigateUrl = "~/21SMSauthorise.aspx";
//child_SM2.Value = "something";
menuTest2.ChildItems.Add(child_SM2);
A: You need to use as below
MenuItem menuTest2 = new MenuItem(); // Main Manu 2
menuTest2.Text = " SMS ";
menuTest2.NavigateUrl = "javascript:void(0)";
//menuTest2.Value = "something";
Menu1.Items.Add(menuTest2);
The problem as I think was that the page get redirected to the same page when clicked. And as I guess the menu is created on page load event.
Using menuTest2.NavigateUrl = "javascript:void(0)"; will stop the menu to postback when it is clicked.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25118337",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
} |
Q: insertSubView:belowSubview: for a UIImageView I am woundering if its possible to use the insertSubView:belowSubview: As it stands the below code is throwing this warning error
Incompatible pointer types sending 'UIImage *__strong' to parameter of type 'UIView *'
I am hoping maybe I have done something slightly wrong you guys can see as the only other way I can think of doing this would be to put the UIImageView into a UIView... please tell me there is a better way.. lol
code below.
UIImage *shadowImage = [UIImage imageNamed: @"shade.png"];
UIImageView *shadowImageView = [[UIImageView alloc] initWithImage:shadowImage];
[otherNav.view addSubview:shadowImageView];
[otherNav.view insertSubview:shadowImage belowSubview:animatedActionView];
any help would be greatly appreciated.
A: try this
[otherNav.view insertSubview:shadowImageView belowSubview:animatedActionView];
because the first parameter must be an View or a subclass of uiview
in your case you try to pass an UIImage who itsn't an UIView or subclass of UIview
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10922911",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What is the best way to iterate multidimensional array in node.js/javascript? I am trying to iterate multidimensional array in Node.js. I have array in JSON object like this :
{
"operationalHours": [
[
{
"opens": "11: 15AM",
"closes": "11: 30AM"
},
{
"opens": "11: 30AM",
"closes": "11: 45AM"
},
{
"opens": "11: 45AM",
"closes": "12: 00PM"
}
],
[
{
"opens": "12: 15AM",
"closes": "12: 30AM"
},
{
"opens": "12: 30AM",
"closes": "12: 45AM"
},
{
"opens": "01: 00AM",
"closes": "01: 15AM"
}
]
]
}
Does anyone know the best way to iterate this in node.js?
A: The most "quicker" way to iterate an array in javascript is:
var i;
for (i = myarray.length; i--;) {
console.log(myarray[i]);
}
Iteration counter in a reverse order - from the biggest number to zero, usually increases the speed, because operation of comparison with 0 is a little more effective, than operation of comparison with array length or with any other number, different to 0.
To iterate object inside of each array element you can use for in cycle:
var i, j;
for (i = myarray.length; i--;) {
for (j in myarray[i]) {
console.log(j, myarray[i][j]);
}
}
A: With lodash:
_.forEach(operationalHours, function(el, key) {
});
You can also find element:
var items = _.findWhere(operationalHours[0], {"opens": "11: 30AM"})
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33931368",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Zap docker - Active scan Is there a way to run active scan through ZAP docker?
I have a web application that requires login and after login I need to record the actions I am doing in UI and need to do active scan against that page. It is a form based web application.
We are using python with selenium for UI automation.
A: Yes, via the Full Packaged Scan: https://www.zaproxy.org/docs/docker/full-scan/
Setting up authentication is also possible - we've just published a video walking through this process: https://www.youtube.com/watch?v=BOlalxfdLbU
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66385885",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Variable not showing value in template tag I have the following segment of code in view:
image = [
'register.png',
'checkin.png',
'checkin.png'
]
imagetext = [
'Register Patient',
'Checkin Patient',
'Checkin Patient'
]
link = [
'/clinic/%s/register' % cliniclabel,
'/clinic/%s/checkin' % cliniclabel,
'/clinic/%s/checkin' % cliniclabel
]
zipsidebarstuff = zip(image, imagetext, link)
return render(request, 'clinic/cliniccurrent3.html',
{'rnd_num': randomnumber(), 'clinic': clinicobj,
'checked_list': checkedin_list, 'patientcount': patientcount,
'type':'live', 'ClinicUserName': name, 'showhelp': helpneeded,
'NumUnconfirmedAppts': NumUnconfirmedAppts(clinicobj),
'zipsidebarstuff': zipsidebarstuff})
In my template I have:
<div class="col-md-6">
<div class="sidebar-nav-fixed pull-right affix">
<div class="row">
<div class="d-inline-flex flex-row flex-wrap">
{% for image, imagetext, link in zipsidebarstuff %}
<div class="p-2 bd-white">
<div class="d-inline-flex flex-column">
<div class="p-2 flex-fill bd-highlight">
<a href="{{ link }}"><img class="imgsidebtn"
src="{% static 'clinic/img/{{ image }}' %}" /></a>
</div>
<div class="p-2 flex-fill bd-highlight">
<a href="{{ link }}" class="btn btn-primary">{{ imagetext }}</a>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
{% include "clinic/helpbar.html" with location="livelist" foo=bar %}
</div>
</div>
The problem is in showing the tag
<a href="{{ link }}"><img class="imgsidebtn"
src="{% static 'clinic/img/{{ image }}' %}" /></a>
in the rendered html. It is shown as:
<a href="/clinic/jeslineye/checkin"><img class="imgsidebtn"
src="/appointments/static/clinic/img/%7B%7B%20image%20%7D%7D"></a>
Why is this happening? How can I fix this?
A: You cannot use template variable inside static tag like this:
{% static 'clinic/img/{{ image }}' %}
Instead use with and add filter
{% with "clinic/img/"|add:image as image_url %}{% static image_url %}{% endwith %}
A: You cannot use a variable inside a {% static %} tag. What you can do is to use get-static-prefix and construct the URL manually. For example:
<img src="{% get_static_prefix %}clinic/img/{{ image }}">
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52867356",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: javascript generate square wave sound I want to generate a square wave sound using a signal "1 0 0 0". Each code (0,1) has a pattern as shown in picture.
For example, code 1 will produce a sound for 500µs and than stops for 1000µs.The signals should go from zero to maximum positive amplitude and will not have any negative amplitude.The frequency of the sound is 10KHz.
Basically i need to generate this sound from mobile devices (iPhone, Android and Windows phone 8). I am using Cordova framework. Any suggestions?
A: Check this
var frequency = 10000;
var data = {
1: {duration:500, sleep:1000},
0: {duration:500, sleep:500}
}
var audio = new window.webkitAudioContext();
//function creates an Oscillator. In this code we are creating an Oscillator for every tune, which help you control the gain.
//If you want, you can try creating the Oscillator once and stopping/starting it as you wish.
function createOscillator(freq, duration) {
var attack = 10, //duration it will take to increase volume full sound volume, makes it more natural
gain = audio.createGain(),
osc = audio.createOscillator();
gain.connect(audio.destination);
gain.gain.setValueAtTime(0, audio.currentTime); //change to "1" if you're not fadding in/out
gain.gain.linearRampToValueAtTime(1, audio.currentTime + attack / 1000); //remove if you don't want to fade in
gain.gain.linearRampToValueAtTime(0, audio.currentTime + duration / 1000); //remove if you don't want to fade out
osc.frequency.value = freq;
osc.type = "square";
osc.connect(gain);
osc.start(0);
setTimeout(function() {
osc.stop(0);
osc.disconnect(gain);
gain.disconnect(audio.destination);
}, duration)
}
function play() {
//your pattern
var song = [1,0,1,1];
timeForNext = 0;
for (i=0;i<song.length;i++){
duration = data[song[i]].duration;
//use timeout to delay next tune sound
window.setTimeout(function(){
createOscillator(frequency, duration);
},timeForNext);
timeForNext+=data[song[i]].sleep;
}
}
//play the music
play();
This link has some good info http://www.bit-101.com/blog/?p=3896 I used it to create a piano app with Cordova a while ago. Still haven't published it though.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32630211",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to find dependency conflict in Gradle I'm trying to add nineoldandroid lib to my project, but I can't find where my dependency problem occurs.
My dependencies:
dependencies {
compile files('src/main/libs/guice-3.0-no_aop.jar')
compile files('src/main/libs/javax.inject-1.jar')
compile files('src/main/libs/roboguice-2.0.jar')
compile files('src/main/libs/junit-4.11.jar')
compile files('src/main/libs/hamcrest-core-1.3.jar')
compile 'com.squareup:otto:1.3.5'
compile 'com.google.android.gms:play-services:6.1.11'
compile 'com.android.support:support-annotations:20.0.0'
compile 'com.android.support:appcompat-v7:21.0.0'
compile 'com.android.support:support-v4:21.0.0'
compile 'com.google.code.findbugs:jsr305:1.3.9'
compile 'io.nlopez.smartlocation:library:2.0.7'
compile ('com.nineoldandroids:library:2.4.0'){
exclude module: 'appcompat-v7'
exclude module: 'support-v4'
exclude module: 'support-annotations'
exclude group: 'com.google.android'
exclude group: 'com.google.android.*'
exclude group: 'com.google.code.findbugs'
exclude group: 'com.android.dx'
}
//compile project(':android-spinwheel')
}
Error I get:
Error:Execution failed for task ':app:dexDebug'.
> com.android.ide.common.internal.LoggedErrorException: Failed to run command:
/home/usr/soft/android-studio/sdk/build-tools/21.0.1/dx --dex --num-threads=4 --output /home/usr/vc/android-local/app/build/intermediates/dex/debug /home/usr/vc/android-local/app/build/intermediates/classes/debug /home/usr/vc/android-local/app/build/intermediates/dependency-cache/debug /home/usr/vc/android-local/app/build/intermediates/pre-dexed/debug/internal_impl-21.0.0-d8c58b966f1337ac583be7169abe38eafaaea523.jar /home/usr/vc/android-local/app/build/intermediates/pre-dexed/debug/hamcrest-core-1.3-42a42e6ec38e3a6ec6a99347d11a9296a04eca00.jar /home/usr/vc/android-local/app/build/intermediates/pre-dexed/debug/classes-3528df59bfffc0f1961007c5282087aa82de987f.jar /home/usr/vc/android-local/app/build/intermediates/pre-dexed/debug/guice-3.0-no_aop-91a65442530b2d5fb3bf96359d70d249985649f6.jar /home/usr/vc/android-local/app/build/intermediates/pre-dexed/debug/otto-1.3.5-c4d763fed0f5fe8a97ac31f49ba37d2cd1567ad8.jar /home/usr/vc/android-local/app/build/intermediates/pre-dexed/debug/classes-8250441981c0a4195e9e6068c3efdb149c0dedfd.jar /home/usr/vc/android-local/app/build/intermediates/pre-dexed/debug/classes-f112c8b8d83a64a7f22e07537d04c10f33f5ab35.jar /home/usr/vc/android-local/app/build/intermediates/pre-dexed/debug/jsr305-1.3.9-4b2d061766ae6ca309e240b50953cd2ffef968a0.jar /home/usr/vc/android-local/app/build/intermediates/pre-dexed/debug/roboguice-2.0-6654a0e822af0f9305ce06f00f0d4e61dfab50fd.jar /home/usr/vc/android-local/app/build/intermediates/pre-dexed/debug/classes-ae9e0725b0368edcf3df124ccecd0b5e1ad65358.jar /home/usr/vc/android-local/app/build/intermediates/pre-dexed/debug/javax.inject-1-f4b5053b6356ac4792c8e5f52c58c62ca27a07cb.jar /home/usr/vc/android-local/app/build/intermediates/pre-dexed/debug/junit-4.11-2882cc48337848b98707492071ee6cb29be1a828.jar /home/usr/vc/android-local/app/build/intermediates/pre-dexed/debug/library-2.4.0-75e51598c065016181fac0cecd368e796b5769a8.jar /home/usr/vc/android-local/app/build/intermediates/pre-dexed/debug/support-annotations-21.0.0-ecd4ef2c68ca29b6a76021f4c9ef5fc3656e79db.jar
Error Code:
2
Output:
UNEXPECTED TOP-LEVEL EXCEPTION:
com.android.dex.DexException: Multiple dex files define Lcom/nineoldandroids/animation/Animator$AnimatorListener;
at com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:596)
at com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:554)
at com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:535)
at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:171)
at com.android.dx.merge.DexMerger.merge(DexMerger.java:189)
at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:454)
at com.android.dx.command.dexer.Main.runMonoDex(Main.java:302)
at com.android.dx.command.dexer.Main.run(Main.java:245)
at com.android.dx.command.dexer.Main.main(Main.java:214)
at com.android.dx.command.Main.main(Main.java:106)
As you can see I have tried every exclude I can think of, I hope I'm using it the right way.
A: I am having a similar problem with yours but with Otto library. My problem is that I have a jar in my libs folder and I have added another version(branch) of the same library from maven repository. If I remove one of them this problem is solved but I need both of them. That's because I want to use AndroidAnnotations
But I cant figure out how I can do that.
Returning to your problem from what I can see you can solve it like this:
You have to find which one of the libraries that you have added has a dependency conflict with nineoldandroids library. You have to remove them one by one and find which one of them is. After you find that try to solve the conflict between these 2 libraries.
I hope this helps you.
A: The SpinnerWheel library you are using has an outdated version of nineoldandroids added as a jar. You will need to remove it and add the updated gradle dependency or update the jar to the version you specified in your primary gradle file.
In the most recent (as of this writing) I was doing the same thing, running into the same problem. It took a while to find because Android Studio was hiding the libs directory so I had to navigate to that folder to remove the jar.
If you are no longer using the SpinnerWheel library it will be the the same thing happening in one of your other dependencies.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26489788",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Setting minDate on datepicker in javascript I'm trying to set the minDate of a datepicker using the date that the user picked from another datepicker (i.e. check-in/check-out dates).
Here's my code:
var checkin = document.getElementById('check-in');
var checkout = document.getElementById('check-out');
var dateField;
$('#check-in').datepicker({
onSelect: function (date) {
dateField = $(this).val();
console.log(date);
},
altField: '#actual-checkin-date',
altFormat: 'mm/dd/yy',
dateFormat: 'dd/mm/yy',
minDate: 0
});
$('#check-out').datepicker({
altField: '#actual-checkout-date',
altFormat: 'mm/dd/yy',
dateFormat: 'dd/mm/yy',
minDate: new Date(dateField)
});
checkin.onclick = function () {
$('#check-in').datepicker();
};
checkout.onclick = function () {
$('#check-out').datepicker();
console.log($('#check-out').datepicker("option", "minDate"));
}
I can log the date from the check-in datepicker correctly, but I can't set that date as minDate of the check-out datepicker. The last log, the one in the last datapicker, shows me "Invalid Date", while the log in the first datapicker shows me the date in the dd/mm/yy format.
What am I doing wrong?
Thanks for the help!
A: You're running into two issues here:
1) when you create your check-out datepicker is created your dataField is not defined yet (it gets set once you select a data in your check-in datepicker)
2) you are not creating a valid Date - you can access the Date of a datepicker by using $('#check-in').datepicker("getDate")
take a look at this fiddle: http://jsfiddle.net/nerL43s5/ to see it in action.
$('#check-in').datepicker({
onSelect: function(date) {
console.log(date );
// now you have a date you can set as the minDate:
$('#check-out').datepicker('option', 'minDate', $('#check-in').datepicker('getDate'));
console.log($('#check-out').datepicker('option', 'minDate'));
},
altField: '#actual-checkin-date',
altFormat: 'mm/dd/yy',
dateFormat: 'dd/mm/yy',
minDate: 0
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44593726",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Styling echarts - Cannot modify title color Looking to work with the below chart, but cannot get to change the title color to white and the axis and axis numbers to grey (or white). This should go above a dark background. Does anybody knows how to change the title color with echarts ?
<script type="text/javascript">
// based on prepared DOM, initialize echarts instance
var myChart = echarts.init(document.getElementById('main'));
// specify chart configuration item and data
var option = {
title: {
text: 'Total memebers of the club',
fontColor: 'white',
display: true,
position: 'bottom'
},
tooltip: {},
legend: {
data: ['Total member']
},
xAxis: {
data: ["11/2018", "12/2018", "01/2019", "02/2019", "03/2019", "04/2019"]
},
yAxis: {},
series: [{
itemStyle: {normal: {color: 'white'}},
name: 'Total',
type: 'bar',
data: [5, 384, 612, 2344, 4670, 9372]
}]
};
// use configuration item and data specified to show chart
myChart.setOption(option);
</script>
A: Give this a try. Add it under 'text:' like:
text: 'Total memebers of the club',
textStyle: {
color: '#ed2d2e'
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55627466",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: War deployment using puppet in Jboss I have deployed the war in Jboss using puppet command and i checked the /standalone/deployments folder to check my .war file but i don't see any .war file there inside /standalone/deployments folder:
/opt/puppetlabs/bin/puppet apply --basemodulepath=/opt/alu/deploy/puppet/modules/ --hiera_config=/opt/install/hiera.yaml --execute ' class { profiles::jboss: }'
Ideally when we are doing manual deployment of .war file , we are putting the .war file inside /standalone/deployments folder.
My question is where can i check the .war which has deployed using puppet in Jboss server. My Jboss version is 6.0
A: Just complementing the answer, you can deploy directly on Jboss with a cli command and/or see the deployment status/content using the following commands:
#deployment-info
NAME RUNTIME-NAME PERSISTENT ENABLED STATUS
hibernate.war hibernate.war false true OK
#deployment=hibernate.war:read-attribute(name=content)
{
"outcome" => "success",
"result" => [{"hash" => bytes {
0x29, 0x93, 0x46, 0x13, 0xdd, 0x74, 0xff, 0x1d,
0xb7, 0x6e, 0xa6, 0xde, 0x60, 0xb3, 0x85, 0xf6,
0xae, 0x72, 0xc9, 0x0f
}}]
}
Q: Where can i check the .war which has deployed using puppet in Jboss server
A: You don't need another tool.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57459249",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I define vocabulary "tuples" in Bixby? I have an enum defining names of altbrains (publications) like so:
enum (AltBrainsNames) {
description (AltBrainsNames)
symbol (Inside the Helmet)
symbol (Impeachment Sage)
symbol (Iran Conflict Tracker)
symbol (Historical Carbon Dioxide Emissions)
symbol (Picard)
symbol (Quotation Bank)
symbol (US Elections)
}
With a corresponding vocab.bxb file to match variations on the names to these "official" names.
What I really want is the Bixby to pass along a string identifier that corresponds to each symbol -- like (Impeachment Sage, impeachmentsage) so that the identifier can be used as a parameter in a request to a restdb. What's a simple way of setting up these tuple relationships?
Fred
A: The symbol for your enum concept can be the string identifier in your restDb. Here's one pattern:
Modify your existing enum to follow this format
enum (AltBrainsNames) {
description (AltBrainsNames Identifiers)
symbol (insideTheHelmut)
symbol (impeachmentSage)
symbol (iranConflictTracker)
symbol (historicalCarbonDioxideEmissions)
symbol (picard)
symbol (quotationBank)
symbol (USElections)
}
Your tuple to connect the user-friendly name to the identifier.
structure (NameSelection) {
property (name) {
type (AltBrainsNames)
min (Required) max (One)
}
property (title) {
type (core.Text)
min (Required) max (One)
visibility (Private)
}
}
Get a list of names
action (GetAltBrainsNames) {
type(Constructor)
output (NameSelection)
}
Provide a list of names, and prompt the user to select one
action (MakeNameSelection) {
type(Calculation)
collect {
input (selection) {
type (NameSelection)
min (Required) max (One)
default-init {
intent {
goal: GetAltBrainsNames
}
}
}
}
output (AltBrainsNames)
}
Your vocabulary can support the user saying synonyms for symbol
vocab (AltBrainsNames) {
"insideTheHelmut" { "insideTheHelmut" "inside the helmut" "helmut"}
"impeachmentSage" { "impeachmentSage" "impeachment sage" "impeachment" "sage"}
"iranConflictTracker" {"iranConflictTracker" "iran conflict tracker"}
"historicalCarbonDioxideEmissions" { "historicalCarbonDioxideEmissions" "historical carbon dioxide emissions"}
"picard" { "picard"}
"quotationBank" {"quotationBank" "quotation bank" "quotations"}
"USElections" {"USElections" "us elections" }
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59940672",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Ruby on Rails: How to send a specific/chosen record from one table (User) to another with a button from user interface I started off with Ruby one week ago. My project is to make a Restaurant reservation webpage. I made the User table that contains Users name/last name/address/email/password/password confirmation info, I also made another table called Friends that contains name/last name/address/email.
The current user is able to add a friend to the Friend table when pressing a Button (Add) by the users row in the table of all existing Users. So, by clicking the button by the specific user info that the current user selected, the specific user info (name/last name/address/email) will be copied to the current user friend table.
The database I am using is Sqlite.
Here is the users_controller:
class UsersController < ApplicationController
before_filter :save_login_state, :only => [:new, :create]
def index
@user = User.all
end
def new
#Signup Form
@user = User.new
end
def show
redirect_to(:controller => 'sessions', :action => 'login')
flash[:notice] = "Successful!"
flash[:color]= "valid"
end
def edit
@user = User.find(params[:id])
end
def update
@user = User.find(params[:id])
if @user.update(user_params)
redirect_to @user
else
render 'edit'
end
end
def create
@user = User.new(user_params)
if @user.save
redirect_to(:action => 'login')
else
flash[:notice] = "Form is invalid"
flash[:color]= "invalid"
render "new"
end
end
private
def user_params
params.require(:user).permit(:email, :password, :password_confirmation, :ime, :prezime, :adresa)
end
end
User index.html.erb:
<table class="table table-striped sortable">
<thead>
<tr class="tr1">
<th class="th2">E-mail</th>
<th class="th2">Ime</th>
<th class="th2">Prezime</th>
<th class="th2">Adresa</th>
</tr>
</thead>
<tbody>
<% @user.each do |users| %>
<tr class="tr1">
<td><%= users.email %></td>
<td><%= users.ime %></td>
<td><%= users.prezime %></td>
<td><%= users.adresa %></td>
<td><%= link_to 'Edit', edit_user_path(users)%></td>
</tr>
<% end %>
</tbody>
</table>
User new.html.erb:
<% @page_title = "UserAuth | Signup" %>
<div class="Sign_Form">
<h1>Registracija</h1>
<%= form_for(@user) do |f| %>
<table class="table4">
<tr><th class="th1"> Email: </th><th><%= f.text_field :email%></th></tr>
<tr><th class="th1"> Password: </th><th><%= f.password_field :password%></th></tr>
<tr><th class="th1"> Repeat password: </th><th><%= f.password_field :password_confirmation%></th></tr>
<tr><th class="th1"> Ime: </th><th><%= f.text_field :ime%></th></tr>
<tr><th class="th1"> Prezime: </th><th><%= f.text_field :prezime%></th></tr>
<tr><th class="th1"> Adresa: </th><th><%= f.text_field :adresa%></th></tr>
</table>
<div align="left"><%= f.submit :"Sign Up" %></div>
<% end %>
<% if @user.errors.any? %>
<ul class="Signup_Errors">
<% for message_error in @user.errors.full_messages %>
<li>* <%= message_error %></li>
<% end %>
</ul>
<% end %>
</div>
user.rb:
class User < ActiveRecord::Base
attr_accessor :password
before_save :encrypt_password
after_save :clear_password
EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/
validates :ime, :presence => true
validates :prezime, :presence => true
validates :adresa, :presence => true
validates :email, :presence => true, :uniqueness => true, :format => EMAIL_REGEX
validates :password, :presence => true, length: { minimum: 6 }, :confirmation => true
#Only on Create so other actions like update password attribute can be nil
#attr_accessible :username, :email, :password, :password_confirmation
def self.authenticate(email="", login_password="")
if EMAIL_REGEX.match(email)
user = User.find_by_email(email)
end
if user && user.match_password(login_password)
return user
else
return false
end
end
def match_password(login_password="")
encrypted_password == BCrypt::Engine.hash_secret(login_password, salt)
end
def encrypt_password
unless password.blank?
self.salt = BCrypt::Engine.generate_salt
self.encrypted_password = BCrypt::Engine.hash_secret(password, salt)
end
end
def clear_password
self.password = nil
end
end
create_users:
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :email
t.string :encrypted_password
t.string :salt
t.string :ime
t.string :prezime
t.string :adresa
t.timestamps
t.timestamps null: false
end
end
end
A: You will need a controller for Friendships e.g. FriendshipsController. Your Add button should point to an action in FriendshipsController which will copy the parameters you provide.
*
*In your view you should have something like this:
<%= button_to "Add friend", friendships_path(:name => user.name, :email => user.email ...) %>
*FriendshipsController:
def create
# handle params here (you can get user's data from params[:name], params[:email] and such
# e.g. @friendship = Friendship.create(:name => params[:name], ...)
end
Also consider this article http://railscasts.com/episodes/163-self-referential-association explaining self referential association in Rails.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36687623",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SQL Server: ODBC Connection pooling / C API I want to clarify how to do connection pooling with SQL Server from C, using ODBC. I know this question is, like.... sooooo 1998, but... I've never done it in C, so... here goes:
First I think I have to set the attribute to enable pooling:
rc = SQLSetEnvAttr( NULL, // make process level cursor pooling
SQL_ATTR_CONNECTION_POOLING,
(SQLPOINTER)SQL_CP_ONE_PER_DRIVER,
SQL_IS_INTEGER);
Then allocate the HENV and set it for ODBC3.0:
rc = SQLAllocHandle(SQL_HANDLE_ENV, NULL, &henv1);
rc = SQLSetEnvAttr(henv1, SQL_ATTR_ODBC_VERSION, (void *)SQL_OV_ODBC3, 0);
Questions
*
*Is it correct that I can use the HENV allocated above, in multiple concurrent threads within a single process, as I call SQLAllocHandle to allocate db connections (HDBC)?
*When I want to use connection from the pool, is it correct that the typical sequence is:
*
*SQLAllocHandle to get connection handle (HDBC)
*SQLDriverConnect/[SQLConnect to connect on that handle
*SQLExecute/SQLExecDirect + a series of SQLFetch, to use the connection
*SQLDisconnect
*SQLFreeConnect
*Is there a significant latency benefit if I save the allocated HDBC handle, and re-use it across multiple SQLDriverConnect + SQLDisconnect calls? In other words, I'd skip steps 2.1 and 2.5, for each use of the connection. Or are steps 2.1 and 2.5 basically just malloc/free? (in which case, I don't think I care).
In this particular scenario, the C app will likely be the only application accessing the SQL Server from this box. But it's going to run within a IIS environment, and that means it will be potentially multi-process and each process will be multi-threaded.
I'll be getting and using that connection within the scope of a HTTP Request, so I'll want it to be as fast, efficient, and scalable as possible.
A: I did research this then writing the odbc-api bindings for Rust. It turns out it is (still) well documented here: https://learn.microsoft.com/en-us/sql/odbc/reference/develop-app/driver-manager-connection-pooling
Your code for activating and using ODBC connection pooling is correct. Now to your questions:
*
*Is it correct that I can use the HENV allocated above, in multiple concurrent threads within a single process, as I call SQLAllocHandle to allocate db connections (HDBC)?
Yes, you can use the environment in multiple concurrent threads. Not only that, it is actually best practice to do so, and have only one ODBC environment for each process.
*When I want to use connection from the pool, is it correct that the typical sequence is: [...]
Yes, the described sequence is reasonable. Of course all depends on the application.
*Is there a significant latency benefit if I save the allocated HDBC handle, and re-use it across multiple SQLDriverConnect + SQLDisconnect calls? In other words, I'd skip steps 2.1 and 2.5, for each use of the connection. Or are steps 2.1 and 2.5 basically just malloc/free? (in which case, I don't think I care)
This depends both on your driver and your definition of 'significant'. Overall any ODBC call incurs some overhead due to it being a function call into a dynamic library (the driver manager). If that specific function call is driver specific (like SqlAllocHandle), it is then forwarded to the driver which is also a dynamically loaded library.
Yet if the driver has any sense it wont send any data around the network, so usually you would not care and it most likely boils down to a somewhat expensive call to malloc/free. So yeah, depends on your definition of 'significant'.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2776443",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: PHP DOMDocument - Get all elements on the first top-level I would like to find all elements in the $content without children.
With my actual code, I find all elements with child (strong, ahref, ...).
$html = new DOMDocument();
$html->resolveExternals = false;
$html->preserveWhiteSpace = false;
$html->substituteEntities = false;
libxml_use_internal_errors(true);
$html->loadHTML(mb_convert_encoding($content, 'HTML-ENTITIES', 'UTF-8'), LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
libxml_clear_errors();
/** @var DOMElement $node */
foreach ($html->documentElement as $node) {
dump($node->nodeName, $node->nodeValue);
}
My $content variable is:
<p>lorem</p>
<p><strong>lorem</strong> ipsum dolor sit amet</p>
<h2>test</h2>
<p>test</p>
I want get all elements p, and hX to detect if it's a paragraph, or figure in paragraph, or title, etc...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65953595",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Accessing smarty multidimensional array values using jquery I have an array being passed from php which looks like:
$resultsArr[123]['A']='q';
$resultsArr[123]['B']='d';
$resultsArr[113]['C']='s';
$resultsArr[113]['A']='ss';
$resultsArr[113]['B']='sd';
$resultsArr[111]['C']='sds';
$resultsArr[111]['A']='vv';
$resultsArr[111]['B']='vv';
i need to access certain values frmo this array using jquery.
i am trying to access it like
keyVal = 123; //dynamically generated
var pri = '~$results['keyVal']['B']`'
but i am getting a blank value in variable 'pri'
How can this be solved?
A: Could you not convert it to a JSON Array and then use it directly in Javascript, rather than picking out individual elements of the array?
<script>
var myArray = <?php echo json_encode($resultsArr); ?>;
</script>
Then use jQuery each to read the array.
This would give you greater flexibility in the long term of what was available to javascript for reading and manipulation.
EDIT
You can read a specific element like so, this will alert "vv":
<script>
var myVar = myArray[111].A;
alert(myVar);
</script>
A: In php use :
$ResultsArr = json_encode($resultsArr);
$this->jsonResultsArr = $ResultsArr; //its seems u r using smarty.
In javascript
jsonResultsArr = "~$jsonResultsArr`";
requireValue = jsonResultsArr[111].A;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11842446",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Mercurial insert CURRENT revision number in files on hg archive I need the current version (version of the latest file) and it's tag to be included in files when I do hg archive.
When using keywords extension in includes the latest version of each file, not the current version.
Example:
repository contents:
file1 Jan 1st 2013 latest change tag v2.0
file2 Mar 1st 2013 latest change tag v1.0
What I need is to generate archive for v2.0 and automatically insert "v2.0" in each file, even if it hasn't been changed under 2.0 changeset.
A: This is better done in your build/packaging/release system not in your source control system. Since you're using hg archive (great choice) then theres a .hg_archive.txt file that's available to your packaging scripts or you can pass it to your release script as a parameter.
You're better off putting something like VERSION_GOES_HERE in your files and when you're archiving do:
LATEST_TAG="$(hg log --template '{latesttag}' -r)"
perl -pie "s/VERSION_GOES_HERE/${LATEST_TAG"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17529540",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: df.query("'string'") produces ValueError: NumExpr 2 does not support Unicode as a dtype If anyone has a solution for how I can get this to work please let me know. I would prefer not downgrading python to 2.x.
I have tried to remaps some of the columns to different dtypes. I think python 3.x may be storing strings as unicode and perhaps pandas and/or numexpr does not support this with the versions I am on.
*
*pandas 1.1.5
*numexpr 2.8.1
*numpy 1.19.5
*python 3.6.9
data = [['tom', 10], ['nick', 15], ['juli', 14]]
df = pd.DataFrame(data, columns=['Name', 'Age'])
df['Name'] = df['Name'].astype('string')
df.dtypes
df.query("'tom'")
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-37-a5f548d874ef> in <module>()
7 df['Name'] = df['Name'].astype('string')
8 df.dtypes
----> 9 df.query("'tom'")
/usr/local/lib/python3.6/dist-packages/pandas/core/frame.py in query(self, expr, inplace, **kwargs)
3343 kwargs["level"] = kwargs.pop("level", 0) + 1
3344 kwargs["target"] = None
-> 3345 res = self.eval(expr, **kwargs)
3346
3347 try:
/usr/local/lib/python3.6/dist-packages/pandas/core/frame.py in eval(self, expr, inplace, **kwargs)
3473 kwargs["resolvers"] = kwargs.get("resolvers", ()) + tuple(resolvers)
3474
-> 3475 return _eval(expr, inplace=inplace, **kwargs)
3476
3477 def select_dtypes(self, include=None, exclude=None) -> "DataFrame":
/usr/local/lib/python3.6/dist-packages/pandas/core/computation/eval.py in eval(expr, parser, engine, truediv, local_dict, global_dict, resolvers, level, target, inplace)
344 eng = _engines[engine]
345 eng_inst = eng(parsed_expr)
--> 346 ret = eng_inst.evaluate()
347
348 if parsed_expr.assigner is None:
/usr/local/lib/python3.6/dist-packages/pandas/core/computation/engines.py in evaluate(self)
71
72 # make sure no names in resolvers and locals/globals clash
---> 73 res = self._evaluate()
74 return reconstruct_object(
75 self.result_type, res, self.aligned_axes, self.expr.terms.return_type
/usr/local/lib/python3.6/dist-packages/pandas/core/computation/engines.py in _evaluate(self)
112 scope = env.full_scope
113 _check_ne_builtin_clash(self.expr)
--> 114 return ne.evaluate(s, local_dict=scope)
115
116
~/.local/lib/python3.6/site-packages/numexpr/necompiler.py in evaluate(ex, local_dict, global_dict, out, order, casting, **kwargs)
813 # Create a signature
814 signature = [(name, getType(arg)) for (name, arg) in
--> 815 zip(names, arguments)]
816
817 # Look up numexpr if possible.
~/.local/lib/python3.6/site-packages/numexpr/necompiler.py in <listcomp>(.0)
812
813 # Create a signature
--> 814 signature = [(name, getType(arg)) for (name, arg) in
815 zip(names, arguments)]
816
~/.local/lib/python3.6/site-packages/numexpr/necompiler.py in getType(a)
689 return bytes
690 if kind == 'U':
--> 691 raise ValueError('NumExpr 2 does not support Unicode as a dtype.')
692 raise ValueError("unknown type %s" % a.dtype.name)
693
ValueError: NumExpr 2 does not support Unicode as a dtype.
A: The only reason you have a scuffed error message that references anything about dtypes, is because you're using the NumExpr engine.
Here, using the python engine, getting a KeyError is clearer:
>>> df.query("'tom'", engine='python')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/bert2me/miniconda3/envs/deleteme/lib/python3.6/site-packages/pandas/core/frame.py", line 3348, in query
result = self.loc[res]
File "/home/bert2me/miniconda3/envs/deleteme/lib/python3.6/site-packages/pandas/core/indexing.py", line 879, in __getitem__
return self._getitem_axis(maybe_callable, axis=axis)
File "/home/bert2me/miniconda3/envs/deleteme/lib/python3.6/site-packages/pandas/core/indexing.py", line 1110, in _getitem_axis
return self._get_label(key, axis=axis)
File "/home/bert2me/miniconda3/envs/deleteme/lib/python3.6/site-packages/pandas/core/indexing.py", line 1059, in _get_label
return self.obj.xs(label, axis=axis)
File "/home/bert2me/miniconda3/envs/deleteme/lib/python3.6/site-packages/pandas/core/generic.py", line 3493, in xs
loc = self.index.get_loc(key)
File "/home/bert2me/miniconda3/envs/deleteme/lib/python3.6/site-packages/pandas/core/indexes/range.py", line 358, in get_loc
raise KeyError(key)
KeyError: 'tom'
As wjandrea pointed out... this isn't a valid query statement to begin with... did you mean?:
>>> df.query("Name == 'tom'")
Name Age
0 tom 10
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74168017",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Ionic 4, Keyboard moves content I have this html in my ionic project
<ion-header>
<ion-toolbar mode="ios">
<ion-searchbar>
</ion-searchbar>
<ion-title>
</ion-title>
</ion-toolbar>
<ion-list class="m-0-p-0">
<ion-item *ngFor="let user of users">
</ion-item>
</ion-list>
</ion-header>
<ion-content scrollY="false">
<ion-grid>
<ion-row class="centered">
....
</ion-row>
</ion-grid>
</ion-content>
this is my centered class:
.centered{
position:fixed ;
width:100%;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
So, when i go into the searchbar, when the keyboard is showing up, the content of the center is moving up. I searched on the web for solutions but it seems that things have changed in ionic 4 and i cannot do: Keyboard.disableScroll(true).. or can I?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54784427",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to use STLPort in my kernel? I am developing a kernel in C++. But I do not want to write a stdlib; for that purpose I have downloaded STLport http://www.stlport.org/, but I don't know how to install and use it.
I am using Linux for building my kernel.
How can I use c++ standard libs in my kernel?
And I do not want to port all libs from STLport. How can I exclude a selection of libs? Like std::string, std::vector etc.
A: I would probably advise against using the STL in Kernel development. STL will assume some form of standard library support of which there is none in your kernel. Also most memory allocation operations have no bounds for the time that they can take and are therefore unsuitable for use in interrupt handlers. Exceptions are another thing that can cause major headaches in the kernel
A: In order for STL to work you have to port several things like static initialization (for i.e. std::cin and std::cout) and stack unwinding...
you'd have to port i.e.: libsupc++ and have that in your kernel.
Basically all this stuff shouldn't be in the Kernel in the first place. DON'T use Vectors use static arrays because vectors might reallocate your data!
also all that stuff will bloat your kernel for nothing!
you can have a look what L4 allows itself to be used in kernel. they don't do memory allocation and they don't do exceptions (unpredictable) and they especially don't do STL.
The latter links shall give you an idea what you need to port to get c++ operating system support. Libsupc++ is part of gcc. it's purpose is to encapsulate all the parts where runtime code is needed.
Useful information about libsupc++
Useful information about c++ operating system support
A: I am not sure whether STL in kernel is actually good to have, but if you really want to try, it's very fun. I have written my own OS and when I had memory allocation in the kernel, the first thing I did was porting STLport (5.2.1). It was working well so far, although the kernel itself is still too preliminary.
Anyway, I can share some experience on porting it.
*Porting STLport requires no building and very few prerequisites, just include the headers and let the compiler know it's path (-I option for gcc). The template classes will be compiled with your cpp source files.
*STLport is configurable, you can disable what you can't afford and select what you want, such as iostream, debug, exception, RTTI and threading. Just checkout the documentation and then get to the configuration headers, it's very nicely commented (e.g. stlport/stl/config/user_config.h)
*As the most basic you'll need malloc and free, or maybe new, delete and variants. That's enough for porting std string, containers and algorithms, IIRC. But it's neither thread safe nor memory allocation optimized, you need to be very careful when you rely on it.
*You can do you own iostream, it's just template classes and global objects (BTW, I hacked ELF sections and manually initialized my global objects by calling the functions), but this needs more work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7470346",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Duende IdentityServer 6.20 .Net6.0 "AuthenticationScheme: idsrv was not authenticated" I have a fully functioning Duende IS6 solution, servicing an Angular client. However the Seq log output contains a lot of these entries with each request:
{
"@t": "2023-01-08T19:14:58.3783602Z",
"@mt": "AuthenticationScheme: {AuthenticationScheme} was not authenticated.",
"@m": "AuthenticationScheme: idsrv was not authenticated.",
"@i": "19c670d5",
"@l": "Debug",
"AuthenticationScheme": "idsrv",
"EventId": {
"Id": 9,
"Name": "AuthenticationSchemeNotAuthenticated"
},
"SourceContext": "Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler",
"RequestId": "0HMNHLIGV47GF:00000002",
"RequestPath": "/.well-known/openid-configuration/jwks",
"ConnectionId": "0HMNHLIGV47GF",
"application": "dev.identity"
}
Does anyone know what the issue is here? To be clear, my app functions and authenticates just fine so whatever it is doesn't appear to be causing an issue, just filling up my logs.
(apols for earlier version tag but could not tag identityserver6 as not enough rep)
A: The error is because ASP.NET Core did not find any cookie that it could convert into a ClaimsPrincipal user.
As you mention, requests to "/.well-known/openid-configuration/jwks" is never made by the browser, instead its made by the client and apis on the backend to retrieve the signing keys. And in these requests, there is no cookie to authenticate.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75051049",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to copy cell range as table from excel to powerpoint - VBA I cant find any way to do this. What I have now is that it copy the range as an image:
Dim XLApp As Excel.Application
Dim PPSlide As Slide
Set XLApp = GetObject(, "Excel.Application")
XLApp.Range("A1:B17").Select
XLApp.Selection.CopyPicture Appearance:=xlScreen, Format:=xlPicture
PPSlide.Shapes.Paste.Select
this works like a charm, but is it possible to get it to copy the range as a table instead of picture?
A: Yes, it is possible. If you write something like this:
XLApp.Selection.Copy
PPSlide.Shapes.PasteSpecial ppPasteOLEObject
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3838819",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Telosys 3 not generating Identity annotation I am using Telosys to generate my DAL layer from database and it is working smoothly. However I have noticed that it only generates field annotation for Identity fields as AUTO
@GeneratedValue(strategy=GenerationType.AUTO)
I have in my database primary key fields set to Identity and a sequence is provided by Postgres. But when I generate my entity class it only shows annotation as AUTO whereas I want it to generate Idendityt:
@GeneratedValue(strategy=GenerationType.IDENTITY)
I checked the source code for JPAAnnotations class and it has the logic to generated IDENTITY annotation.
Am I missing something?
Also, how can I upgrade my eclipse plugin to use Telosys 4.x version?
Thank you Telosys team.
A: Telosys 4 is not yet available as an Eclipse plugin (work in progress).
In the meantime, you can use Telosys CLI.
NB : since version 4 there is a unique model type : the "DSL model", is you are starting from an existing database the DSL model will be created from the database schema (instead of the previous specific "database model" based on XML)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72999104",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to watch nb-Model at child? I am using ui-select inside a controller, I need to listen for changes for the ng-model from the controller, here is my HTML:
<div id="countryCtrl" country-selection class="form-inline">
<ui-select ng-model="selectedCountry" theme="selectize" style="{{$cat_style}}">
<ui-select-match placeholder="Select or search ...">
@{{$select.selected.title}}
</ui-select-match>
<ui-select-choices repeat="country in countries | filter: $select.search">
<span ng-bind-html="country.title | highlight: $select.search"></span>
</ui-select-choices>
</ui-select>
</div>
In the countrySelection controller:
angular.module('mainCtrl').directive('countrySelection', ['Country','state', function(Country, state) {
var linkF = function (scope, element, attrs, widgetPath) {
scope.$watch("selectedCountry", function (neww, old) {
console.log(scope.selectedCountry);
widgetPath.selectedCountry= widgetPath.model.selectedCountry;
scope.update("state.country.changed",scope.selectedCountry);//widgetPath.model.selectedCountry);
}, true);
};
return {
require: "^widgetPath",
restrict: 'A',
link: linkF,
scope: {}
}
}]);
watch would work if I set the country-selection at the ui-select directive as an attribute like this:
<ui-select ng-model="selectedCountry" country-selection theme="selectize" style="{{$cat_style}}">
but, then, I won't be able to isolate the scope for country-selection and I will get error
Multiple directives [countrySelection, uiSelect] asking for new/isolated scope on:
So, how would I watch ng-Model attribute at ui-select directive from the parent directive country-selection ?
A: There is an on-select attribute, from there you can call a function on your scope.
<ui-select ng-model="person.selected" theme="select2" on-select="someFunction($item, $model)" ...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29605175",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: selecting element by partial string that was loaded cannot grab value I am currently working on an application that already has an existing functionality of loading information that i need to parse together with ajax calls loading this information in. I am having an issue selecting an element value on the loaded document in that it is not returning a value to me based on the dom element which it IS selecting (tested by highlighting) and it is the only element being selected. The jQuery code snippet in question is :
$('.viewComponent').each(function(){
//run ajax call to get the components
var foodId = $(this).nextAll('input[name$=".code"]').val();
$('#createComponentDialog').load('getComoponent.do', "foodID=" + foodId);
calories = $('#createComponentDialog :input[name*="Calories"]').val();
});
So as you can see for each component im loading the query and then trying to select a single field that is populated by the query to enter into another area later after doing some math however the val is returning as: "" The dom element that its selecting in one instance of this is inside the id tag area but as loaded:
<li><label for="nutrients['Calories'].quantity">Calories</label><input id="nutrients'Calories'.quantity" name="nutrients['Calories'].quantity" class="text number" type="text" value="31.0" disabled="disabled"> kcal</li>
I included the label so if that would be an issue I am not sure, i have also run length debug and it is still not returning anything but a length of 1 so there is only one of these addressed inputs in the document that i can find with the jquery tags so im not dual selecting something.
This is fully running on a spring mvc stack so thats why there are some funky names going on.
EDIT: I found the problem with my script wasnt just there now i have a new issue and with it, a bit more of a snippet this time, maybe some sense can be had:
$('input.nutritionFacts').live('click', function(e){
var servings = $('#servings').val();
var calories = 0;
var servSize = 0;
$('.weight').each(function(){
servSize += parseFloat($(this).val());
});
$('#servSize').html(servSize);
$('#servCont').html(servings);
//for each component
$('.viewComponent').each(function(){
//run ajax call to get the components
var foodId = $(this).nextAll('input[name$=".code"]').val();
var weight = $(this).nextAll('.weight').val();
$('#createComponentDialog').load('getComponent.do', "foodId=" + foodId, function(){
console.log("loaded" + foodId + "successfully");
});
calories += parseFloat($("input[name*='Calories']").val());
});
$('#calories').html(calories);
//run against weight from get components result
//sum into form frame for nutritionfacts
$('#nutritionFacts').dialog();
console.log("loaded nutrients");
});
This is my current script, after doing many many tests, breakpoints for some reason were pausing and causing issues however it does populate data to the popup im creating properly now!
I as you can see am running a log and its ALWAYS firing line for "loaded nutrients" in my log FIRST Why would it do that?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18514198",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: MongoDB Object Serialized as JSON I'm attempting to send a JSON encoded MongoDB object back in my HTTP response. I've followed several other similar questions but am still missing something. No exceptions are thrown, but I get a cryptic <api.views.MongoEncoder object at 0x80a0c02c> response in the browser. I'm sure it's something simple, but any help would be appreciated.
Function:
from django.utils.simplejson import JSONEncoder
from pymongo.objectid import ObjectId
class MongoEncoder( JSONEncoder ):
def _iterencode( self, o, markers = None ):
if isinstance( o, ObjectId ):
return """ObjectId("%s")""" % str(o)
else:
return JSONEncoder._iterencode(self, o, markers)
views.py:
user = User({
's_email': request.GET.get('s_email', ''),
's_password': request.GET.get('s_password', ''),
's_first_name': request.GET.get('s_first_name', ''),
's_last_name': request.GET.get('s_last_name', ''),
'd_birthdate': request.GET.get('d_birthdate', ''),
's_gender': request.GET.get('s_gender', ''),
's_city': request.GET.get('s_city', ''),
's_state': request.GET.get('s_state', ''),
})
response = {
's_status': 'success',
'data': user
}
return HttpResponse(MongoEncoder( response ))
I'm on Python 2.4, pymongo, simplejson.
A: In newer versions of simplejson (and the json module in Python 2.7) you implement the default method in your subclasses:
from json import JSONEncoder
from pymongo.objectid import ObjectId
class MongoEncoder(JSONEncoder):
def default(self, obj, **kwargs):
if isinstance(obj, ObjectId):
return str(obj)
else:
return JSONEncoder.default(obj, **kwargs)
You could then use the encoder with MongoEncoder().encode(obj) or json.dumps(obj, cls=MongoEncoder).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6255387",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: JQuery Moving 30 boxes from left to right, then right to right I'm learning Jquery right now and I'm stuck on how I move my boxes from left to right, then right to left. They have a delay meter that I can use as well to change the speed. I just don't know what I'm missing to make the boxes move in the two specified directions (Left To Right, Right To Left). I'm assuming it's something simple, that's usually the case. But, I'm not sure what to change. Any Help would be greatly appreciated.
Here is my code:
var easingsList = [
"swing",
"easeInQuad",
"easeOutQuad",
"easeInOutQuad",
"easeInCubic",
"easeOutCubic",
"easeInOutCubic",
"easeInQuart",
"easeOutQuart",
"easeInOutQuart",
"easeInQuint",
"easeOutQuint",
"easeInOutQuint",
"easeInSine",
"easeOutSine",
"easeInOutSine",
"easeInExpo",
"easeOutExpo",
"easeInOutExpo",
"easeInCirc",
"easeOutCirc",
"easeInOutCirc",
"easeInElastic",
"easeOutElastic",
"easeInOutElastic",
"easeInBack",
"easeOutBack",
"easeInOutBack",
"easeInBounce",
"easeOutBounce"
];
var moveRight = function(){
var n = 0;
var e = easingsList[n];
var d = parseInt($("#delay").val());
moveBoxRight(n, e, d);
var n = 1;
var e = easingsList[n];
var d = parseInt($("#delay").val());
moveBoxRight(n, e, d);
}
var moveLeft = function(){
var n = 0;
var e = easingsList[n];
var d = parseInt($)"#delay").val());
moveBoxLeft (n, e, d);
var n = 1;
var e = easingsList[n];
var d = parseInt($("#delay").val());
moveBoxLeft(n, e, d);
}
var moveBoxRight= function(n, easing, duration)
{
var id = "#button" + n.toString();
var pageWidth = $("body").width();
var boxWidth = 150;
$(id).animate({"margin-left":pageWidth-boxWidth + "px"}, duration, easing);
}
var moveBoxLeft= function(n, easing, duration)
{
var id = "#button" + n.toString();
var pageWidth = $("body").width();
var boxWidth = 150;
$(id).animate({"margin-left" : "0px"}, duration, easing);
}
*******and heres my HTML*********
<!doctype html>
<html>
<head>
<title> jQuery animate()</title>
<script src="jquery-1.11.3.js" type="text/javascript">
</script>
<script src="jquery.easing.1.3.js" type="text/javascript">
</script>
<script src="test.js" type="text/javascript">
</script>
<style>
body
{
margin: 0;
}
.button{
height:50px;
width:150px;
display: block;
border: solid 1px black;
text-align: center;
text-decoration: none;
margin-bottom: 10px;
line-height: 50px;
}
</style>
</head>
<body>
<h1> jQuery Animate Easing Examples </h1>
<input placeholder='delay; 100ms, 1s etc.' id='delay'>
<input placeholder='end color; rgb(0,0,0), #000000, rgba(0,0,0,1) etc.' id='endColor'>
<br>
<a href='javascript:moveLeft()' class='link' id='button1'> Move Left </a>
<a href='javascript:moveRight()' class='link' style='float:right' id='button1'> Move Right </a>
<div class='button' id='button0'> swing </div>
<div class='button' id='button1'>easeInQuad</div>
<div class='button' id='button2'>easOutQuad</div>
<div class='button' id='button3'>easeInOutQuad</div>
<div class='button' id='button4'>easeInCubic</div>
<div class='button' id='button5'>easeOutCubic</div>
<div class='button' id='button6'>easeInOutCubic</div>
<div class='button' id='button7'>easeInQuart</div>
<div class='button' id='button8'>easeOutQuart</div>
<div class='button' id='button9'>easeInOutQuart</div>
<div class='button' id='button10'>easInQuint</div>
<div class='button' id='button11'>easeOutQuint</div>
<div class='button' id='button12'>easeInOutQuint</div>
<div class='button' id='button13'>easeInSine</div>
<div class='button' id='button14'>easeOutSine</div>
<div class='button' id='button15'>easeInOutSine</div>
<div class='button' id='button16'>easeInExpo</div>
<div class='button' id='button17'>easeOutExpo</div>
<div class='button' id='button18'>easeInOutExpo</div>
<div class='button' id='button19'>easeInCirc</div>
<div class='button' id='button20'>easeOutCirc</div>
<div class='button' id='buton21'>easeInOutCirc</div>
<div class='button' id='button22'>easeInElasic</div>
<div class='button' id='button23'>easeOutElastic</div>
<div class='button' id='button24'>easeInOutElatic</div>
<div class='button' id='button25'>easeInBack</div>
<div class='button' id='button26'>easeOutBack</div>
<div class='button' id='button27'>easeInOutBack</div>
<div class='button' id='button28'>easeInBounce</div>
<div class='button' id='button29'>easeOutBounce</div>
</div>
</body>
</html>
A: In my opinion, your approach can be improved altogether
*
*Firstly, animating the margin property of an element is not a good way to move it left and right. Making the element fixed and animating the left and right properties would work much better.
*Secondly, you could greatly simplify the code by using an attribute on the button to determine direction instead of writing duplicated code with just a few words different for moving left vs right.
*Also, your calling your variable delay but using that variable to set the animation's duration which is misleading. You should re-name that duration
Here's how I would do it:
var easingsList = [
"swing",
"easeInQuad",
"easeOutQuad",
"easeInOutQuad",
"easeInCubic",
"easeOutCubic",
"easeInOutCubic",
"easeInQuart",
"easeOutQuart",
"easeInOutQuart",
"easeInQuint",
"easeOutQuint",
"easeInOutQuint",
"easeInSine",
"easeOutSine",
"easeInOutSine",
"easeInExpo",
"easeOutExpo",
"easeInOutExpo",
"easeInCirc",
"easeOutCirc",
"easeInOutCirc",
"easeInElastic",
"easeOutElastic",
"easeInOutElastic",
"easeInBack",
"easeOutBack",
"easeInOutBack",
"easeInBounce",
"easeOutBounce"
];
$('.move').click(function(){
var $this=$(this);
var duration = parseInt($("#duration").val());
var direction = $(this).data('direction');
var n =0;
moveBox($('.box').eq(n), easingsList[n], duration, direction);
moveBox($('.box').eq(n+1), easingsList[n+1], duration, direction);
});
function moveBox($element, easing, duration, direction) {
var pageWidth = $("body").width();
var boxWidth = $element.width();
$element.css('right','auto').css('left','auto');
var options = {duration:duration,easing:easing};
var properties ={};
properties[direction]=pageWidth - boxWidth + "px";
$element.stop().animate(properties,options);
}
body {
margin: 0;
}
.box {
height: 50px;
width: 150px;
display: block;
border: solid 1px black;
text-align: center;
text-decoration: none;
margin-bottom: 10px;
line-height: 50px;
position:fixed;
}
.box-holder{
width: 100%;
position:relative;
height: 50px;
margin-bottom: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script>
<h1> jQuery Animate Easing Examples </h1>
<input placeholder='duration; 100ms, 1s etc.' id='duration' value="3000">
<input placeholder='end color; rgb(0,0,0), #000000, rgba(0,0,0,1) etc.' id='endColor'>
<br>
<a href='#' class='link move' data-direction="right" > Move Left </a>
<a href='#' class='link move' data-direction="left" style='float:right'> Move Right </a>
<div class="box-holder"><div class="box"> swing </div> </div>
<div class="box-holder"><div class="box">easeInQuad</div></div>
<div class="box-holder"><div class="box">easOutQuad</div></div>
<div class="box-holder"><div class="box">easeInOutQuad</div></div>
<div class="box-holder"><div class="box">easeInCubic</div></div>
<div class="box-holder"><div class="box">easeOutCubic</div></div>
<div class="box-holder"><div class="box">easeInOutCubic</div></div>
<div class="box-holder"><div class="box">easeInQuart</div></div>
<div class="box-holder"><div class="box">easeOutQuart</div></div>
<div class="box-holder"><div class="box">easeInOutQuart</div></div>
<div class="box-holder"><div class="box">easInQuint</div></div>
<div class="box-holder"><div class="box">easeOutQuint</div></div>
<div class="box-holder"><div class="box">easeInOutQuint</div></div>
<div class="box-holder"><div class="box">easeInSine</div></div>
<div class="box-holder"><div class="box">easeOutSine</div></div>
<div class="box-holder"><div class="box">easeInOutSine</div></div>
<div class="box-holder"><div class="box">easeInExpo</div></div>
<div class="box-holder"><div class="box">easeOutExpo</div></div>
<div class="box-holder"><div class="box">easeInOutExpo</div></div>
<div class="box-holder"><div class="box">easeInCirc</div></div>
<div class="box-holder"><div class="box">easeOutCirc</div></div>
<div class="box-holder"><div class="box">easeInOutCirc</div></div>
<div class="box-holder"><div class="box">easeInElasic</div></div>
<div class="box-holder"><div class="box">easeOutElastic</div></div>
<div class="box-holder"><div class="box">easeInOutElatic</div></div>
<div class="box-holder"><div class="box">easeInBack</div></div>
<div class="box-holder"><div class="box">easeOutBack</div></div>
<div class="box-holder"><div class="box">easeInOutBack</div></div>
<div class="box-holder"><div class="box">easeInBounce</div></div>
<div class="box-holder"><div class="box">easeOutBounce</div></div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35108716",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Get looked up array count for a document i have 2 collections : words and phrases
Each word document has an array of phrases id's. And each phrase can be active or inactive.
For example :
words : {"word" => "hello", phrases => [1,2]}{"word" => "table", phrases => [2]}
phrases :{"id" => 1, "phrase" => "hello world!", "active" => 1}{"id" => 2, "phrase" => "hello, i have already bought new table", "active" => 0}
I need to get count of active phrases for each word.
In php i do it like this:
1. get all words
2. for each word get count of active phrases with condition ['active' => 1]
Question: How can i get words with active phrases count in one request? I tried to use MapReduce, but i need to make a request for each word to get count of active phrases.
UPD:
In my test collection there are 92 000 phrases and 23 000 words.
I have already tested both variant: with php loop for each word in which i get phrases count and aggreagation function in mongo.
But i changed aggregation pipeline in commets below because of phrases_data. It is array, so i can't use $match on it. I use $unwind after $lookup.
[ '$unwind' => '$5'],
[
'$lookup' => [
'from' => 'phrases_926ee3bc9fa72b029e028ec90e282072ea0721d1',
'localField' => '5',
'foreignField' => '0',
'as' => 'phrases_data'
]
],
[ '$unwind' => '$phrases_data'],
[ '$match' => [ 'phrases_data.3' => 77] ], //phrases_data.3 => 77 it is similar to phrases_data.active => 1
[ '$group' =>
[
'_id' => ['word' => '$1', 'id' => '$0'],
'active_count' => [ '$sum' => 1]
]
],
[ '$match' => [ 'active_count' => ['$gt' => 0]] ],
[ '$sort' =>
[
'active_count' => -1
]
]
The problem is that $group command take 80% of process time. And it is much slower than php loop. Here is my results for test collection:
1. Php loop (get words-> get phrases count for each word): 10 seconds
2. Aggregation function : 20 seconds
A: db.words.aggregate([
{ "$unwind" : "$phrases"},
{
"$lookup": {
"from": "phrases",
"localField": "phrases",
"foreignField": "id",
"as": "phrases_data"
}
},
{ "$match" : { "phrases_data.active" : 1} },
{ "$group" : {
"_id" : "$word",
"active_count" : { $sum : 1 }
}
}
]);
You can use above aggregation pipeline :
*
*Unwind the phrases array from words collection documen as separate document
*do a lookup(join) in phrases collection using unwinded phrases
*filter the phrases and check for active using $match
*Finally group phrases by word and count using $sum : 1
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43821447",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: r - Overall mean of elements in list by rows and columns I need to take the overall mean in each row and column within a list of data.frames:
set.seed(1)
df_1 = data.frame(a = rnorm(3), b = rnorm(3), c = rnorm(3))
df_2 = data.frame(a = rnorm(3), b = rnorm(3), c = rnorm(3))
df_3 = data.frame(a = rnorm(3), b = rnorm(3), c = rnorm(3))
df_lst = list(df_1, df_2, df_3)
Here I need to do the following:
mean(c(df_lst[[1]]$a[1], df_lst[[2]]$a[1], df_lst[[3]]$a[1]))
mean(c(df_lst[[1]]$a[2], df_lst[[2]]$a[2], df_lst[[3]]$a[2]))
mean(c(df_lst[[1]]$a[3], df_lst[[2]]$a[3], df_lst[[3]]$a[3]))
mean(c(df_lst[[1]]$b[1], df_lst[[2]]$b[1], df_lst[[3]]$b[1]))
mean(c(df_lst[[1]]$b[2], df_lst[[2]]$b[2], df_lst[[3]]$b[2]))
mean(c(df_lst[[1]]$b[3], df_lst[[2]]$b[3], df_lst[[3]]$b[3]))
mean(c(df_lst[[1]]$c[1], df_lst[[2]]$c[1], df_lst[[3]]$c[1]))
mean(c(df_lst[[1]]$c[2], df_lst[[2]]$c[2], df_lst[[3]]$c[2]))
mean(c(df_lst[[1]]$c[3], df_lst[[2]]$c[3], df_lst[[3]]$c[3]))
And the desired output is:
> out
a b c
1 -0.03687367 0.5853922 0.3541071
2 0.76310860 -0.6035424 0.2220019
3 0.15773067 -0.5616297 0.4546074
Any suggestion?
A: We can use Reduce to get the elementwise sum (+) and then divide by the length of the list
Reduce(`+`, df_lst)/length(df_lst)
# a b c
#1 -0.03687367 0.5853922 0.3541071
#2 0.76310860 -0.6035424 0.2220019
#3 0.15773067 -0.5616297 0.4546074
Or convert it to an array and then use apply
apply(array(unlist(df_lst), c(3, 3, 3)), 1:2, mean)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56019781",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android - cz.msebera.android.httpclient.entity.ByteArrayEntity required: org.apache.http.HttpEntity I am using loopj AsyncHttpClient to call web services. I am trying register a user. So I need to send JSON data to Web Service.
ByteArrayEntity entity = new ByteArrayEntity(json.toString().getBytes("UTF-8"));
entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
client.post(getApplicationContext(), "http://10.0.3.2:8080/WebService/rest/user/insert", entity, new JsonHttpResponseHandler(){
When I put cursor on the entity in client.post line it gives this error.
cz.msebera.android.httpclient.entity.ByteArrayEntity required: org.apache.http.HttpEntity
Example That I am trying is also from stack-overflow - Send JSON as a POST request to server by AsyncHttpClient
Libraries that I am using
compile files('libs/android-async-http-1.4.4.jar')
compile 'cz.msebera.android:httpclient:4.3.6'
Anybody can help me? Thanks in advance.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49949643",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Error in Sqlite query in android I need to find a string in a column and return another column containing the value. I have the string value "xyx " .. The space is creating unknown characters so I want to look if it has just xyz and I am getting the following error
cursor = sqlDb.query(MYTABLE,
thecolumns, NAME + " LIKE '" + name + "'", null, null, null, null);
04-07 10:31:38.302: W/dalvikvm(18987): threadid=1: thread exiting with uncaught exception (group=0x41884da0)
04-07 10:31:38.372: E/AndroidRuntime(18987): FATAL EXCEPTION: main
04-07 10:31:38.372: E/AndroidRuntime(18987): Process: com.myproject, PID: 18987
04-07 10:31:38.372: E/AndroidRuntime(18987): android.database.sqlite.SQLiteException: unrecognized token: "'%xyz" (code 1): , while compiling: **SELECT column FROM TABLE_NAME WHERE Name LIKE '%xyz��������������������������������������������������������������������%'**
04-07 10:31:38.372: E/AndroidRuntime(18987): at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
04-07 10:31:38.372: E/AndroidRuntime(18987): at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1113)
04-07 10:31:38.372: E/AndroidRuntime(18987): at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:690)
04-07 10:31:38.372: E/AndroidRuntime(18987): at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
04-07 10:31:38.372: E/AndroidRuntime(18987): at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:59)
04-07 10:31:38.372: E/AndroidRuntime(18987): at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
04-07 10:31:38.372: E/AndroidRuntime(18987): at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
04-07 10:31:38.372: E/AndroidRuntime(18987): at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1435)
04-07 10:31:38.372: E/AndroidRuntime(18987): at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1282)
04-07 10:31:38.372: E/AndroidRuntime(18987): at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1153)
04-07 10:31:38.372: E/AndroidRuntime(18987): at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1321)
A: Check if the apostrophes are valid, but to avoid this use the selection args with the ? operator.
cursor = sqlDb.query(MYTABLE,
thecolumns, NAME + " LIKE ?", new String[]{"%" + name + "%"}, null, null, null);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29497820",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: I have a "TypeError: 'float' object is not iterable" when I want to convert the second number in the float too def pl():
num1=float(ent.get())
ent.delete(0, END)
num2=float(ent.get())
result=sum(num1, num2)
ent.insert(END, result)
When I want to sum both of the numbers this error happens. It says I cannot convert string number to the float one.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72355289",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Problems trying to find the root category based on category id I am trying to figure out the root level category_id of a category based on it's parent_id.
In the function below $this->cat_arr is an array of all categories and their parent_id's.
If a parent_id is set to 0 it is assumed to be a root node. I wish to loop through the array until I find the parent_id of passed $cat_id.
function getRoot($cat_id) {
foreach ($this->cat_arr as $row) {
if ($row->cat_id == $cat_id && $row->parent_id == 0) {
return $row->cat_id;
break;
} else {
$this->getRoot($row->parent_id);
}
}
}
In my application I only call this function when I know $cat_id is not at the root level (because the parent_id is greater than 0), but when I try to run this it gets stuck in an infinite loop.
Is my logic flawed, or am I missing something simple?
A: Try this:
function getRoot($cat_id) {
foreach ($this->cat_arr as $row) {
if ($row->cat_id == $cat_id && $row->parent_id == 0) {
return $row->cat_id;
}
}
return $this->getRoot($row->parent_id);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4941268",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to make AesEncrypterHandler encrypt the same way as Aes does I am trying to use AesCryptoServiceProvider to achieve the same encryption mechanism as Aes.
Here is my AesCryptoServiceProvider version of it:
public string version1(string plainText, string encryptionKey, string initializationVector)
{
AesCryptoServiceProvider provider = new AesCryptoServiceProvider
{
BlockSize = 128,
Padding = PaddingMode.PKCS7,
Key = Convert.FromBase64String(encryptionKey),
IV = Encoding.UTF8.GetBytes(initializationVector)
};
byte[] buffer = Encoding.ASCII.GetBytes(plainText);
byte[] encrypted = provider.CreateEncryptor().TransformFinalBlock(buffer, 0, buffer.Length);
return Convert.ToBase64String(encrypted);
}
And here is the Aes version of it:
public string version2(string plainText, string encryptionKey, string initializationVector)
{
byte[] clearBytes = Encoding.UTF8.GetBytes(plainText);
byte[] encryptedBytes;
byte[] iv = Encoding.UTF8.GetBytes(initializationVector);
using (Aes aes = Aes.Create())
{
aes.BlockSize = 128;
aes.Padding = PaddingMode.PKCS7;
aes.Key = Convert.FromBase64String(encryptionKey);
aes.IV = iv;
using (MemoryStream ms = new MemoryStream())
using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
encryptedBytes = ms.ToArray();
}
}
byte[] ivEncryptedBytes = new byte[iv.Length + encryptedBytes.Length];
Buffer.BlockCopy(iv, 0, ivEncryptedBytes, 0, iv.Length);
Buffer.BlockCopy(encryptedBytes, 0, ivEncryptedBytes, iv.Length, encryptedBytes.Length);
return Convert.ToBase64String(ivEncryptedBytes);
}
When I encrypt the same string using version1 and version2 they came out to be different. Any idea on how these two methods are different and how I can make version1 produces the same encrypted string as version2? (p.s. I am rather new to encryption so sorry if the answer is obvious) Thanks!
A: As @MichaelFehr pointed out, version2 only has the initialization vector and the encrypted bytes concatenated together before converting the bytes back to string. I have tested that if I concatenate the string the same way as version2 in version1, the result string will become the same.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62293059",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What are anonymous hashes in perl? $hash = { 'Man' => 'Bill',
'Woman' => 'Mary,
'Dog' => 'Ben'
};
What exactly do Perl's “anonymous hashes” do?
A: It's quite simple. They allow you to write
push @hashes, { ... };
f(config => { ... });
instead of
my %hash = ( ... );
push @hashes, \%hash;
my %config = ( ... );
f(config => \%config);
(If you want to know the purpose of references, that's another story entirely.)
A: Anything "anonymous" is a data structure that used in a way where it does not get a name.
Your question has confused everyone else on this page, because your example shows you giving a name to the hash you created, thus it is no longer anonymous.
For example - if you have a subroutine and you want to return a hash, you could write this code:-
return {'hello'=>123};
since it has no name there - it is anonymous. Read on to unwind the extra confusion other people have added on this page by introducing references, which are not the same thing.
This is another anonymous hash (an empty one):
{}
This is an anonymous hash with something in it:
{'foo'=>123}
This is an anonymous (empty) array:
[]
This is an anonymous array with something in it:
['foo',123]
Most of the time when people use these things, they are really trying to magically put them inside of other data structures, without the bother of giving them a waste-of-time temporary name when they do this.
For example - you might want to have a hash in the middle of an array!
@array=(1,2,{foo=>3});
that array has 3 elements - the last element is a hash! ($array[2]->{foo} is 3)
perl -e '@array=(1,2,{foo=>1});use Data::Dumper;print Data::Dumper->Dump([\@array],["\@array"]);'
$@array = [
1,
2,
{
'foo' => 1
}
];
Sometimes you want to don't want to pass around an entire data structure, instead, you just want to use a pointer or reference to the data structure. In perl, you can do this by adding a "\" in front of a variable;
%hashcopy=%myhash; # this duplicates the hash
$myhash{test}=2; # does not affect %hashcopy
$hashpointer=\%myhash; # this gives us a different way to access the same hash
$hashpointer->{test}=2;# changes %myhash
$$hashpointer{test}=2; # identical to above (notice double $$)
If you're crazy, you can even have references to anonymous hashes:
perl -e 'print [],\[],{},\{}'
ARRAY(0x10eed48)REF(0x110b7a8)HASH(0x10eee38)REF(0x110b808)
and sometimes perl is clever enough to know you really meant reference, even when you didn't specifically say so, like my first "return" example:
perl -e 'sub tst{ return {foo=>bar}; }; $var=&tst();use Data::Dumper;print Data::Dumper->Dump([\$var],["\$var"]);'
$var = \{
'foo' => 'bar'
};
or:-
perl -e 'sub tst{ return {foo=>bar}; }; $var=&tst(); print "$$var{foo}\n$var->{foo}\n"'
bar
bar
A: It is a reference to a hash that can be stored in a scalar variable. It is exactly like a regular hash, except that the curly brackets {...} creates a reference to a hash.
Note the usage of different parentheses in these examples:
%hash = ( foo => "bar" ); # regular hash
$hash = { foo => "bar" }; # reference to anonymous (unnamed) hash
$href = \%hash; # reference to named hash %hash
This is useful to be able to do, if you for example want to pass a hash as an argument to a subroutine:
foo(\%hash, $arg1, $arg2);
sub foo {
my ($hash, @args) = @_;
...
}
And it is a way to create a multilevel hash:
my %hash = ( foo => { bar => "baz" } ); # $hash{foo}{bar} is now "baz"
A: You use an anonymous hash when you need reference to a hash and a named hash is inconvenient or unnecessary. For instance, if you wanted to pass a hash to a subroutine, you could write
my %hash = (a => 1, b => 2);
mysub(\%hash);
but if there is no need to access the hash through its name %hash you could equivalently write
mysub( {a => 1, b => 2} );
This comes in handy wherever you need a reference to a hash, and particularly when you are building nested data structures. Instead of
my %person1 = ( age => 34, position => 'captain' );
my %person2 = ( age => 28, position => 'boatswain' );
my %person3 = ( age => 18, position => 'cabin boy' );
my %crew = (
bill => \%person1,
ben => \%person2,
weed => \%person3,
);
you can write just
my %crew = (
bill => { age => 34, position => 'captain' },
ben => { age => 28, position => 'boatswain' },
weed => { age => 18, position => 'cabin boy' },
);
and to add a member,
$crew{jess} = { age => 4, position => "ship's cat" };
is a lot neater than
my %newperson = ( age => 4, position => "ship's cat" );
$crew{jess} = \%newperson;
and of course, even if a hash is created with a name, if its reference is passed elsewhere then there may be no way of using that original name, so it must be treated as anonymous. For instance in
my $crew_member = $crew{bill}
$crew_member is now effectively a reference to an anonymous hash, regardless of how the data was originally constructed. Even if the data is (in some scope) still accessible as %person1 there is no general way of knowing that, and the data can be accessed only by its reference.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14175585",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
} |
Q: Why is this regular expression matching so much? I am trying to use http://www.regexr.com/ to create a regular expression.
Basically I am looking to replace something that matches <Openings>any other tags/text</Openings>
<Openings><opening><item><x>3</x><y>3</y><width>10.5</width><height>13.5</height><type>rectangle</type><clipX>0</clipX><clipY>0</clipY><imgsrc></imgsrc></item></opening></Openings>
I started with ([\<Openings\>])\w+ (http://regexr.com/393mv ) but it seems to be matching too many things. Right now that regular expression should only match <Openings>.
A: Regex to match the whole Openings tag is,
<Openings>.*?<\/Openings>
If you want to capture the contents inside the Openings tag then try the below,
<Openings>(.*?)<\/Openings>
A: ([\<Openings\>])\w+
The brackets mean "Match any character in this". You should use
(\<Openings\>)\w+
which matches specifically "<Openings>" plus one or more word characters.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24554136",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Invalid Root In Registry Key in reading IExplorer VBA I have a code that tries to run an IExplorer that would load a google map. Anyways, It bugs everytime it tries to run the code where it reads the HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\" & "App Paths\IEXPLORE.EXE\
with the error: Invalid Root in registry key
Dim obj_FSO As Object
Dim obj_Shell As Object
Dim str_IEVersion As String
Dim StrArray() As String
Dim iVersion As Integer
Set obj_FSO = CreateObject("scripting.filesystemobject")
Set obj_Shell = CreateObject("wscript.shell")
str_IEVersion = obj_FSO.GetFileVersion(obj_Shell.RegRead("HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\" & "App Paths\IEXPLORE.EXE\"))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70331508",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Can I check multiple ancestors in JavaScript using Element.closest()? I have a verbose condition:
if (
(e.target.parentNode.classList[0] === 'my-class') ||
(e.target.parentNode.parentNode.classList[0] === 'my-class') ||
(e.target.parentNode.parentNode.parentNode.classList[0] === 'my-class')
) {
/* [... CODE HERE...] */
}
In some contexts, I can easily imagine the condition extending to 5 lines or more.
I am aware that I can write a recursive function which checks if the next higher-up ancestor node is not <body> and, if not, runs the same recursive function on that node.
But given that Element.closest() exists:
See: https://developer.mozilla.org/en-US/docs/Web/API/Element/closest
is there a simpler way I can write the condition, something along the lines of:
if (e.target.closest('.my-class') !== false) {
/* [... CODE HERE...] */
}
A: From the summary:
If there isn't such an ancestor, it returns null.
So:
if (e.target.closest('.my-class') !== null)
In the event that e.target itself may be a .my-class, and you want to exclude that, you need to start from the element's parent:
if (e.target.parentNode.closest('.my-class') !== null)
but if e.target is guaranteed never to be a .my-class the first example will suffice.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49474956",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to pass React component as regular JS to react-test-renderer I see only examples with components in JSX.
But how to pass a component as regular JS React.createElement() instead of JSX something like
const testRenderer = ReactTestRenderer.create(
React.createElement('div', null, 'Text');
);
Now with this code I get the error
missing ) after argument list
ps. React on Node.js
A: This is how you would do it. (Meaning almost like you did it)
(https://reactjs.org/docs/react-api.html#createelement)
But you have an extra semicolon inside the create argument list.
const testRenderer = ReactTestRenderer.create(
React.createElement('div', null, 'Text')
);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70112835",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Get status of ICommand execute in WPF in order to update text on xaml I have a view model which looks like:
public sealed class MyViewModel: INotifyPropertyChanged
{
public bool ShowSuccess
{
get { return _success; }
set
{
_success = value;
PropertyChanged?.Invoke( ... );
}
}
public ICommand TestCommand
{
get
{
_test = _test ?? new MyTestCommand();
return _test;
}
}
}
and the command
public sealed class MyTestCommand : ICommand
{
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
// do stuff
}
}
and in xaml
<Button Command="{Binding TestCommand}" Content="Test" />
I want to update ShowSuccess property after executing Execute from MyTestCommand.
How to achieve that ?
Thanks
PS: I'm still newbie in WPF, just learned MVVM and custom command
A: You can use DelegateCommand for this. Which helps you use one Generic class for all commands instead of creating individual Command classes.
public sealed class MyViewModel : INotifyPropertyChanged
{
private ICommand _test;
private bool _success;
public bool ShowSuccess
{
get { return _success; }
set
{
_success = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(ShowSuccess)));
}
}
public ICommand TestCommand
{
get
{
_test = _test ?? new DelegateCommand((arg) => ShowSuccess = true);
return _test;
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
public class DelegateCommand : ICommand
{
private readonly Predicate<object> _canExecute;
private readonly Action<object> _execute;
public event EventHandler CanExecuteChanged;
public DelegateCommand(Action<object> execute)
: this(execute, null)
{
}
public DelegateCommand(Action<object> execute,
Predicate<object> canExecute)
{
_execute = execute;
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
if (_canExecute == null)
{
return true;
}
return _canExecute(parameter);
}
public void Execute(object parameter)
{
_execute(parameter);
}
public void RaiseCanExecuteChanged()
{
CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
}
A: I strongly recomment taking a look at ReactiveUI - UI framework based around Rx - you don't have to use all of its features, like built in dependency injection or view location, but it's also very cool. It's not worth to reinvent the wheel in this case.
It has an implementation of ICommand that not only supports asynchronous work out of the box, it also allows commands to return stuff (VERY usefull) and takes care of disabling buttons when executing.
It also comes with DynamicData - a cure to all problems related to collections.
So, most basic sample would be:
TestCommand = ReactiveCommand.CreateFromTask<int>(async paramater =>{
var result = await DoStuff(parameter); // ConfigureAwait(false) might be helpful in more complex scenarios
return result + 5;
}
TestCommand.Log(this) // there is some customization available here
.Subscribe(x => SomeVmProperty = x;); // this always runs on Dispatcher out of the box
TestCommand.ThrownExceptions.Log(this).Subscribe(ex => HandleError(ex));
this.WhenAnyValue(x => x.SearchText) // every time property changes
.Throttle(TimeSpan.FromMilliseconds(150)) // wait 150 ms after the last change
.Select(x => SearchText)
.InvokeCommand(Search); // we pass SearchText as a parameter to Search command, error handling is done by subscribing to Search.ThrownExceptions. This will also automatically disable all buttons bound to Search command
What is even more useful, I think, is being able to subscribe in the View code behind.
// LoginView.xaml.cs
ViewModel.Login.Where(x => !x.Success).Subscribe(_ =>{
PasswordBox.Clear();
PasswordBox.Focus();
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59928357",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to draw a circumference in a graph in Excel (eventually with macro) I´d like to draw a circumference in a graph in Excel based on a radius value written in a cell.
I know how to draw Circle by macro but not in an Excel Graph.
Any help are welcome
Thx so much
M.
A: Your best bet would be to do some off to the side calculations. For example, with columns t, X, and Y:
*
*Your first point (x, y) will be any point on the circle with radius r.
*Your next point will use the math here https://www.mathopenref.com/coordparamcircle.html based on the first point and whatever t you wish (smaller increments will produce a more accurate circle)
*Keep using that math until you hit 360 degrees.
Assuming r = 5, centered at (5, 10), and using t increments of 0.25:
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47448107",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Cant find imgs:s when React.js project is bundled with webpack2 Everything works in development, all images are found. But when I bundle my the files and upload to webhost, product img:s can't be found and returns error:
This is my .htaccess:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>
This is my webpack.config.prod.js file:
// PRODUCTION
const webpack = require('webpack');
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const entry = {
app: path.join(process.cwd(), 'src/app.js')
}
const output = {
path: path.join(__dirname, 'dist'),
filename: 'bundle.min.js',
}
const plugins = [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production')
}),
new webpack.optimize.UglifyJsPlugin({
mangle: false,
compress: {
warnings: false
}
}),
new ExtractTextPlugin('bundle.css'), // creation of HTML files to serve your webpack bundles
new HtmlWebpackPlugin({
template: 'index-template.html'
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'bundle',
filename: '[name].common.js'
})
]
const config = {
context: path.join(__dirname, 'src'),
entry: entry,
output: output,
devtool: "source-map",
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
include: path.join(__dirname, 'src'),
use: "babel-loader"
},
{
test: /\.(png|jpg|gif)$/,
use: [{
loader: 'url-loader',
options: { limit: 10000, name: './img/[name].[ext]' } // Convert images < 10k to base64 strings (all in img folder)
}]
},
{
test: /\.(sass|scss)$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
'css-loader',
{
loader: 'postcss-loader',
options: {
plugins: (loader) => [ require('autoprefixer')() ]
}
},
'sass-loader',
]
})
}
]
},
plugins: plugins,
externals: {
jquery: 'jQuery'
}
}
module.exports = config;
Images are imported in my product product component under lifecycle event "componentDidMount":
import React, { Component } from 'react';
import Modal from 'react-modal';
import PropTypes from 'prop-types';
// Custom styles for Modal image
const customStyles = {
content : {
top : '50%',
left : '50%',
right : 'auto',
bottom : 'auto',
marginRight : '-50%',
transform : 'translate(-50%, -50%)',
background : 'rgba(0, 0, 0, 0.8)',
width : '100vw',
height : '100vh',
display : 'flex',
justifyContent : 'center',
alignItems : 'center'
}
};
class ProductItem extends Component {
constructor(props) {
super(props);
this.state = {
modalIsOpen: false,
image: '',
previewImg: ''
};
this.openModal = this.openModal.bind(this);
this.closeModal = this.closeModal.bind(this);
}
// Set state object "modalIsOpen" to true when click on <ProductItem/> component
openModal() {
this.setState({
modalIsOpen: true
});
}
// Set state object "modalIsOpen" to false when click on <Modal/> component
closeModal() {
this.setState({
modalIsOpen: false
});
}
render(){
// Create variables for all <ProductItem/> description options. If <PoductItem/> object has props or state, render it. Otherwise return null.
var img = this.state.image ?
<img src={this.state.image} /> :
null;
const name = this.props.product.stocked ?
<h3>{this.props.product.name}</h3> :
<h3><span style={{color: 'red'}}>
{this.props.product.name}
</span></h3>;
var limited = this.props.product.limited ?
<p>begränsad upplaga: {this.props.product.limited} ex</p> :
null;
var available = this.props.product.available ?
<p>tillgängliga: {this.props.product.available} ex</p> :
null;
var price = this.props.product.price ?
<p>{this.props.product.price} kr</p> :
null;
var type = this.props.product.type ?
<p>{this.props.product.type}</p> :
null;
var size = this.props.product.size ?
<p>{this.props.product.size} cm</p> :
null;
var desc = this.props.product.desc ?
<p>{this.props.product.desc}</p> :
null;
var modalName = this.props.product.name ?
<h2>{this.props.product.name}</h2> :
null;
var modalDesc = this.props.product.desc ?
<h2>{this.props.product.desc}</h2> :
null;
return (
<div className="product hvr-sink" onClick={this.openModal}>
<Modal
isOpen={this.state.modalIsOpen}
onRequestClose={this.closeModal}
style={customStyles}
contentLabel="Modal image"
>
<div className="modal-box" onClick={this.closeModal}>
<div className="close" onClick={this.closeModal}>x</div>
<img className="modal-img" src={this.state.previewImg}/>
{modalName}
{modalDesc}
</div>
</Modal>
{img}
{name}
{type}
{limited}
{available}
{size}
{price}
{desc}
</div>
);
};
// Import all thumbnail + previewImg images and then() put them into state. If rejection occures catch() returns rejection reasen (err).
componentDidMount() {
import(`./images/${this.props.product.thumbnail}`).then(
(image) => this.setState({
image: image
})
).catch((err) => {
console.log('error thumbnail' + err);
});
import(`./images/${this.props.product.previewImg}`).then(
(previewImg) => this.setState({
previewImg: previewImg
})
).catch((err) => {
console.log('error previewImg' + err);
});
}
};
// Components expected proptypes
ProductItem.propTypes = {
product: PropTypes.object.isRequired
}
export default ProductItem;
All this works in development environment, images render no problem. Also, my background image and other img work that are being inserted via SASS:
.background-img {
position: fixed;
background: url(../images/main.jpg) no-repeat center center scroll;
background-size: cover;
z-index: 0;
}
or via "import" as ex "magdaImg":
A: It turned out to be a problem with my project not being located in the root.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44462250",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What is the story of the Observer Design Pattern? I have been investigating about the observer pattern for an assignment. So far, I have come to the conclusion that it first appeared in a book written by a group of people called "The Gang of Four".
But I also read that its first implementation was in a SmallTalk MVC-based framework.
Is there an origin to the observer pattern? Who designed it first? Which of the GoF members did it? Has it suffered any changes since its creation?
Also, some implementations of the pattern include what they call a "ConcreteSubject" which is a generalization of the Subject class. Is this a variation of the pattern, or rather an evolution from the original model?
A: The Gang of Four's main contribution to Design Patterns is really giving names to some commonly-used patterns to assist communication of design intent. It's so much easier to write
// this is an observer
than a big ol' block of comments that no one will read. And if people shared the jargon, developers can communicate more effectively.
The Observer pattern has been around long before OO programming. Most often it was referred to using the term "callback", often implemented with function pointers in various languages, or perhaps even a flag that was used to indicate which function/procedure/subroutine should be called. This represented one of the earliest forms of abstract communication between modules. I've even seen similar approaches taken in assembler languages - storing a callback address and using it to indirectly notify that "something happened".
A big thing to remember... the implementations that the Gang of Four show in the Design Patterns book are not "absolute" - they're there to demonstrate an approach. You can just as easily implement the Observer pattern with a function pointer as you can with an abstract class, interface, or C# delegate.
(I teach a Design Patterns course at Johns Hopkins, btw ;) )
A: What The Gang of Four did wasn't invent patterns, they observed and researched the software field at the time in order to catalog the solutions to the common problems faced by developers.
As for who initially invented it your guess is as good as mine I suppose. Although I'll be interested if anyone do know who invented it. In my opinion it's like asking who invented fire...
ConcreteSubject refers to the implementation of the Subject interface. And it's not a variation it's simply necessary to have a interface to facilitate the pattern. (or a super class but an interface is much more better).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16599899",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How does the Windows Python Launcher (py.exe) find the python executable(s)? I'm trying to use the Windows Python Launcher (py.exe) for the first time. I run python in a command shell but the launcher, running in the same shell, can't find any version of python.exe to run:
where python
C:\Python38\python.exe
py --list
Installed Pythons found by py Launcher for Windows
No Installed Pythons Found!
Obviously there is something missing in my configuration but I'm at a loss as to what. I've been digging into the registery and have located keys in:
HKEY_LOCAL_MACHINE/SOFTWARE/Wow6432Node/Python/PyLauncher
HKEY_LOCAL_MACHINE/SOFTWARE/Wow6432Node/Python/PythonCore
but there isn't anything that references any executables.
Any help appreciated!
A: You was on the right path. In your case, you would need to add the the following entries in the registry:
[HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\3.8]
[HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\3.8\InstallPath]
@="C:\\python38\\"
"ExecutablePath"="C:\\Python38\\python.exe"
"WindowedExecutablePath"="C:\\Python38\\pythonw.exe"
Also answered in py launcher does not find my Python 2.7
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66824903",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Hiding .aspx from url in ASP.NET Framework 3.5 I would require to hide .aspx extension and query sting values from complete url. I have tried many solution online but didn't succeeded.
After long search I have found one sample code article (linked below):
http://www.aspsnippets.com/Articles/How-to-hide-remove-ASPX-extension-in-URL-in-ASPNet.aspx
Now, in this article it's given at starting that it would build using Framework 3.5 & Service Pack 1.
Even I have checked the Visual Studio 2008 I have installed on my machine is Framework 3.5 & SP1. Therefore I have tried this application.
But there are some issues while I have tried this solution.
ie:
*
*As we have to import Routing package (System.Web.Routing), I have imported it, but it didn't recognized. Then I have manually referenced the Routing package from .NET Libararies.
*After that it didn't recognizing the method of (routes.MapPageRoute).
*This method is being used to manually set the alias for url, but it shows me Blue Underline under this method and on running it shows me the message as (MapPageRoute is not a member of System.Web.Routing.RouteCollection).
so, please guide me according to this solution.
A: it's available only on .net framework 4.0 & 4.5
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27287344",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Frameless window shows dark border on linux I created a dialog with shadow effect
Qt::WindowFlags flags = Qt::Dialog| Qt::FramelessWindowHint;
QGraphicsDropShadowEffect* effect = new QGraphicsDropShadowEffect;
effect->setOffset(4);
effect->setBlurRadius(9);
contWdget->setGraphicsEffect(effect);
This works perfect on windows but when I open the same dialog in Linux its showing dark black color border around the dialog.
What work around I need to do to make it work on Linux.
A: 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
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46604835",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Focus randomly jumps when scrolling I have an activity with many EditText controls and checkboxes near them. By default, most EditTexts are disabled.
When I open the activity, some random EditText control gets focus (a frame around it) and if you tap on it, the on-screen keyboard appears even though the EditText is disabled and no text appears when you press the on-screen keys.
Also, my whole layout is wrapped in a ScrollView. When you scroll, some random EditTexts get focus. It can be the lowest visible one, or the highest visible, or sometimes one in the middle, sometimes one outside the visible area.
Because a random element of the layout gets focus, the Activity gets randomly scrolled down when you open it, which is pretty annoying.
I guess it's an Android's bug, but is there a workaround?
Stop EditText from gaining focus at Activity startup handles the situation with only 1 EditText for which you can tell to lose focus so that the dummy element could gain it. In my case the dummy element doesn't gain focus, both in onResume or onCreate, with both android:focusable="true" android:focusableInTouchMode="true"
Should I check all the EditText controls (there are 12 of them) and tell them to lose focus? What with scrolling, because it seems focus randomly jumps.
A: Because of the implementation of the fling Method in the ScrollView -
it is sufficient to override the findFocus(), so that it will return this
to prevent the focus from jumping around when scrolling.
@Override
public View findFocus() {
return this;
}
A: It's not scrolling that randomly focuses the EditText. It's when the scrollview handles a fling event. If you overwrite the fling method the won't be any random focus changes.
Then if you want the fling functionality back you'll need to write your own fling method. There's code here you can copy from:
Smooth scrolling in Android
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6679294",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: I have a linked table which is linked to a .txt file in my directory itself I have a linked table which is linked to a .txt file in my directory itself. Now I need to create a command button in a Form which helps me to relink the .txt file whenever I require, using VBA code.
Can anyone please help me on this.
A: You don't have to. The file/data will be read "as is" whenever you open the table.
If you wish to update the text file, just replace it with the new file.
A: Thanks for the reply. But i need to refresh my linked table anyway. So i found this code helpful.
Private Sub Command3_Click()
Dim b As Boolean
b = RefreshLinkedTables() End Sub
Function RefreshLinkedTables() As Boolean
Dim db As DAO.Database
Dim tb As DAO.TableDef
Dim fld As DAO.Field
Set db = CurrentDb
For Each tb In db.TableDefs
' Skip system files.
If (Mid(tb.Name, 1, 4) <> "MSys" And Mid(tb.Name, 1, 4) <> "~TMP") Then
Debug.Print tb.Name
Debug.Print tb.Connect
'If (Mid(tb.Connect, 1, 5) = "ODBC;") Then
If (tb.Name = "P60DZ30") Then
tb.RefreshLink
Debug.Print "Refreshing fields data"
tb.Fields.Refresh
End If
'End If
Debug.Print "=== === ==="
End If
db.TableDefs.Refresh
Next
Set db = Nothing
RefreshLinkedTables = True
Exit Function
End Function
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40236972",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: android searchview setOnActionExpandListener on Honeycomb 3.2 I'm developing an app for Android 3.2 and greater with android-support-v4. I need to implement OnActionExpandListener for "intercept" when SearchView in the actionbar is expanded and when is collapsed. My code for Android 4.0 and higher it's ok, but for 3.2 no.
menu.xml
<item android:id="@+id/menu_search"
android:title="@string/menu_search"
android:icon="@android:drawable/ic_menu_search"
android:showAsAction="collapseActionView|always"
android:actionViewClass="android.widget.SearchView" />
MyActivity.java
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.reader, menu);
final MenuItem searchMI = menu.findItem(R.id.menu_search);
if(searchView == null) {
//searchView = (SearchView) searchMI.getActionView();
searchView = (SearchView) MenuItemCompat.getActionView(searchMI);
searchView.setOnQueryTextListener(this);
searchView.setOnSuggestionListener(this);
searchView.setOnCloseListener(new OnCloseListener() {
@Override
public boolean onClose() {
//some code
return false;
}
});
}
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion <= android.os.Build.VERSION_CODES.HONEYCOMB_MR2) {
MenuItemCompat.setShowAsAction(searchMI, MenuItemCompat.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW | MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
MenuItemCompat.setOnActionExpandListener(searchMI, new OnActionExpandListener() {
/* (non-Javadoc)
* @see android.support.v4.view.MenuItemCompat.OnActionExpandListener#onMenuItemActionExpand(android.view.MenuItem)
*/
@Override
public boolean onMenuItemActionExpand(MenuItem item) {
Toast.makeText(getApplicationContext(), "onMenuItemActionExpand", Toast.LENGTH_SHORT).show();
return true;
}
/* (non-Javadoc)
* @see android.support.v4.view.MenuItemCompat.OnActionExpandListener#onMenuItemActionCollapse(android.view.MenuItem)
*/
@Override
public boolean onMenuItemActionCollapse(MenuItem item) {
Toast.makeText(getApplicationContext(), "onMenuItemActionExpand", Toast.LENGTH_SHORT).show();
return true;
}
});
} else {
searchMI.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
@Override
public boolean onMenuItemActionExpand(MenuItem item) {
Toast.makeText(getApplicationContext(), "MenuItem#onMenuItemActionExpand", Toast.LENGTH_SHORT).show();
return true;
}
@Override
public boolean onMenuItemActionCollapse(MenuItem item) {
Toast.makeText(getApplicationContext(), "MenuItem#onMenuItemActionExpand", Toast.LENGTH_SHORT).show();
return true;
}
});
}
}
Why, for Honeycomb, methods of listener is not invoked?
Thank you so much.
A: I found that MenuItemCompat.setOnActionExpandListener(...) is not working if you don't pass:
searchItem
.setShowAsAction(MenuItemCompat.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW
| MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
But this is changing the SearchView and is replacing the DrawerToggle with back arrow.
I wanted to keep the original views and still track the Expanded/Collapsed state and use supported Search View.
Solution:
When android.support.v7.widget.SearchView is changing the view state the LinearLayout view's, with id android.support.v7.appcompat.R.id.search_edit_frame, visibility value is being changed from View.VISIBLE to View.GONE and opposite. So I add ViewTreeObserver to track the visibility change of the search edit frame.
menu_search.xml:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto" >
<item
android:id="@+id/action_search"
android:icon="@android:drawable/ic_menu_search"
android:title="@string/search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="always"/>
</menu>
In the activity:
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuItem;
..........
private View mSearchEditFrame;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_search, menu);
MenuItem searchItem = (MenuItem) menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat
.getActionView(searchItem);
searchView.setSubmitButtonEnabled(false);
mSearchEditFrame = searchView
.findViewById(android.support.v7.appcompat.R.id.search_edit_frame);
ViewTreeObserver vto = mSearchEditFrame.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
int oldVisibility = -1;
@Override
public void onGlobalLayout() {
int currentVisibility = mSearchEditFrame.getVisibility();
if (currentVisibility != oldVisibility) {
if (currentVisibility == View.VISIBLE) {
Log.v(TAG, "EXPANDED");
} else {
Log.v(TAG, "COLLAPSED");
}
oldVisibility = currentVisibility;
}
}
});
return super.onCreateOptionsMenu(menu);
}
Thanks!
A: You probably missed the fact (like I did) that `MenuItemCompat.OnActionExpandListener' interface has a static implementation, and is not an instance method.
So, if you have a class that implements MenuItemCompat.OnActionExpandListener then in that class you need to install it as the listener like this:
MenuItem menuItem = menu.findItem(R.id.search);
if (menuItem != null) {
MenuItemCompat.setOnActionExpandListener(menuItem,this);
MenuItemCompat.setActionView(menuItem, mSearchView);
}
The same paradigm applies to setActionView ... rather than invoke menuItem.setActionView(this), you pass the menuItem as the first argument to the static version MenuItemCompat.setActionView and follow with the other argument(s).
A: For MenuItemCompat.setOnActionExpandListener to work you should add "collapseActionView" added in the menu item -
for example -
<item android:id="@+id/action_search"
android:icon="@drawable/ic_action_search"
android:title="@string/action_search"
app:showAsAction="ifRoom|collapseActionView"
app:actionViewClass="android.support.v7.widget.SearchView" />
And in the onCreateOptionsMenu you can use it this way -
MenuItemCompat.setOnActionExpandListener(menu_search,
new OnActionExpandListener()
{
@Override
public boolean onMenuItemActionCollapse(MenuItem item)
{
// Do something when collapsed
return true; // Return true to collapse action view
}
@Override
public boolean onMenuItemActionExpand(MenuItem item)
{
// Do something when expanded
return true; // Return true to expand action view
}
});
A: Your Listener should be MenuItemCompat.OnActionExpandListener() .
MenuItemCompat.setOnActionExpandListener(searchItem,
new MenuItemCompat.OnActionExpandListener() {
}
A: thanks for your help,
your solution is work for me. and i'd like to vote you up, but i just realized i have only 1 reputation,(;′⌒`)
actually, my solution is similar to your, there is just one different in the menu xml file like this:
<item
android:id="@+id/apps_menu_search"
android:icon="@drawable/ic_action_search"
android:title="@string/apps_menu_search"
android:visible="true"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="ifRoom|collapseActionView" />
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19918500",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: Plot a vertical line using matplotlib I would like to draw a vertical line with Matpotlib and I'm using axvline, but it doesn't work.
import sys
import matplotlib
matplotlib.use('Qt4Agg')
from ui_courbe import *
from PyQt4 import QtGui
from matplotlib import pyplot as plt
class Window(QtGui.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
self.setupUi(self)
self.boutonDessiner.clicked.connect(self.generatePlot)
def generatePlot(self):
# generate the plot
ax = self.graphicsView.canvas.fig.add_subplot(111)
ax.plot([1,3,5,7],[2,5,1,-2])
plt.axvline(x=4)
self.graphicsView.canvas.draw()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
win = Window()
win.show()
sys.exit(app.exec_())
I can see my plot, but no vertical line. Why?
A: Your example is not self contained, but I think you need to replace:
plt.axvline(x=4)
with:
ax.axvline(x=4)
You are adding the line to an axis that you are not displaying. Using plt. is the pyplot interface which you probably want to avoid for a GUI. So all your plotting has to go on an axis like ax.
A: matplotlib.pyplot.vlines
*
*The difference is that you can pass multiple locations for x as a list, while matplotlib.pyplot.axvline only permits one location.
*
*Single location: x=37
*Multiple locations: x=[37, 38, 39]
*If you're plotting a figure with something like fig, ax = plt.subplots(), then replace plt.vlines or plt.axvline with ax.vlines or ax.axvline, respectively.
import numpy as np
import matplotlib.pyplot as plt
xs = np.linspace(1, 21, 200)
plt.vlines(x=[37, 38, 39], ymin=0, ymax=len(xs), colors='purple', ls='--', lw=2, label='vline_multiple')
plt.vlines(x=40, ymin=0, ymax=len(xs), colors='green', ls=':', lw=2, label='vline_single')
plt.axvline(x=36, color='b', label='avline')
plt.legend()
plt.show()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29096948",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: how to use yii2-bootstrap4 extension with bootstrap 3 in the same app I have tried to install yii2-bootstrap4
but I got this composer error
Your requirements could not be resolved to an installable set of packages.
Problem 1
- Installation request for yiisoft/yii2-bootstrap4 ^1.0@dev -> satisfiable by yiisoft/yii2-bootstrap4[1.0.x-dev].
- Conclusion: don't install bower-asset/bootstrap v3.3.7
- yiisoft/yii2-bootstrap4 1.0.x-dev requires bower-asset/bootstrap ~4.0.0 -> satisfiable by bower-asset/bootstrap[v4.0.0, v4.0.0-beta.3, v4.0.0-beta1, v4.0.0-alpha.6, v4.0.0-alpha.5, v4.0.0-alpha.4, v4.0.0-alpha.3, v4.0.0-alpha.2, v4.0.0-alpha1].
- Can only install one of: bower-asset/bootstrap[v3.3.7, v4.0.0].
- Can only install one of: bower-asset/bootstrap[v3.3.7, v4.0.0-beta.3].
- Can only install one of: bower-asset/bootstrap[v3.3.7, v4.0.0-beta1].
- Can only install one of: bower-asset/bootstrap[v3.3.7, v4.0.0-alpha.6].
- Can only install one of: bower-asset/bootstrap[v3.3.7, v4.0.0-alpha.5].
- Can only install one of: bower-asset/bootstrap[v3.3.7, v4.0.0-alpha.4].
- Can only install one of: bower-asset/bootstrap[v3.3.7, v4.0.0-alpha.3].
- Can only install one of: bower-asset/bootstrap[v3.3.7, v4.0.0-alpha.2].
- Can only install one of: bower-asset/bootstrap[v3.3.7, v4.0.0-alpha1].
- Installation request for bower-asset/bootstrap (locked at v3.3.7) -> satisfiable by bower-asset/bootstrap[v3.3.7].
Installation failed, reverting ./composer.json to its original content
I want to be able to use bootstrap3 and 4 in the same app, I also tried what is described in this issue "prefer-stable": true, and did not work also.
so what exactly should I do, how to use both bootstrap:~3.0 and bootstrap:~4.0 with official yii2-bootstrap packages
A: You can try to override some requirements in this way:
"minimum-stability": "dev",
"prefer-stable": true,
"require": {
"php": ">=5.4.0",
"yiisoft/yii2": "~2.0.14",
"yiisoft/yii2-bootstrap": "~2.0.8",
"yiisoft/yii2-bootstrap4": "1.0.x-dev",
"bower-asset/bootstrap": "3.3.7 as 4.1.3",
"npm-asset/bootstrap": "~4.1.3"
},
This will install bootstrap 3.3.7 from bower and bootstrap 4.1.3 from npm. You need to update path for bootstrap4 assets bundles:
'components' => [
'assetManager' => [
'bundles' => [
'yii\bootstrap4\BootstrapAsset' => [
'sourcePath' => '@npm/bootstrap/dist'
],
'yii\bootstrap4\BootstrapPluginAsset' => [
'sourcePath' => '@npm/bootstrap/dist'
]
]
]
]
Note that yii2-bootstrap4 is not ready to use and does not even have a alpha/beta release, so expect many other problems.
A: A lot of solution on how to use Bootstrap 4 in Yii2. Even the Yii2 team created an extension for that. But since, I don't like too much configuration. This is what I did. In AppAsset.php, remove the yii\bootstrap\BootstrapAsset with custom your own. I'll recommend, you stick with the original filename and classname.
// AppAsset.php
public $depends = [
'yii\web\YiiAsset',
//'yii\bootstrap\BootstrapAsset', // Remove this
'app\assets\BootstrapAsset', // Add this
];
Then, I created a BootstrapAsset.php file in assets folder. Copy the code from yii\bootstrap\BootstrapAsset. Then changed some part of the code. No NPM, No Bower.
namespace app\assets;
use yii\web\AssetBundle;
class BootstrapAsset extends AssetBundle
{
public $basePath = '@webroot';
public $baseUrl = '@web';
public $css = [
'vendor/bootstrap/css/bootstrap.min.css'
];
public $js = [
'vendor/bootstrap/js/bootstrap.min.js',
'vendor/popper.js/umd/popper.min.js'
];
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50028312",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Azure Traffic Manager Load Balance Options I tried to dig on MSDN but could not get concrete statement for which is the best load balancing method.
could someone please share some light on which of the below are best option for given scenario:
*
*Performance
*Failover
*Round Robin.
Scenario:
x Web Roleshosted on Large VM on single data center.
Requirement:
must be 100% up 24x7.
Thank you.
A: First: Do you really want to offer a 100% uptime SLA for your customers, when Azure itself doesn't offer 100% in its SLA's?
That said: Traffic Manager only load-balances your compute, not your storage. So if you're trying to increase uptime by having a set of backup compute nodes running in another data center, you need to think about data access speed and cost:
*
*With round robin, you'll now have distributed traffic across multiple data centers, guaranteed, and constantly. And if your data is in a single data center (which is a good idea to have data in a single System of Record, unless you have replication logic all taken care of), some of your users are going to see increased latency as the nodes separated from your data are going to be requesting data across many miles (potentially between continents). Plus, data egress has a $$$ cost to it.
*With performance, your users are directed toward the data center which offers them the lowest latency. Again, this now means traffic across multiple data centers, with the same issues as round robin.
*With failover, you now have all traffic going to one data center, with another designated as your failover data center (so it's for High Availability). In the event you have an outage in the primary data center, you'd now have a failover data center to rely on. This may help justify the added latency and cost, as you'd only experience this latency+cost when your primary app location becomes unavailable for some reason.
So: If you're going for the high availability route, to help approach the 100% availability mark, I'm guessing you'd be best off with the failover model.
A: Traffic manager comes into picture only when your application is deployed across multiple cloud services within same data center or in different data centers. If your application is hosted in a single cloud service (with multiple instances of course) , then the instances are load balanced using Round Robin pattern. This is the default load balancing pattern and comes to you without any extra charge.
You can read more about traffic manager here: https://azure.microsoft.com/en-us/documentation/articles/traffic-manager-overview/
A: As per my guess there can not be comparison which is best load balancing method of Azure Traffic manager. All of them have unique advantages and vary depending on the requirement of application. Most common scenario is to use performance load balancing option with azure traffic manager. But as Gaurav said, you will have to have your cloud service application hosted on more than one cloud services. If you wish to implement performance load balancing then here is the link to get you started - http://sanganakauthority.blogspot.com/2014/06/performance-load-balancing-using-azure.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17312183",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to draw a vertical line at specified x value on QHorizontalBarSeries/QChart? I've followed this example to create a horizontal bar chart. I'd like to draw a static vertical line at a specific value along the x-axis. I've tried adding a QLineSeries to the QChart, but nothing is showing up. I'm doing this in Python, but C++ works, too.
A: A possible solution is to override the drawForeground() method to paint the vertical line, to calculate the positions you must use the mapToPosition() method:
import sys
from PyQt5.QtCore import Qt, QPointF
from PyQt5.QtGui import QColor, QPainter, QPen
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtChart import (
QBarCategoryAxis,
QBarSet,
QChart,
QHorizontalBarSeries,
QChartView,
QValueAxis,
)
class ChartView(QChartView):
_x = None
@property
def x(self):
return self._x
@x.setter
def x(self, x):
self._x = x
self.update()
def drawForeground(self, painter, rect):
if self.x is None:
return
painter.save()
pen = QPen(QColor("indigo"))
pen.setWidth(3)
painter.setPen(pen)
p = self.chart().mapToPosition(QPointF(self.x, 0))
r = self.chart().plotArea()
p1 = QPointF(p.x(), r.top())
p2 = QPointF(p.x(), r.bottom())
painter.drawLine(p1, p2)
painter.restore()
def main():
app = QApplication(sys.argv)
set0 = QBarSet("Jane")
set1 = QBarSet("John")
set2 = QBarSet("Axel")
set3 = QBarSet("Mary")
set4 = QBarSet("Samantha")
set0 << 1 << 2 << 3 << 4 << 5 << 6
set1 << 5 << 0 << 0 << 4 << 0 << 7
set2 << 3 << 5 << 8 << 13 << 8 << 5
set3 << 5 << 6 << 7 << 3 << 4 << 5
set4 << 9 << 7 << 5 << 3 << 1 << 2
series = QHorizontalBarSeries()
series.append(set0)
series.append(set1)
series.append(set2)
series.append(set3)
series.append(set4)
chart = QChart()
chart.addSeries(series)
chart.setTitle("Simple horizontal barchart example")
chart.setAnimationOptions(QChart.SeriesAnimations)
categories = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
axisY = QBarCategoryAxis()
axisY.append(categories)
chart.addAxis(axisY, Qt.AlignLeft)
series.attachAxis(axisY)
axisX = QValueAxis()
chart.addAxis(axisX, Qt.AlignBottom)
series.attachAxis(axisX)
axisX.applyNiceNumbers()
chart.legend().setVisible(True)
chart.legend().setAlignment(Qt.AlignBottom)
chartView = ChartView(chart)
chartView.setRenderHint(QPainter.Antialiasing)
chartView.x = 11.5
window = QMainWindow()
window.setCentralWidget(chartView)
window.resize(420, 300)
window.show()
app.exec()
if __name__ == "__main__":
main()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67591067",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to pass cv::mat objects from a python module to a c++ function and give back returned object which is type cv::mat? I try to start a project with Django which a part of that is about showing some images.
As probably you know, c++ is so faster than python. so I wrote a c++ function which receives two Mat type input and do some pre processing on them and finally return a cv::mat variable as it's output.
I want to call this function inside my python module and send from my python code, two images as input argument and show the result of c++ function in my django project.
I tried to call my c++ function with ctypes.CDLL, ctypes work with simple functions but for this c++ code gives a memory error.
this is my c++ function:
extern "C" Mat watermark2(Mat source_img, Mat logo)
{
// Simple watermark
double alpha = 0.5;
int width = logo.size().width;
int height = logo.size().height;
int x_pos = rand() % (source_img.size().width - width);
int y_pos = rand() % (source_img.size().height - height);
cv::Rect pos = cv::Rect(x_pos, y_pos, width, height);
addWeighted(source_img(pos), alpha, logo, 1 - alpha, 0.0, source_img(pos));
return source_img;
}
as you see, this is a simple function and don't use a lot of memory. I test it for some very small pictures and I saw the same error.
I search a lot in net and found some instructions about Wrapping C/C++ for Python. but I don't sure that it can help me.
because I'm new in Django, can anybody help me how to negotiate from my python code which I have two images with my c++ function to some manipulate on images and save the returned output in my Django?
A: Maybe consider using the Boost-Python library for interfacing between Python and C++.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57889151",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: java.lang.SecurityException: Requires VIBRATE permission on Jelly Bean 4.2 Since yesterday I have an issue on Android 4.2 when I receive push notifications it requires the permission even if i don't set it to vibrate
Notification notification = new Notification(icon, notificationItem.message, when);
notification.setLatestEventInfo(context, "App", notificationItem.message,
PendingIntent.getActivity(context, 0, intent, 0));
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.defaults |= Notification.DEFAULT_SOUND;
NotificationManager nm =
(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(notificationItem.notificationID, notification);
the exception is raised by nm.notify
I have this issue in two different apps and i never modify the code
A: I got the same Exception in Jelly Bean 4.1.2, then following changes I made to resolve this
1.added permission in manifest file.
<uses-permission
android:name="android.permission.VIBRATE"></uses-permission>
2.Notification Composing covered by Try-Catch
try
{
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this)
.setSmallIcon(R.drawable.ic_notif_alert)
.setContentTitle(getResources().getString(R.string.app_name))
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg)
.setStyle(bigTextStyle)
.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);
mBuilder.setAutoCancel(true);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
Log.d(TAG, "---- Notification Composed ----");
}
catch(SecurityException se)
{
se.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
A: Since this bug only occurs on Android 4.2 and 4.3 you might use this as a workaround (i.e. include the maxSdkVersion):
<uses-permission android:name="android.permission.VIBRATE" android:maxSdkVersion="18"/>
Note: the maxSdkVersion attribute was only added in API level 19, which in this case is luckily exactly the minimum we want! In theory we could put any value <= 18 to get the same effect, but that would be nasty.
A: This was a bug in Android 4.2 due to a change in the notification vibration policy; the permission bug was fixed by this change in 4.2.1.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13602190",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "36"
} |
Q: How to select specific div using BeautifulSoup when multiple divs have the same class name no id tag? Please help I don't know how to select specific div using BeautifulSoup when multiple divs have the same class name no id tag.
Web page that I am trying to scrape: https://www.helpmefind.com/rose/l.php?l=2.65689.
I want to select contents of specific divs independently and then pass to a csv file. Got stuck since find_all returns multiple divs and I don't know how to restrict further.
rose_div = rose.find_all("div", class_="hdg")
Returns:
[<div class="hdg">HMF Ratings:</div>, <div class="hdg">Origin:</div>, <div class="hdg">Class:</div>, <div class="hdg">Bloom:</div>, <div class="hdg">Parentage:</div>, <div class="hdg">Notes:</div>, <div class="hdg"> </div>]
I want to select individually below divs:
<div class="hdg">Origin:</div>
<div class="hdg">Class:</div>
<div class="hdg">Bloom:</div>
<div class="hdg">Parentage:</div>
A: You can use CSS selector div.hdg:contains("Origin:") to select <div> with class="hdg" that contains word "Origing:". To get next element with class grp, you can add + .grp.
For example:
import requests
from bs4 import BeautifulSoup
url = 'https://www.helpmefind.com/rose/l.php?l=2.65689'
soup = BeautifulSoup( requests.get(url).content, 'html.parser' )
origin = soup.select_one('div.hdg:contains("Origin:") + .grp').text
class_ = soup.select_one('div.hdg:contains("Class:") + .grp').text
bloom = soup.select_one('div.hdg:contains("Bloom:") + .grp').text
parentage = soup.select_one('div.hdg:contains("Parentage:") + .grp').text
print(origin)
print(class_)
print(bloom)
print(parentage)
Prints:
Bred by Arai (Japan, before 2009).
Floribunda.
Light pink and white, yellow stamens. Single (4-8 petals), cluster-flowered bloom form. Blooms in flushes throughout the season.
If you know the parentage of this rose, or other details, please contact us.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62740766",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I create a camera including guidelines for the user to snap the picture between? I'm working with OCR using tess-two as my scanner and it works great when taking the photo, and using https://github.com/IsseiAoki/SimpleCropView to crop the image for the right numbers to be read from tess-two.
What I'd like to do is to take the second step of cropping the image out of the process, making it quicker for the user. I'm just confused on how to add my own crop rectangle area to allow the user to take a picture in.
Even something as simple as "[ ]" with the rest of the camera surface view blacked out or dimmed, guiding the user to take the photo of the numbers in between the brackets.
Are there any good tutorials out there involving this? I've searched, but with no success. Or if anyone can point me in the right direction on how to start this that would be a big help! Thanks in advance!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32958676",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: maximum plot points in R? I have come across a number of situations where I want to plot more points than I really ought to be -- the main holdup is that when I share my plots with people or embed them in papers, they occupy too much space. It's very straightforward to randomly sample rows in a dataframe.
if I want a truly random sample for a point plot, it's easy to say:
ggplot(x,y,data=myDf[sample(1:nrow(myDf),1000),])
However, I was wondering if there were more effective (ideally canned) ways to specify the number of plot points such that your actual data is accurately reflected in the plot. So here is an example.
Suppose I am plotting something like the CCDF of a heavy tailed distribution, e.g.
ccdf <- function(myList,density=FALSE)
{
# generates the CCDF of a list or vector
freqs = table(myList)
X = rev(as.numeric(names(freqs)))
Y =cumsum(rev(as.list(freqs)));
data.frame(x=X,count=Y)
}
qplot(x,count,data=ccdf(rlnorm(10000,3,2.4)),log='xy')
This will produce a plot where the x & y axis become increasingly dense. Here it would be ideal to have fewer samples plotted for large x or y values.
Does anybody have any tips or suggestions for dealing with similar issues?
Thanks,
-e
A: I tend to use png files rather than vector based graphics such as pdf or eps for this situation. The files are much smaller, although you lose resolution.
If it's a more conventional scatterplot, then using semi-transparent colours also helps, as well as solving the over-plotting problem. For example,
x <- rnorm(10000); y <- rnorm(10000)
qplot(x, y, colour=I(alpha("blue",1/25)))
A: Beyond Rob's suggestions, one plot function I like as it does the 'thinning' for you is hexbin; an example is at the R Graph Gallery.
A: Here is one possible solution for downsampling plot with respect to the x-axis, if it is log transformed. It log transforms the x-axis, rounds that quantity, and picks the median x value in that bin:
downsampled_qplot <- function(x,y,data,rounding=0, ...) {
# assumes we are doing log=xy or log=x
group = factor(round(log(data$x),rounding))
d <- do.call(rbind, by(data, group,
function(X) X[order(X$x)[floor(length(X)/2)],]))
qplot(x,count,data=d, ...)
}
Using the definition of ccdf() from above, we can then compare the original plot of the CCDF of the distribution with the downsampled version:
myccdf=ccdf(rlnorm(10000,3,2.4))
qplot(x,count,data=myccdf,log='xy',main='original')
downsampled_qplot(x,count,data=myccdf,log='xy',rounding=1,main='rounding = 1')
downsampled_qplot(x,count,data=myccdf,log='xy',rounding=0,main='rounding = 0')
In PDF format, the original plot takes up 640K, and the downsampled versions occupy 20K and 8K, respectively.
A: I'd either make image files (png or jpeg devices) as Rob already mentioned, or I'd make a 2D histogram. An alternative to the 2D histogram is a smoothed scatterplot, it makes a similar graphic but has a more smooth cutoff from dense to sparse regions of space.
If you've never seen addictedtor before, it's worth a look. It has some very nice graphics generated in R with images and sample code.
Here's the sample code from the addictedtor site:
2-d histogram:
require(gplots)
# example data, bivariate normal, no correlation
x <- rnorm(2000, sd=4)
y <- rnorm(2000, sd=1)
# separate scales for each axis, this looks circular
hist2d(x,y, nbins=50, col = c("white",heat.colors(16)))
rug(x,side=1)
rug(y,side=2)
box()
smoothscatter:
library("geneplotter") ## from BioConductor
require("RColorBrewer") ## from CRAN
x1 <- matrix(rnorm(1e4), ncol=2)
x2 <- matrix(rnorm(1e4, mean=3, sd=1.5), ncol=2)
x <- rbind(x1,x2)
layout(matrix(1:4, ncol=2, byrow=TRUE))
op <- par(mar=rep(2,4))
smoothScatter(x, nrpoints=0)
smoothScatter(x)
smoothScatter(x, nrpoints=Inf,
colramp=colorRampPalette(brewer.pal(9,"YlOrRd")),
bandwidth=40)
colors <- densCols(x)
plot(x, col=colors, pch=20)
par(op)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1962954",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Subsets and Splits