source
sequence | text
stringlengths 99
98.5k
|
---|---|
[
"stackoverflow",
"0044319317.txt"
] | Q:
flexbox mobile first menu issue
I have tried to emulate the excellent flexbox tutorials by Wes Bos. I wanted to convert one specific tutorial he has on responsive flexbox menu. But I wanted my menu to be done with mobile first so I did my media queries with min-width.
But I am not able to make it work properly on the default mobile layout. In the menu created by Wes, the li items are stacked upon each other and the social icons at the bottom have flex:1 1 25%. But my social icons are also stacked.
On the other breakpoints my layout follows the one that Wes created.
I have set up a codepen for my code.
.flex-nav ul {
list-style: none;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
}
.flex-nav .social {
flex: 1 1 25%;
}
@media all and (min-width:500px) {
.flex-nav li {
flex: 1 1 50%;
}
.flex-nav ul {
flex-wrap: wrap;
flex-direction: row;
}
.flex-nav ul {
border: 1px solid black;
}
}
@media all and (min-width:800px) {
.flex-nav li {
flex: 3;
}
.flex-nav .social {
flex: 1;
}
}
A:
This is your default code (no media queries applied):
.flex-nav ul {
display: flex;
flex-direction: column;
}
.flex-nav .social {
flex: 1 1 25%;
}
Yes, you've given each social media icon a flex-basis: 25%.
BUT, your container is flex-direction: column.
So the flex rule applied to your social media icons works vertically, not horizontally.
Consider this method instead:
.flex-nav ul {
display: flex;
flex-wrap: wrap;
}
li {
flex: 0 0 100%; /* sized to fit one item per row */
}
.flex-nav .social {
flex: 0 0 25%; /* sized to fit four items per row */
}
revised demo
|
[
"stackoverflow",
"0014666647.txt"
] | Q:
Jquery iterate through the parent table on click of a link within a child td
I have the following table structure
<table calss="ptable">
<tr>
<td><select>...</select></td>
<td><input/></td>
<td>input/></td>
<td><a class="abc"></a></td>
</tr>
<tr>
<td><select>...</select></td>
<td><input/></td>
<td>input/></td>
<td><a class="abc"></a></td>
</tr>
<tr>
<td><select>...</select></td>
<td><input/></td>
<td>input/></td>
<td><a class="abc"></a></td> </tr></table>
now on click of 'a' tag I have to iterate through the whole table and set vales for select and input within each td. I m Using jquery... Please help I m new to jquery....
I found solution for this like .......
var firsta = $(".abc").first().parents(".ptable");
$(firsta).children("tbody").find("tr td").each(function (index) { alert(index); });
Is there a better way to achive this.
A:
Just don"t want to keep it unanswered. as I have one solution I would like to share it...
var firsta = $(".abc").first().parents(".ptable");
$(firsta).children("tbody").find("tr td").each(function (index) { alert(index); });
Thanks everyone for the help...
|
[
"math.stackexchange",
"0002126773.txt"
] | Q:
Geometry Derivative
Show that the normals to the curve $y=4x^2$ from points the same distance on either side of the y-axis intersect on the y-axis.
My attempt, I differentiated so it becomes $8x$, but I don't understand the question. Can anyone explain it to me ? Thanks in advance:
A:
The distance from a point $P=(a,4a^2)$ of the curve to the y-axis is $d=|a|$, so two points of the curve has the same distance to y-axis then they are $(a,4a^2)$ and $(-a,4a^2)$.
The normal has slope $m=-\frac{1}{8x_0}$ and then it has the form
$$y=-\frac{1}{8x_0}x+k$$
If it goes trough $(a,4a^2)$ we get
$$y_1=-\frac{1}{8a}x+\frac{32a^2+1}{8a}$$
If it goes through $(-a,4a^2)$ we get
$$y_2=\frac{1}{8a}x+\frac{32a^2+1}{8a}$$
So the point
$$\left(0,\frac{32a^2+1}{8a}\right)$$
is the intersection
|
[
"stackoverflow",
"0036401368.txt"
] | Q:
import oauth2client ImportError: No module named oauth2client
I am working on a python program for extracting stuff from the cloud. As such I am using
google-api-python-client
I have successfully installed that, however when I run my program I get the error message
ImportError: No module named oauth2client
I have 2 issues with that error. Firstly, I had oauth2client install prior to installing google-api-python-client. Secondly, oauth2client gets install as a requirement for google-api.
My first thoughts were that there was some conflict so I uninstalled both programs and installed google-api-python-client alone. This should resolve any conflicts ? Still no joy. Although as I am uninstalling and installing the program I repeatedly see this warning
Running setup.py (path:C:\Users\078861~1.025\AppData\Local\Temp\pip_build_07886187\oauth2client\setup.py) egg_info for package oauth2client
warning: no previously-included files matching '*' found under directory 'tests'
I feel this is a crucial clue but not sure what it means. I did a quick search and I have a number of tests folders in the site packages related to a number of other libraries , is there any way that they are interfering with the correct implantation of oauth2client ? Any insight would be much appreciated thanks.
A:
SO eventually figured it out , said that I would leave this marker for anyone coming after me. I was running the script from the python34 directory where I had the file stored, however I was using git Bash , and that uses the python that is in the environmental variables, regardless of where it is called from. I had python2.7 in the environmental variables.
|
[
"stackoverflow",
"0043671876.txt"
] | Q:
python urlib AttributeError: 'HTTPResponse' object has no attribute 'readall'
I am following a tutorial on tkinter with some urlib in it and get this error message.
AttributeError: 'HTTPResponse' object has no attribute 'readall'
here is the code:
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
import matplotlib.animation as animation
from matplotlib import style
import urllib
import json
import pandas as pd
import numpy as np
import tkinter as tk
from tkinter import ttk
LARGE_FONT= ("Verdana", 12)
style.use("ggplot")
f = Figure(figsize=(5,3), dpi=100)
a = f.add_subplot(111)
def animate(i):
dataLink = 'https://btc-e.com/api/3/trades/btc_usd?limit=2000'
data = urllib.request.urlopen(dataLink)
data = data.readall().decode("utf-8")
data = json.loads(data)
here is the complete trace back
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Programs\Python\Python35\lib\tkinter\__init__.py", line 1550, in __call__
return self.func(*args)
File "C:\Programs\Python\Python35\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 280, in resize
self.show()
File "C:\Programs\Python\Python35\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 351, in draw
FigureCanvasAgg.draw(self)
File "C:\Programs\Python\Python35\lib\site-packages\matplotlib\backends\backend_agg.py", line 464, in draw
self.figure.draw(self.renderer)
File "C:\Programs\Python\Python35\lib\site-packages\matplotlib\artist.py", line 63, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "C:\Programs\Python\Python35\lib\site-packages\matplotlib\figure.py", line 1150, in draw
self.canvas.draw_event(renderer)
File "C:\Programs\Python\Python35\lib\site-packages\matplotlib\backend_bases.py", line 1815, in draw_event
self.callbacks.process(s, event)
File "C:\Programs\Python\Python35\lib\site-packages\matplotlib\cbook.py", line 549, in process
proxy(*args, **kwargs)
File "C:\Programs\Python\Python35\lib\site-packages\matplotlib\cbook.py", line 416, in __call__
return mtd(*args, **kwargs)
File "C:\Programs\Python\Python35\lib\site-packages\matplotlib\animation.py", line 831, in _start
self._init_draw()
File "C:\Programs\Python\Python35\lib\site-packages\matplotlib\animation.py", line 1490, in _init_draw
self._draw_frame(next(self.new_frame_seq()))
File "C:\Programs\Python\Python35\lib\site-packages\matplotlib\animation.py", line 1512, in _draw_frame
self._drawn_artists = self._func(framedata, *self._args)
File "C:\Programs\Python\Python35\tkinter\TutorialTwo.py", line 28, in animate
data = data.readall().decode("utf-8")
AttributeError: 'HTTPResponse' object has no attribute 'readall'
A:
HttpResponse has no attribute readall.
>>> dir(data)
['__abstractmethods__', '__class__', '__del__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__',
'__exit__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__',
'__iter__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__next__', '__reduce__', '__reduce_ex__',
'__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_abc_cache', '_abc_negative_cache',
'_abc_negative_cache_version', '_abc_registry', '_checkClosed', '_checkReadable', '_checkSeekable', '_checkWritable',
'_check_close', '_close_conn', '_get_chunk_left', '_method', '_peek_chunked', '_read1_chunked',
'_read_and_discard_trailer', '_read_next_chunk_size', '_read_status', '_readall_chunked', '_readinto_chunked',
'_safe_read', '_safe_readinto', 'begin', 'chunk_left', 'chunked', 'close', 'closed', 'code', 'debuglevel', 'detach',
'fileno', 'flush', 'fp', 'getcode', 'getheader', 'getheaders', 'geturl', 'headers', 'info', 'isatty', 'isclosed',
'length', 'msg', 'peek', 'read', 'read1', 'readable', 'readinto', 'readinto1', 'readline', 'readlines', 'reason',
'seek', 'seekable', 'status', 'tell', 'truncate', 'url', 'version', 'will_close', 'writable', 'write', 'writelines']
>>> type(data)
< class 'http.client.HTTPResponse'>
try use read or readline
data = data.readline().decode("utf-8")
|
[
"stackoverflow",
"0008034870.txt"
] | Q:
Using UITableView in UIView with existing TableViewController
I have several UITableViewControllers. I want to use one of those controllers as delegate and data source for a UITableView in some other view. I have an IBOutlet in the view controller containing the table view, and it is connected to the table view in IB.
How do I connect the table view to the delegate and datasource (which is a table view controller I already have to display the same content)? I have tried draging a NSObject in the black bar below my view controller and setting the class to MyTableViewController, connecting the delegate and datasource to this, but it wil crash when the view loads, without a descriptive error.
Will the viewDidAppear: on the delegate fire (this is where I fetch the content for the table view)?
I would really have liked to post a screenshot, but I am too new.
A:
How do i connect the TableView to the Delegate and Datasource (Which
is a TableViewController I already have to display the same content) ?
self.myTableView.dataSource=myTableViewController.table.dataSource;
self.myTableView.delegate=myTableViewController.table.delegate;
Can this help?
Edit1: Even if this helps and you find a solution, I am tempted to say you have an architecture problem.
|
[
"stackoverflow",
"0056372469.txt"
] | Q:
No way to make Work persistent across reboots?
So I know WorkManager utilizes JobScheduler on supported APIs but there doesnt seem to be any way to make WorkManager work persistent across reboots? Is the only option to request the BOOT_COMPLETED permission and reschedule jobs?
A:
To answer your question: You don't need to do anything if the device is rebooted. WorkManager keeps scheduling your Work without any additional requirement from your side.
WorkManager persists Work requests in its internal Room database. This allows it to guarantee Work execution across device restart.
The documentation covers this as this blog "Introducing WorkManager" that the team wrote last year.
|
[
"math.stackexchange",
"0001713152.txt"
] | Q:
If $R$ is an integral domain, show that there is no subfield $k$ of Frac($R$) containing $R$.
If $R$ is an integral domain, show that there is no subfield $k$ of Frac($R$) containing $R$.
I think the way to prove this is by contradiction. So, let $R$ be an integral domain, and let $k$ be a subfield of Frac($R$) such that $R$$\subseteq \!\,$$k$.
I think we need to assume that two elements are in $k$ and then show that at least one of these elements is not in $R$. So, to show that two elements are not in $R$, we need the product of these two elements to equal zero.
Let $h$,$j$ $\in \!\ k$. I am honestly not sure what to do from here.
A:
Just use the fact that $\operatorname{Frac}(R)$ has all field operations applicable to elements of $R$ and that $k$ is closed under the field operations. Since $a,b\in R$ with $b\ne 0$ implies $a+b, ab, a/b\in k$, this is exactly the elements of $\operatorname{Frac}(R)$, so $\operatorname{Frac}(R)\subseteq k$.
|
[
"stackoverflow",
"0021652766.txt"
] | Q:
Filter in SPARQL query
I have the following SPARQL query:
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX type: <http://dbpedia.org/class/yago/>
PREFIX prop: <http://dbpedia.org/property/>
SELECT *
WHERE {
?person a foaf:Person;
foaf:name ?name;
prop:deathCause ?death_cause.
FILTER (langMatches(lang(?name), "EN")) .
}
LIMIT 50
If you run this here: http://dbpedia.org/snorql/
You will see that you get a lot of results. Now I would like to filter out one death cause, let's say 'Traffic collision'. So this should be simply by adding a filter:
FILTER (?death_cause = "Traffic collision").
So the query should then be:
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX type: <http://dbpedia.org/class/yago/>
PREFIX prop: <http://dbpedia.org/property/>
SELECT *
WHERE {
?person a foaf:Person;
foaf:name ?name;
prop:deathCause ?death_cause.
FILTER (?death_cause = "Traffic collision").
FILTER (langMatches(lang(?name), "EN")) .
}
LIMIT 50
However this returns nothing. Anyone that knows what is wrong with the query? Thanks.
A:
You will see that you get a lot of results. Now I would like to filter
out one death cause, let's say 'Traffic collision'. So this should be
simply by adding a filter:
FILTER (?death_cause = "Traffic collision" ).
Filters define what things you keep, not what things you remove, so if you wanted to filter out traffic collisions, you'd actually want:
FILTER ( ?death_cause != "Traffic collision" )
If you try that, though, you'll still see traffic collisions in your results, because there's a difference between "Traffic collision" and "Traffic collision"@en. The former (which is what your code would be removing) is a plain literal (i.e., without a datatype or a language tag). The latter is a literal with the language tag "en". These are not the same, so filtering out one doesn't filter out the other, and keeping one won't keep the other. To remove the "Traffic collision"@en, you can filter it out with:
FILTER ( ?death_cause != "Traffic collision"@en )
Alternatively, you can use the str function to get the lexical part of a literal, so you could filter out "Traffic collision" regardless of the language tag (or datatype, if it appeared as a typed literal):
FILTER ( str(?death_cause) != "Traffic collision" )
Thus:
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX type: <http://dbpedia.org/class/yago/>
PREFIX prop: <http://dbpedia.org/property/>
SELECT *
WHERE {
?person a foaf:Person;
foaf:name ?name;
prop:deathCause ?death_cause.
FILTER (langMatches(lang(?name), "EN")) .
FILTER ( ?death_cause != "Traffic collision"@en )
}
LIMIT 50
SPARQL results
|
[
"math.stackexchange",
"0000237646.txt"
] | Q:
Proving $\cos (z)$ is real for real values of $z$
Given the definition of cos function through the exponential function, how can we prove rigorously that for real values of $z$ $$\cos(z)=\operatorname{Re}(\exp(iz))$$?
A:
Notice that $\overline{e^z} =e^{\overline{z}}$. Hence for $z\in \mathbb{R}$, $$\text{cos}(z) = \frac{e^{iz}+e^{-iz}}{2} = \frac{e^{iz}+e^{\overline{iz}}}{2} = \frac{e^{iz}+\overline{e^{iz}}}{2} = \text{Re}(e^{iz})$$
|
[
"stackoverflow",
"0010864515.txt"
] | Q:
I need sample code of using
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class/Reference/Reference.html#//apple_ref/occ/instm/NSNotificationCenter/postNotificationName:object:userInfo:
postNotificationName:object:userInfo:
Basically how does the observer get that userInfo?
Is there a short sample code somewhere to show the whole thing?
A:
#import <Foundation/Foundation.h>
#define kSomeKey @"key"
#define kNotificationName @"MyMadeUpNameNotification"
@interface Test : NSObject
@end
@implementation Test
-(void) handleNotification:(NSNotification*)notification {
NSString *object = [notification.userInfo objectForKey:kSomeKey];
NSLog(@"%@",object);
}
-(void) run {
[[NSNotificationCenter defaultCenter] addObserver: self
selector: @selector(handleNotification:)
name: kNotificationName
object: nil];
NSString *anyObject = @"hello";
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:anyObject forKey:kSomeKey];
NSNotification *notification = [NSNotification notificationWithName:kNotificationName object:nil userInfo:userInfo];
[[NSNotificationCenter defaultCenter] postNotification:notification];
}
@end
int main(int argc, char *argv[]) {
@autoreleasepool {
[[Test new] run];
}
}
|
[
"stackoverflow",
"0023117393.txt"
] | Q:
CSS: Text over image with reduced opacity should not have reduced opacity
I have an image which has reduced opacity and some text, which is in a separate div, which is lying over the image (negative margin-top). While the image should be transparent, the text should not. I now found out that, depending on the value of the opacity the text is shown in black or also transparent.
When the image has
opacity: 1
the text ist black, when the value lower - the text has an reduced opacity as well.
My markup looks like this:
<li>
<img src="image.jpg">
<div class="text">Description</div>
</li>
.text{ margin-top: -3em; }
img{ opacity: 0.5; }
http://jsfiddle.net/BFhau/1/
How can I display the text always in black?
A:
Add
position: relative;
to place text at the top.
Demo
The problem was setting opacity different than 1 creates an stacking context.
Then, according to the order defined in the spec, images overlap texts, because:
(4) .text are in-flow, non-positioned, block-level elements
(6) Images are inline elements that generate a stacking context
Since 4 < 6, images overlap text.
To avoid that, you can make .text positioned elements adding position: relative. Now they will fall into this category:
(8) Positioned descendants with 'z-index: auto' or 'z-index: 0'
Now, since 6 < 8, texts overlap images.
Alternatively, you could also add a positive z-index (e.g. z-index:1) in order to make .text fall into the next category:
(9) Stacking contexts formed by positioned descendants with z-indices greater than or equal to 1
You can read more about stacking contexts and z-axis positioning in What No One Told You About Z-Index, a great article much more appealing than the raw spec.
|
[
"stackoverflow",
"0051102013.txt"
] | Q:
array values in for loop stops page from loading and creates an unlimited loop php
I've got a page where I run a while loop from a database. I ended up needing some of the information before I displayed the page, so I ended up having to set up an array to store the while loop information. Once the while loop completes, then the page loads.
$first = $data[$key]['order'][$data_order_id]['lowest_staff_markup'];
$second = $data[$key]['order'][$data_order_id]['lowest_markup'];
If I use echo $first .' ... '. $second; it returns 12 ... 30
the values are being set correctly. The array works
Now I need to set up a for loop to loop between the numbers. If I manually put in 12 and 30 it works great. But the moment I try to place $first and $second in, the entire for loop freezes the page and creates an unlimited loop of 12
echo '<select name="markup['. $cart_result['product_table'] .':'. $cart_result['product_id'] .']" />'; // fix this
for ($mu = $first;
$mu <= $second;
$mu++) {
echo '<option value="'. $data[$key]['order'][$data_order_id]['markup_key'] .'">'. $mu .' %</option>';
}
echo '</select>';
Any idea why this is happening? I've been staring at this code for entirely too long trying to understand it. I've tried everything I can think of even though I'm sure the answer is obvious.
Like I said, the for loop works perfectly if I place the numbers in manually so I know the code itself works.
Sorry if there is any typos. I took unneeded portions fo the code out like "selected = selected" conditions, etc. I only placed the amount of code needed for the problem.
A:
After debugging in the comments with OP using
var_dump($first);
var_dump($second);
Appeared that $first contains a space:
string(3) "12 "
string(2) "30"
Solution:
Casting the strings to integers solve this issue:
for ($mu = (int)$first; $mu <= (int)$second; $mu++) {
// code here ...
}
|
[
"stackoverflow",
"0031301452.txt"
] | Q:
Undefined object inside object when accessing with Object function
I am trying to change the value of "selectedArea" to the values I get from the mouse. Whenever I try to do so I get "Uncaught TypeError: Cannot read property 'start' of undefined". (mouseDown())
Probably an easy solution, just that I can not see it(quite new to javascript).
var areaSelection = {
mouseisDown: false,
selectedArea: {
start: { x: 0, y: 0 },
end: { x: 0, y: 0 }
},
initialize: function () {
canvasSource.addEventListener("mousedown", this.mouseDown);
canvasSource.addEventListener("mousemove", this.mouseMove);
canvasSource.addEventListener("mouseup", this.mouseUp);
},
mouseDown: function (event) {
if (!this.mouseisDown) {
this.selectedArea.start.x = event.clientX;
this.selectedArea.start.y = event.clientY;
}
},
mouseMove: function (event) {
if (this.mouseisDown) {
var x = this.selectedArea.start.x;
var y = this.selectedArea.start.y;
var width = event.clientX - x;
var height = event.clientY - y;
drawOverlay(x, y, width, height);
}
},
mouseUp: function (event) {
if (this.mouseisDown) {
this.selectedArea.end.x = event.clientX;
this.selectedArea.end.y = event.clientY;
}
}
};
A:
You are missing the correct context in which the function is called:
canvasSource.addEventListener("mousedown", this.mouseDown.bind(this));
If you don't bind the context then the this inside the listener refers to the clicked element, which is the canvas.
|
[
"stackoverflow",
"0021817774.txt"
] | Q:
How to do patternmatching against HashDict in elixir?
How can I do pattern matching against HashDict in Elixir? I can not find any decent information anywhere.
So example I have is and it is bound to variable a:
#HashDict<[{"a", 1}, {"b", 2}]>
And lets say I want to get 2
I tried something like this to test a concept, but no luck:
[{"a",1}, {"b",val} = a
But I get: (MatchError) no match of right hand side value
Can someone help me with this?
A:
You can't pattern match on a HashDict. In general, when you see something printed as #HashDict<...> it is exactly because its internal representation is "private". Maps are coming on Elixir 0.13 and they will support pattern matching (and other goodies).
|
[
"stackoverflow",
"0019804928.txt"
] | Q:
Scala : Writing String Iterator to file in Efficient way
I have thousands of files (50K) and each file has around 10K lines.I read the file do some processing and write the lines back to an output file. While my reading and processing is way faster, the final step to convert the String Iterator back to a single String and write it to a file take a long time(almost a second.I wouldn't do the math for doing this for the whole population of files which is around 50K). I see this to be the bottleneck in the of improving my parsing time.
This is my code.
var processedLines = linesFromGzip(new File(fileName)).map(line => MyFunction(line))
var outFile = Resource.fromFile(outFileName)
outFile.write(processedLines.mkString("\n")) // severe overhead caused by this line-> processedLines.mkString("\n")
( I read on few other forums/blogs that mkString is much better than other approaches. (eg.)
Is there a better alternative to mkString("\n") ? Is there a totally different approach that would increase my speed of processing files. (remember, I have 50K files of each close to 10K lines).
A:
Well you are repeating the operation 2 times: Once to iterate over the string and mkString "\n" and then writing these lines to a file. Instead you could do it in one go:
for(x <-processedLines){
outFile.write(x);
outFile.write("\n");
}
|
[
"meta.stackexchange",
"0000240494.txt"
] | Q:
What can I do against moderators with double standards?
On Arqade I re-edited a question title to make it a tad clearer, along the same lines as other users have suggested we post titles. I was heckled to oblivion, with comments telling me that titles were up to the OP in the end, and it was not my place to judge that.
So I went back to a previous question that had had a title that was in line with what the meta post suggests, a question that I had asked, changed the title back to the first title I had picked, and then the moderators banned me right away.
For no apparent reason, except to say, double standard. They told me I had no right to judge the original askers intent, yet they judged my intent on my very own question.
What do I do in this case? The moderators that have banned me have made baseless claims, accusing me of trolling, when in fact, the same moderator who has banned me has trolled me before, making rude, accusatory comments directed towards me in the past.
A:
Well, there are a few popular strategies here, and considerable debate as to which is the "best"... I'll lay them out and leave the decision up to you.
The Archivist
This strategy involves carefully monitoring a moderator's activity over time, potentially many months or even years. Notes are taken of any inconsistencies between what the moderator says and does, supporting information (transcripts, screenshots, archive.org links) are attached and annotated.
Finally, the archive is presented, either publicly or to the site administrators, along with the assertion that - in light of such overwhelming evidence of malfeasance - the only sane option is to remove the moderator from his position and send him away in disgrace.
The Robot
In this strategy, one distills each utterance of the duplicitous moderator into its most literal form, bereft of all nuance, and tirelessly applies it in every possible context until the rest of a community is in an uproar over the resulting chaos... At this point, the robot presents his defense: "this moderator commanded me to do so. Your grievance is not with me, but with him!"
The Rage Quitter
Generally the easiest but least effective strategy, a rage-quitter responds to any official rebuke with a tirade of vulgarity and accusation, then leaves the site vowing never to return. Unlike the previous two strategies, rage-quitting has little chance of actually convincing anyone else that the dastardly moderator is actually in the wrong - its success hinges on the Quitter's ability to vaporize all semblance of order and dignity with his outburst, leaving behind a smoking wasteland for which the moderator must take responsibility. Once the dust has settled, the Quitter may quietly return to the site, disclaiming all knowledge of the distant past in which such alleged outbursts might have been said to occur.
The Legislator
This clever strategist does not seek to attack the wretched moderator directly, but instead calls him out obliquely - making references only to "certain confused users" who are "struggling to understand our ambiguous rules". The Legislator then draws up plans to "clarify" the rules, carefully defining each scenario in which they apply and the resulting implications in the most minute detail. The goal here is to prevent the moderator from speaking up without incriminating himself, while simultaneously tying his hands to prevent such meddling in the future.
The Communicator
Easily the most boring strategy of the lot, this strategist calmly talks to the moderator, perhaps even in public, laying out the behavior he found worrisome and asking politely for clarification or correction. Success in this strategy is anticlimactic; all but the most stupid moderators will recognize that the game is up and either explain or reverse their actions to avoid the wrath of the community. I honestly cannot recommend using this strategy unless you for some reason wish for a long and productive future on the site.
A:
The Community Managers are the Moderators' "bosses". They're the ones who are going to do anything, if anything is going to be done.
I think your recourse is this:
Send an email message to [email protected]. Explain the situation as best you can. Provide links and any other evidence you have to make your case.
I suggest you be upfront. It takes two to make a conflict, so own up to your own behavior; don't sugarcoat it. The Stack Exchange team will be able to see things that us mere mortals cannot.
And then, let them investigate. I'm sure you're not the only issue they're dealing with. It may take some time. You may be asked for more information. Be patient and don't make matters worse. (It's good that you haven't name-checked anyone here.) Don't create a new account to get around your suspension. Don't continue to flog the issue here. Let the Community Team do what they're here for.
|
[
"stackoverflow",
"0017553778.txt"
] | Q:
Define formula of Countif in Excel VBA, not working
I really appreciate if anyone could help; I've been working on this for a while...
I just want to define the formula of countif in a cell, here is the code:
Range("E" & PLrowstart).Formula = "= CountIf($B$PLrowstart:$B$PLrowend" & ",B2)"
PLrowstart and PLrowend are integer variables I set before the line. The range for count if is range("B" & PLrowstart & ":B" & PLrowend). I've also tried other ways, none worked...
TIA.
A:
Range("E" & PLrowstart).Formula = "= CountIf($B$" & PLrowstart & ":$B$" & PLrowend & ",B2)"
|
[
"stackoverflow",
"0012573783.txt"
] | Q:
Scala Lift - Reading a file from "/resources/toserve"
I'm attempting to provide a StreamingResponse for files stored under Lifts resources/toserve directory, in order to authorize access for different users.
I can access an image for example with:
localhost:8080/classpath/images/test.jpg
But when I try and actually read the file using scala I keep getting file not found exceptions:
val file = new java.io.FileInputStream("/classpath/images/test.jpg")
Is there a specific method to reading files located on classpath?
Thanks in advance, much appreciated :)
A:
To read resources from the toserve-directory you need to do a call like
LiftRules.getResource("/toserve/images/test.jpg")
If you try to use 'classpath' instead of 'toserve' you will receive an empty box.
By default, Lift uses two different path-prefixes to locate resources either programmatically within the server or through a link-element from HTML. For the former, you will use the 'toserve'-prefix, for the latter the 'classpath'-prefix.
This behavior is specified in the objects net.liftweb.http.LiftRules and net.liftweb.http.ResourceServer. In particular, you can there specify (i.e. replace) the path to the resources. The relevant code is:
/** (from net.liftweb.http.ResourceServer)
* The base package for serving resources. This way, resource names can't be spoofed
*/
var baseResourceLocation = "toserve"
You might also want to look at the following method in LiftRules, which allows you to redefine the name used to serve resources through the server:
/** (from net.liftweb.http.LiftRules)
* The path to handle served resources
*/
@volatile var resourceServerPath = "classpath"
If you wish to use the same prefix to refer both to resources you can use either (or both) of these settings to achieve your purpose.
|
[
"ru.stackoverflow",
"0000928438.txt"
] | Q:
В чем преимущества sklearn.impute.SimpleImputer перед подсчетом среднего вручную?
Обрабатываю пропуски вещественных признаков, заполняя их средним:
X_data = pd.DataFrame()
for column in data.columns[:num_of_numerical_vars]:
m1 = data[column].mean()
if np.isnan(m1):
m1 = data[column].notnull().mean()
X_data[column] = data[column].fillna(m1)
В соседнем вопросе мне рекомендовали использовать SimpleImputer.
from sklearn.impute import SimpleImputer
impute = SimpleImputer(strategy='mean')
impute.fit_transform(X_data)
Подскажите, в чем преимущества второго подхода?
A:
Главное преимущество в том, что используя Simpleimputer можно за один вызов заполнить пропущенные значения во всех числовых столбцах. Кроме этого можно выбрать стратегию заполнения отличную от заполнения средним арифметическим значением - можно, например, заполнять отсутствующие значения медианным значением, наиболее часто встречающимся значением или константным значением.
Еще одним преимуществом данного подхода является возможность комбинировать различные методы обработки в SciKit-Learn в Pipeline - пример использования
|
[
"stackoverflow",
"0032259454.txt"
] | Q:
Error when doing (supported) float texture write in iOS Metal
When I try to write to a float texture from a kernel, I get the error:
/SourceCache/AcceleratorKit/AcceleratorKit-17.7/ToolsLayers/Debug/MTLDebugComputeCommandEncoder.mm:596: failed assertion `Non-writable texture format MTLPixelFormatR32Float is being bound at index 2 to a shader argument with write access enabled.'
However, when I go check in the documentation, that format is color-renderable and function-writeable (see table at the bottom):
https://developer.apple.com/library/prerelease/ios/documentation/Metal/Reference/MetalConstants_Ref/index.html#//apple_ref/c/tdef/MTLPixelFormat
Partial code:
// texture creation
MTLTextureDescriptor *floatTextureDescriptor = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatR32Float width:_width height:_height mipmapped:NO];
_myFloatTexture = [self.device newTextureWithDescriptor:floatTextureDescriptor];
// texture binding
[computeCommandEncoder setTexture:_myFloatTexture atIndex:2];
// texture used in the shader
void kernel myKernel(//...
texture2d<float, access::write> myFloats [[ texture(2) ]],
uint2 gid [[ thread_position_in_grid ]])
Am I doing something wrong or might this be a bug?
A:
They are supported only from iOS 9.
|
[
"stackoverflow",
"0001921481.txt"
] | Q:
AS2: Does xml.sendAndLoad use POST or GET?
All,
I'm trying to find out, unambiguously, what method (GET or POST) Flash/AS2 uses with XML.sendAndLoad.
Here's what the help/docs (http://livedocs.adobe.com/flash/9.0/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00002340.html) say about the function
Encodes the specified XML object into
an XML document, sends it to the
specified URL using the POST method,
downloads the server's response, and
loads it into the resultXMLobject
specified in the parameters.
However, I'm using this method to send XML data to a Java Servlet developed and maintained by another team of developers. And they're seeing log entries that look like this:
GET /portal/delegate/[someService]?svc=setPayCheckInfo&XMLStr=[an encoded version of the XML I send]
After a Google search to figure out why the POST shows up as a GET in their log, I found this Adobe technote (http://kb2.adobe.com/cps/159/tn_15908.html). Here's what it says:
When loadVariables or getURL actions are
used to send data to Java servlets it
can appear that the data is being sent
using a GET request, when the POST
method was specified in the Flash
movie.
This happens because Flash sends the
data in a GET/POST hybrid format. If
the data were being sent using a GET
request, the variables would appear in
a query string appended to the end of
the URL. Flash uses a GET server
request, but the Name/Value pairs
containing the variables are sent in a
second transmission using POST.
Although this causes the servlet to
trigger the doGet() method, the
variables are still available in the
server request.
I don't really understand that. What is a "GET/POST hybrid format"?
Why does the method Flash uses (POST or GET) depend on whether the data is sent to a Java servlet or elsewhere (e.g., a PHP page?)
Can anyone make sense of this? Many thanks in advance!
Cheers,
Matt
A:
Have you try doing something like that :
var sendVar=new LoadVars();
var xml=new XML("<r>test</r>");
sendVar.xml=xml;
sendVar.svc="setPayCheckInfo";
var receiveXML=new XML();
function onLoad(success) {
if (success) {
trace("receive:"+receiveXML);
} else {
trace('error');
}
}
receiveXML.onLoad=onLoad;
sendVar.sendAndLoad("http://mywebserver", receiveXML, "POST");
|
[
"stackoverflow",
"0058541389.txt"
] | Q:
Method push is not adding a value to a vector that previously had the same value
The goal of the code I'm going to present is to create a aux vector that will contain petri nets transitions, arcs and places. I'm dividing a petri net into several groups, each group is a transition with respective input arcs and places.
The issue is the following: After I put the info in the first position of the aux vector, I'm unable to put a place with the same id of the place of the previous group. For example, if I have a transition with place_id=1 and place_id=2, and the next transition have place_id=2 and place_id=3, the code doesn't write the value place_i=2 in the vector for the second group.
function conflict() {
var id = [];
var source = [];
var target = [];
var aux = [];
var cont = [];
var places = pnml.getElementsByTagName("place");
var arcs = pnml.getElementsByTagName("arc");
var transitions = pnml.getElementsByTagName("transition");
for (var i = 0; i < transitions.length; i++) {
target.push(transitions[i].getAttribute("id"));
aux.push([]);
for (var j = 0; j < arcs.length; j++) {
if (arcs[j].getAttribute("target") == transitions[i].getAttribute("id")) {
id.push(arcs[j].getAttribute("id"));
source.push(arcs[j].getAttribute("source"));
//console.log(arcs[j].getAttribute( "source" ));
}
}
//console.log(id);
//console.log(arcs);
//console.log(places);
aux[i].push(id, source, target);
//id.length=0;
target = [];
source = [];
id = [];
}
}
Image of the platform with console open
Thanks in advance
A:
Without knowing a whole lot for the issue, try to change this
aux.push([]);
to this
aux[i]=[];
So that you initialize and fill using an index instead of a push and an index later, for consistency.
Let me know if it helps
EDIT:
Also this
aux[i].push(id, source, target);
to this (maybe? )
aux[i].push({ id: id, source:source, target:target});
You probably want to keep objects in aux, so you need to push an object, not 3 parameters like that
|
[
"serverfault",
"0000009728.txt"
] | Q:
How and where can I find a good part-time sysadmin?
I run a small (tiny for now) business, and I find I need a sysadmin for a couple of hours a month. I'm not good enough at it, and I don't enjoy it so I'm unlikely to ever be so. I'd like to hire outside help. Does anybody have any tips on where to look for, and how to evaluate, sysadmins? If it makes a difference my platform is Java on Linux.
A:
If you are near to a college / university I might also suggest that you contact the CS department and see if there is a student that they might be willing to recommend. The cost is less and you will frequently get as good or better attention than a freelancer. Explain to the head of the department exactly what you're looking for and give the student a good interview. It's good for you to make sure you have a picture of exactly what you need and can also help to jump start the career of a young person.
Of course you will not necessarily get the experience you would from a freelancer or consulting firm, so do with this what you will. But I am a strong advocate of giving young people a chance to get going!
A:
I have used various freelance web sites like Scriptlance and Get A Freelancer with good success. While those sites mostly focus on programming projects, there are categories for system administration and related tasks.
I've hired several part time junior admins from both of those sites with good results.
|
[
"stackoverflow",
"0014868556.txt"
] | Q:
Cannot start a script
#!/bin/bash
value=$(<man.txt)
echo "$value"
if [ "$value" == "true" ]; then
echo "startedif_manthan"
ps -ef|grep sym |awk '{ print $2 }'|sudo xargs kill -9;
sleep 30;
sudo sh /var/www/symmetric-ds-3.1.6/bin/sym --port 8082 --server;
fi
Hi There, I have this script killing a process and restart the script in some time. It is killing the script normally but the restart script (sudo sh /var/www/symmetric-ds-3.1.6/bin/sym --port 8082 --server) is not running properly. when I run the script manually also it is giving problems. I don't know whether it is a shell script or not. But when I tried to go manually to the script location and execute this command ./sym --port 8082 --server the script running normally.
Any suggestions?
A:
Since you say it works OK when you cd to the script directory, then do that in the script:
#!/bin/bash
value=$(<man.txt)
echo "$value"
if [ "$value" == "true" ]
then
echo "startedif_manthan"
ps -ef|grep sym |awk '{ print $2 }'|sudo xargs kill -9
sleep 30
(cd /var/www/symmetric-ds-3.1.6/bin; sudo sh ./sym --port 8082 --server)
fi
|
[
"stackoverflow",
"0033713063.txt"
] | Q:
Static IP for Cloud Service on Azure
I have a Cloud Service that has Worker Role. Cloud Service is set to scale at 5 instances. There is an operation that requires communication from Azure to our data center. For the communication to happen, we have to Whitelist the IP address.
My question is that since I have set the Cloud Service to have 5 instances, do I need 5 static IPs or 1?
Also how does this pan out if I set it to Auto Scale?
A:
All five (or any number of) instances in a single Cloud Service sit behind a single IP address.
The assigned IP address for the cloud service doesn't change unless you deprovision and reprovision the service (xyz.cloudapp.net). So, if you resolved your cloudapp.net name to an IP address, you'd be able to whitelist that IP address (until such time that you take down the Cloud Service. Then the IP address is lost).
If you want to ensure that you always know the IP address, even if you deprovision / reprovision, you can set up a reserved IP address in Azure, and then assign it to the Cloud Service.
More info on reserved IP addresses here.
|
[
"stackoverflow",
"0010314049.txt"
] | Q:
Stop jquery from adding links…
i have a function that is supposed to create a button on every time a element is cloned. The problem is that it is adding a button to all elements within that div even though there already is one. I sure this is a simple task but just cant get my head around it.
<h1>skapa ett moment</h1>
<?php foreach($rows as $r) : ?>
<div class="span6 part">
<button id="add_part" class="btn-mini btn pull-right">Lägg till</button>
<div class="moment_content">
<h1 class="part_heading"><?php echo $r->title; ?></h1>
<h4 id="id" style="display:none;" class="pull-left"><?php echo $r->id;?></h4>
<div class=""><?php echo $r->content; ?></div>
</div>
</div>
<div id="result" class="span3 pull-right">
</div>
<?php endforeach; ?>
<script type="text/javascript">
var knapp = $('.part').find('.btn').hide();
$('.part').hover(function(){
$(this).toggleClass('well');
$(this).children('.btn').toggle();
});
$('button#add_part').on('click', function(){
var add = $(this).next().clone().appendTo('#result');
if ($('<a class="btn-mini pull-right btn" href="#">ta bort</a>').length > 0)
{
$('<a class="btn-mini pull-right btn" href="#">ta bort</a>').insertBefore('#result .part_heading');
}
if ($('<a class="btn-mini pull-right btn" href="#">ta bort</a>').length > 1){
$('#result a.btn').remove();
}
});
</script>
A:
I would do something like this jsBin live example
To work, you need some changes:
remove all id's
add btn-add-part as a class to the button
change the <h4> with the removable link
if you want to access the added id's, I have included the data-content-id as part of the <div> block
put the <div id="result"> outside your loop (as I'm assuming that's what you want after all
I also have styled a little bit to be easier to follow up...
The jQuery code is essentially:
$(function(){
// hide all "ADD" buttons
$(".btn-add-part").hide();
// on mouse over .part
$(".part").hover(function() {
$(this).toggleClass("well").find(".btn-add-part").stop().fadeToggle();
});
// on "ADD" click
$(".btn-add-part").click(function() {
// clone DOM block
var block = $(this).closest(".part").find(".moment_content").clone();
// show remove link
block.find(".btn-rem-part").show();
// append to result
block.appendTo("#result");
});
// on "REMOVE" click
$(".btn-rem-part").live("click", function() {
$(this).closest(".moment_content").fadeOut("slow", function() {
// Now that faded, let's remove it...
$(this).remove();
});
});
});
Added Save Button
// on "SAVE"
$(".btn-Save").click(function() {
// empty?
if($("#result").length > 0) {
var r = "";
$("#result").find(".moment_content").each(function() {
// for each block added
if(r.length > 0) r += ", ";
r += $(this).attr("data-content-id");
});
alert("Submiting the following ID's: " + r);
return true;
}
alert('Nothing to save...');
return false;
});
|
[
"webmasters.stackexchange",
"0000103355.txt"
] | Q:
An email says that my AdSense application has been successfully reviewed but the site says the application is stlill being reviewed
I got an email from adsense after submitting my application
Your application has been successfully reviewed. Now you need to
create your first ad unit and place the ad code on www.example.com to
fully activate your account. Note that before your account is fully
activated, only blank ads will appear on your pages. Once your account
is fully activated, you’ll receive a confirmation email and begin to
see live ads. Please don't click on your live ads, even to test them –
doing so isn't permitted by the AdSense programme policies. Sign in to
Google Adense to create your first ad unit and get fully approved.
Then I sign in to Google AdSense account but it is still saying
we are reviewing your site. Reviewing your site will take up to 3
days. We'll email you when we've finished.
and I am not able to click on any option in left side.
So how can I create ads?
Can someone help what to do next
A:
I'm experiencing this same problem, but I got my email a week ago. For that entire week, my account has said, "Reviewing your site will take up to 3 days. We'll email you when we're done." I've already got the email saying the review is successful.
Any additional advice...? It doesn't seem that waiting a little longer is doing the trick.
|
[
"math.stackexchange",
"0000105244.txt"
] | Q:
Does the logistic function really uniquely satisfy this?
It is said that the logistic function (denoted $y(u)$ below) is derived from the relation:
$$\frac{dy}{du}=y(u)(1-y(u))$$
Does $y(u)=\frac{1}{1+e^{-u}}$ really uniquely satisfy this? I don't see how. It seems to me there must be several functions that can satisfy that. Please help me to see the light.
If I am permitted a follow-up question:
What do I have to do to the first equation so that
$$y(u)=\frac{1}{1+u^{-2}}$$
satsifies it?
Thanks
A:
No, $\frac{1}{1 + e^{-u}}$ is not the only function satisfying the equation. So would any $y$ of the form $y(u) = \frac{1}{1 + C e^{-u}}$ for any fixed real number $C$, and so would $y$ given by the formula $y(u) = 0$. (These functions I've listed are it, though, as far as differentiable functions defined on all of $\mathbb{R}$ go; there aren't any others.) I will give a link on how to arrive at this result in a paragraph or two.
The function $\frac{1}{1 + e^{-u}}$ may be the only function satisfying both the differential equation and some initial condition of interest to the person asserting the uniqueness. If you are getting the uniqueness assertion from a professor or textbook, they probably have that in mind, even if they forgot to say it.
There is a general method for solving equations like these, but it is best learned from a textbook. The Wikipedia pages on separable differential equations and separation of variables are a start--- but better would be looking for "separable differential equations" in the index of the nearest calculus or differential equations book. Wikipedia (and the Internet in general, for basic material like this) is more concerned with methods for writing down formulas that solve a differential equation, than proving that the formulas produced by the method are the only solutions to the differential equation.
I'm not sure what your second question precisely is: there's nothing you can "do" to the original equation to make it have that other solution, beyond just changing the equation entirely. So really you're asking, what differential equation might have this other function as a solution.
In general, "given a function, find a differential equation satisfied by it" is not that interesting of a problem (unless you are looking for differential equations within some specific restricted class, or have other more specific goals in mind). Let's see why. If $y(1 + u^{-2}) = 1$, then differentiating both sides with respect to $u$ and using the product rule you find that $y(-2 u^{-3}) + y'(1 + u^{-2}) = 0$. This a differential equation and it is satisfied by the original function $y$ (and other functions too). So that's that.
Maybe this equation is not what you want because it explicitly involves the variable $u$. But one can prove that there is no differential equation of the form $y'(u) = F(y(u))$ satisfied by the function $y(u) = \frac{1}{1 + u^{-2}}$.
To see this, suppose there were.
Since $y(1) = y(-1) = \frac{1}{2}$ (just compute using the formula for $y(u)$) we would conclude by putting in $u = 1$ and $u = -1$ in the equation $y'(u) = F(y(u))$ that $y'(1) = F(\frac{1}{2})$ and that $y'(-1) = F(\frac{1}{2})$ and hence that $y'(1) = y'(-1)$. But you can calculate (use the formula for $y(u)$ to find a formula for $y'(u)$, and then put in $1$ and $-1$) that $y'(1)$ and $y'(-1)$ are not equal. So no such $F$ can exist.
|
[
"stackoverflow",
"0010343782.txt"
] | Q:
Return a List with multiple results using LINQ and EF
I have this simple method that returns a user:
User usr = ReliableExecution.RetryWithExpression<User, User>(u => u.FirstOrDefault(x => x.UserEmail == userEmail));
Now I need to create a similar method, but I need to return a list
List<Asset> lst = ReliableExecution.RetryWithExpression<Asset, List<Asset>>(u => u.SelectMany(x => x.EventId == eventId));
My problem is with the [SelectMany(x => x.EventId == eventId)] part that doesn't compile and I can't understand exactly how to use LINQ to get multiple results.
I have specified "SelectMany" just for an example, it can be whatever you find correct.
This is the signature of RetryWithExpression for reference:
public static TValue RetryWithExpression<T, TValue>(Func<ObjectSet<T>, TValue> func, Int32 retryInfiniteLoopGuard = 0)
where T : class
A:
I think your expression should be rewritten as follows:
List<Asset> lst = ReliableExecution
.RetryWithExpression<Asset, List<Asset>>(
u => u.Where(x => x.EventId == eventId).ToList()
);
In simple terms, SelectMany flattens a "list of lists of items A" into a "list of items B" using a functor that extracts a list of items B from each single item A; this is not what you want to do.
|
[
"stackoverflow",
"0053816753.txt"
] | Q:
Decode a Python string
Sorry for the generic title.
I am receiving a string from an external source: txt = external_func()
I am copying/pasting the output of various commands to make sure you see what I'm talking about:
In [163]: txt
Out[163]: '\\xc3\\xa0 voir\\n'
In [164]: print(txt)
\xc3\xa0 voir\n
In [165]: repr(txt)
Out[165]: "'\\\\xc3\\\\xa0 voir\\\\n'"
I am trying to transform that text to UTF-8 (?) to have txt = "à voir\n", and I can't see how.
How can I do transformations on this variable?
A:
You can encode your txt to a bytes-like object using the encode-method of the str class.
Then this byte-like object can be decoded again with the encoding unicode_escape.
Now you have your string with all escape sequences parsed, but latin-1 decoded. You still have to encode it with latin-1 and then decode it again with utf-8.
>>> txt = '\\xc3\\xa0 voir\\n'
>>> txt.encode('utf-8').decode('unicode_escape').encode('latin-1').decode('utf-8')
'à voir\n'
The codecs module also has an undocumented funciton called escape_decode:
>>> import codecs
>>> codecs.escape_decode(bytes('\\xc3\\xa0 voir\\n', 'utf-8'))[0].decode('utf-8')
'à voir\n'
|
[
"math.stackexchange",
"0000920953.txt"
] | Q:
What is the order of operations in trig functions?
Is $\sin(x)^2$ the same as $\sin^2(x)$ or $\sin(x^2)$? I thought it would mean the former interpretation, $\sin^2(x)$, rather than the latter, but my teacher and I had a long argument on this and in the end I found that Casio calculators have a space between before the parenthesis, so it would look like $\sin\text{ }(x)^2$ and what the calculator would do is calculate $x^2$, and then take the $\sin$ of that whereas on Texas calculators, there is no space, so it would look like $\sin(x)^2$ and it will calculate $\sin$ of $x$ first, and then take the result and square it.
A:
$$\Large \sin(x)^2 \equiv [\sin(x)]^2 \equiv \sin^2(x).$$
Think about it: if $\sin(x)^2$ were equivalent to $\sin(x^2),$ then the exponent $\quad ^2 \quad$ would be inside the brackets.
|
[
"stackoverflow",
"0010065377.txt"
] | Q:
Rails 3 - link_to() - need multiple text segments with separate HTML/CSS classes in a single link
I'm creating a "compound" link using link_to. The link text has a prefix portion formatted in one CSS style, and a root portion formatted in a different CSS style. For example:
preprocess
I've been able to crudely achieve this with two, back-to-back link_to statements:
<div class="dual-format-link">
<%= link_to 'pre', compound_path, :class => "prefix-style" %><%= link_to 'process', compound_path, :class => "root-style" %>
</div>
Unfortunately the roll-over affect clearly shows that these are two different links, just arranged side-by-side. The fact that it is not a single, unified link causes user confusion.
I tried putting HTML in link_to's first argument but it is displayed as raw HTML.
Is there a way to have link_to do this? Are there alternatives to link_to that would work?
A:
You have to tell Rails that the html is okay to render as html instead of escaped plain text by using html_safe:
<div class="dual-format-link">
<%= link_to '<span class="prefix-style">pre</span><span class="root-style">process</span>'.html_safe, compound_path %>
</div>
See http://yehudakatz.com/2010/02/01/safebuffers-and-rails-3-0/ for more information.
|
[
"stackoverflow",
"0056328776.txt"
] | Q:
class method triggered without being called
I've defined a class to handle playing audio files. I'm instantiating the class, and calling its addEventListener() method at which time, playSound() is being triggered without the element being tapped. Also, when I call getEventListeners(bgMusic.elem) - the listener is no longer attached.
class WebAudio {
constructor(soundFile, elem) {
this.soundFile = soundFile;
this.elem = elem;
this.audio = new Audio('sound/' + this.soundFile);
}
addListener() {
this.elem.addEventListener('touchstart', this.playSound());
}
playSound() {
if (context.state != 'suspended') {
console.log('playing audio file');
if (!this.audio.playing) {
this.audio.play();
}
} else {
console.log("Audio Context locked? " + context.state)
}
}
}
var AudioContext = window.AudioContext || window.webkitAudioContext;
var context = new AudioContext();
function webAudioTouchUnlock(context) {
return new Promise( (resolve, reject) => {
//if AudioContext is suspended, and window has been interacted with
if (context.state === 'suspended' && 'ontouchstart' in window) {
console.log(context.state);
var unlock = () => {
//resume AudioContext (allow playing sound), remove event listeners
context.resume().then(() => {
console.log("context resumed");
document.body.removeEventListener('touchstart', unlock);
document.body.removeEventListener('touchend', unlock);
resolve(true);
}, function (reason) {
reject(reason);
});
};
document.body.addEventListener('touchstart', unlock, false);
document.body.addEventListener('touchend', unlock, false);
} else {
console.log('context not suspended? Context is ' + context.state);
resolve(false);
}
});
}
webAudioTouchUnlock(context);
let bgMusic = new WebAudio('bensound-clearday.mp3', document.querySelector('#sound_button'));
bgMusic.addListener();
A:
When you add the event listener like:
this.elem.addEventListener('touchstart', this.playSound());
You care calling the function: this.playSound() and adding the result of that function (undefined) as the listener.
You just want to add the reference to the function:
this.elem.addEventListener('touchstart', this.playSound);
so the listener can call it when it needs too.
Also you will probably need to use something like this to maintain the proper this:
this.elem.addEventListener('touchstart', () => this.playSound());
or:
this.elem.addEventListener('touchstart', this.playSound.bind(this));
|
[
"stackoverflow",
"0023879774.txt"
] | Q:
Gnuplot plot error bars every 10 data points
I want to plot my data with error bars. It is to do with the syntax
plot "xyz.dat' u 1:2:3 w yerrorbars
However, since my data file has 10000 data points, plotting all error bars would make the error bars overshadow the line shape of the data. So I want to plot error bars every 10 data points. How can I do that?
A:
Try
plot "xyz.dat" u 1:2:3 every 10 w yerrorbars
Also look at:
How do I plot every nth point
|
[
"stackoverflow",
"0004282507.txt"
] | Q:
Why does openssl_pkey_new() fail?
I'm very new to this. Why is openssl_pkey_new() returning false?
I am using XAMPP and there is a an OpenSSL under the Apahce\bin directory.
What obvious beginner mistake am I making? Maybe it's a matter of SSL configuration?
My goal is to write the two keys into two files.
Update: as suggested, I used openssl_error_string() and it says error:02001003:system library:fopen:No such process. It sounds like maybe OpenSSL isn't running or isn't in the path?? Any ideas?
Update: I put c:\xampp\php into the windows path, so that it could find libeay32.dlland restarted Apache.
Now I get error:2006D080:BIO routines:BIO_new_file:no such file. Any ideas?
A:
Use openssl_error_string() to find out why openssl_pkey_new() is returning false (or any other OpenSSL error).
After your latest update, it appears that OpenSSL can't find the openssl.cnf file, as described here.
|
[
"tex.stackexchange",
"0000204555.txt"
] | Q:
Justify without indent
I was wondering how I can justify the text without making it indenting with \justifying.
I'm using
\usepackage[parfill]{parskip}
Secondary question:
Any way how to increase the parskip distance, by the way?
Thanks!
A:
Text is justified to both margins by default. To control the indentation of the first line and spaces between paragraphs you need only set respectively \parindent and \parskip lenghts, without any package.
An example with some exaggerated values to see clearly the result:
\documentclass{article}
\usepackage{lipsum} % for example dummy text
\setlength{\parskip}{2cm}
\setlength{\parindent}{5em}
\begin{document}
\lipsum[1-3]
\end{document}
Note that often in LaTex you can use extensible ans/or shrinkable lenghts (see What is glue stretching?) so one can use some like:
\setlength{\parskip}{2cm plus 1.9cm minus 1.9cm}
or
\setlength{\parskip}{2cm plus 1 fill minus 0 cm}
Experiment adding a paragraphs in the MWE (e.g. change \lipsum[1-3] to \lipsum[1-4]) and see the effect with this or another settings.
A more reasonable settings could be:
\setlength\parskip{.5\baselineskip plus .1\baselineskip minus .1\baselineskip}
\setlength\parindent{0pt}
(These are exactly the setting for the artikel3 document class, cited in the parskip documentation)
A:
It is better to use the parskip package (as shown in the question) than to just adjust the parskip and parindent yourself unless you are also prepared to make the kinds of adjustments required to avoid the side-effects of these changes.
In addition to adjusting these lengths, parskip does some basic work to avoid excessive spacing in list environments. Even if you do not think you use lists, you probably do since many LaTeX environments are based on lists. For example, quotation is a trivial list environment and there are many others.
Here is a document which just adjusts the lengths by hand based on Fran's answer:
\documentclass{article}
\usepackage{lipsum} % for example dummy text
\setlength\parskip{.5\baselineskip plus .1\baselineskip minus .1\baselineskip}
\setlength\parindent{0pt}
\begin{document}
\lipsum[1]
\begin{quotation}
\lipsum[2]
\end{quotation}
\lipsum[3]
\begin{itemize}
\item This is the first item in a list of several items, which is preceded by none but followed by some.
\item This is the second item in a list of several items, which is preceded by some and followed by some.
\item This is the third item in a list of several items, which is preceded by some and followed by some.
\item This is the fourth item in a list of several items, which is preceded by some but followed by none.
\end{itemize}
\lipsum[4]
\end{document}
As can be seen, excessive spacing is left around the quotation and list, in comparison with that which is left between regular paragraphs.
Here is the same document using parskip with default adjustments:
\documentclass{article}
\usepackage{lipsum} % for example dummy text
\usepackage[parfill]{parskip}
\begin{document}
\lipsum[1]
\begin{quotation}
\lipsum[2]
\end{quotation}
\lipsum[3]
\begin{itemize}
\item This is the first item in a list of several items, which is preceded by none but followed by some.
\item This is the second item in a list of several items, which is preceded by some and followed by some.
\item This is the third item in a list of several items, which is preceded by some and followed by some.
\item This is the fourth item in a list of several items, which is preceded by some but followed by none.
\end{itemize}
\lipsum[4]
\end{document}
It is still very possible to adjust the parskip while benefiting from the package's improved layout of list environments. This example uses the same parskip as that in the first document and as specified in Fran's 'reasonable' settings:
\documentclass{article}
\usepackage{lipsum} % for example dummy text
\usepackage[parfill]{parskip}
\setlength\parskip{.5\baselineskip plus .1\baselineskip minus .1\baselineskip}
\begin{document}
\lipsum[1]
\begin{quotation}
\lipsum[2]
\end{quotation}
\lipsum[3]
\begin{itemize}
\item This is the first item in a list of several items, which is preceded by none but followed by some.
\item This is the second item in a list of several items, which is preceded by some and followed by some.
\item This is the third item in a list of several items, which is preceded by some and followed by some.
\item This is the fourth item in a list of several items, which is preceded by some but followed by none.
\end{itemize}
\lipsum[4]
\end{document}
As can be seen, the manual adjustment of the parskip length does not undermine the enhancements to layout achieved by loading the parskip package. So this option offers the best results with standard classes.
That is, some classes are designed to accommodate non-zero parskip and zero parindent in their design, and these will likely have more fine-grained tuning. But for classes which are not so designed, loading the package parskip instead of, or in addition to, setting the parskip length explicitly will give the best results.
To avoid the oddity of the indented paragraph in the quotation, either use quote rather than quotation or let the latter environment be equal to the former one:
\documentclass{article}
\usepackage{lipsum} % for example dummy text
\usepackage[parfill]{parskip}
\setlength\parskip{.5\baselineskip plus .1\baselineskip minus .1\baselineskip}
\let\quotation\quote
\begin{document}
\lipsum[1]
\begin{quotation}
\lipsum[2]
\end{quotation}
\lipsum[3]
\begin{itemize}
\item This is the first item in a list of several items, which is preceded by none but followed by some.
\item This is the second item in a list of several items, which is preceded by some and followed by some.
\item This is the third item in a list of several items, which is preceded by some and followed by some.
\item This is the fourth item in a list of several items, which is preceded by some but followed by none.
\end{itemize}
\lipsum[4]
\end{document}
|
[
"math.stackexchange",
"0002252186.txt"
] | Q:
$ \lim_{ \|x\| \to 0 } \frac{E \left[ \log \left(1+ \left(\|x\|^2+ \langle x,Z \rangle \right)^2 \right) \right]}{\| x\|^2} = 1$
How to compute the limit
\begin{align}
\lim_{ \|x\| \to 0 } \frac{E \left[ \log \left(1+ \left(\|x\|^2+ \langle x,Z \rangle \right)^2 \right) \right]}{\| x\|^2}
\end{align}
where $Z$ is i.i.d. Gaussian vector of lenght $n$.
Upper bound:
\begin{align}
\lim_{ \|x\| \to 0 } \frac{E \left[ \log \left(1+ \left(\|x\|^2+ \langle x,Z \rangle \right)^2 \right) \right]}{\| x\|^2} \le \lim_{ \|x\| \to 0 } \frac{E \left[ \left(\|x\|^2+ \langle x,Z \rangle \right)^2 \right]}{\| x\|^2}
\end{align}
here we used that $\log(x) \le x-1$
Next, observe that
\begin{align}
E[\langle x, Z \rangle]=0,\\
E[\langle x, Z \rangle^2 ]= \|x\|^2
\end{align}
where the last two stament follow from i.i.d. assumption.
So, in conclusion, we have
\begin{align}
\lim_{ \|x\| \to 0 } \frac{E \left[ \log \left(1+ \left(\|x\|^2+ \langle x,Z \rangle \right)^2 \right) \right]}{\| x\|^2} \le 1.
\end{align}
I am stuck with showing the other direction.
For the lower bound one can use $\log(1+x) \ge \frac{x}{x+1}$ which result in
\begin{align}
\lim_{ \|x\| \to 0}\frac{1}{\|x\|}E \left[ \frac{\left(\|x\|^2+ \langle x,Z \rangle \right)^2 }{1+\left(\|x\|^2+ \langle x,Z \rangle \right)^2 } \right]
\end{align}
However, not sure how to proceed next.
A:
I think the following is an outline where you can get the solution.
First, consider the random variable $Y :=\langle x, Z \rangle/||x||$. Obviously, $Y$ is standard normal. Now let $a:= ||x||$, and the problem reduced to
$\lim_{a\downarrow 0} E\frac{[\log(1+(a^2+aY)^2]}{a^2}$.
Now if you want, you can calculate the expectation, however, since we are concerned with limit, I want to interchange the order or limit and expectation. Your previous solution shows that this is allowed because of dominated convergence theorem.
After interchanging the limit and the expectation, we arrived at
$E \lim_{a \downarrow 0} \frac{[\log(1+(a^2+aY)^2]}{a^2}$
To calculate the limit, use L'Hospital's Rule, and take derivative both in the denominator and numerator, you have something like
$E \lim_{a \downarrow 0} \frac{(a+Y)(2a+Y)}{1+(a^2+aY)^2} = EY^2 =1$
|
[
"stackoverflow",
"0053760051.txt"
] | Q:
PHP / JSON - Return large string result in error
I am trying to convert a PDF file to raw text. This works fine actually, however - I am not able to return the converted text with JSON.
This is how I convert the PDF to Text:
$text = (new Pdf('/usr/local/bin/pdftotext'))
->setPdf(storage_path() . '/app/temp_files/' . $name)
->text();
$text = iconv('latin5', 'utf-8', $text); //Convert foreign characters
Now if I return the $text in normal JSON like this:
return response()->json([
'result' => $text
], 200);
I get a Server Error message.
However, if I limit the string to for example 100 characters, it works fine:
return response()->json([
'result' => str_limit($text, 100)
], 200);
Returns:
{
"result": "Fuldstændig express DET EUROPÆISKE FÆLLESKAB 1ANGIVELSE 8 2 Afsender / Eksportør nr. IM MAEDEN INTER..."
}
How can I get it to return the entire text? The original PDF is a 2 pages long.
A:
This sounds like JSON is running into an encoding error.
Replace:
$text = iconv('latin5', 'utf-8', $text); //Convert foreign characters
With:
$text = mb_convert_encoding($text, 'UTF-8', 'UTF-8'); //Force the UTF-8 encoding.
Hope it helps.
|
[
"tex.stackexchange",
"0000096958.txt"
] | Q:
Switching to biblatex: how to load custom elsarticle-harv.bst style
As I am switching to biblatex for some specific purpose, but the default citation style could not fulfill the need.
By natbib:
\bibliographystyle{elsarticle-harv} % author-year
is used to load special style.
By biblatex:
\RequireBibliographyStyle{elsarticle-harv}
seems not working.
Since I had no clue to find the relevant command to load this .bst file in the extremely long package manual, so how to figure this out?
A:
As Audrey so succinctly notes in the comments, (and as Mico and I commented on your question) you simply can't use .bst files with biblatex. So the best solution would be to find existing biblatex style that comes close to the elsarticle-harv style.
Since the elsarticle-harv is a generic author-year style, the first place to start might be one of the standard author-year styles that biblatex provides. If they are not sufficient, perhaps you could try the apa style for biblatex. This produces fairly standard Author-Year citations and bibliography. Here's a simple example with references per chapter added to the table of contents.
\documentclass{book}
% The next 4 lines are required for the biblatex-apa style
% adding the refsection=chapter option makes allows each chapter to have a
% references section
\usepackage[american]{babel}
\usepackage{csquotes}
\usepackage[style=apa,backend=biber,refsection=chapter]{biblatex}
\DeclareLanguageMapping{american}{american-apa}
% load your bib file (.bib suffix required)
\addbibresource{newmainjournals.bib}
\begin{document}
\frontmatter
\tableofcontents
\mainmatter
\chapter{First Chapter}
% insert some citation commands in your text
% at the end of the chapter, print the bibliography as a section, added to TOC
\printbibliography[heading=subbibintoc]
% now repeat for the next chapter
\chapter{Second Chapter}
% some more citation commands
% and the next references section
\printbibliography[heading=subbibintoc]
\backmatter
\end{document}
|
[
"stackoverflow",
"0059095681.txt"
] | Q:
Highstock displayed inconsistent
I'm working on a website where I'm using HighStock. The site was working fine and then I went away for a few hours. When I came back the chart would only display one datapoint.
Looking in the code with Chrome there were no errors and the datpoints had been printed by the PHP correctly.
By a coincidence, I noticed when resized the window it would suddenly display correctly. The only thing that's changing on resize in my CSS is the containers width (parent of the chart div).
I tried taking just a few of my datapoints into a HighStock example on JsFiddle, there I see no datapoints. https://jsfiddle.net/p9jqvw41/
Highcharts.stockChart('chart2', {
rangeSelector: {
selected: 1
},
title: {
text: 'AAPL Stock Price'
},
series: [{
name: 'AAPL Stock Price',
data: "[1574880360000,9],[1574876760000,10],[1574873160000,10]",
type: 'spline',
tooltip: {
valueDecimals: 2
}
}]
});
I also tried:
Using a proxy to visit my site, then It's displayed
correctly. (So I guess It has to be a local error?)
Using a different browser, displayed incorrectly.
Clearing Cache, still incorrectly displayed.
The only thing that would seem reasonable is that I've reached some limited number of calls to HighStock, but even that isn't consistent with some of the mentioned above.
I feel like I'm going nuts so any help would be very appreciated.
A:
Solved: I had data in Descending order instead of Ascending, probably stopped working after update to Highchart.
|
[
"stackoverflow",
"0030926736.txt"
] | Q:
Parallel.ForEach loop is performing like a serial loop
I've spent about 8+ hours searching online for help and I couldn't find anything so, here goes.
I'm working with Team Foundation Server and C# and I'm trying to acquire a list of work items and convert them into a generic object we made to be bound to a special UI. To work items are Tasks for a specific day and the list is about 30ish items in size, so not that big of a deal.
The loop looks like this:
List<IWorkItemData> workitems = new List<IWorkItemData>();
var queryForData = Store.Query(query).Cast<WorkItem>();
if (queryForData.Count() == 0)
return workitems;
Parallel.ForEach(queryForData, (wi) =>
{
var temp = wi;
lock (workitems)
{
TFSWorkItemData tfsWorkItem = new TFSWorkItemData(temp);
workitems.Add(tfsWorkItem);
}
});
The inside of TFSWorkItemData's constuctor looks like this:
public TFSWorkItemData(WorkItem workItem)
{
this.workItem = workItem;
this.Fields = new Dictionary<string, IFieldData>();
// Add Fields
foreach (Field field in workItem.Fields)
{
TFSFieldData fieldData = new TFSFieldData
{
Value = field.Value,
OldValue = field.OriginalValue,
ReferenceName = field.ReferenceName,
FriendlyName = field.Name,
ValueType = field.FieldDefinition.SystemType
};
this.Fields.Add(field.ReferenceName, fieldData);
}
}
So it takes about 90 seconds to perform this operation. I know it doesn't take that long to grab 30 work items so it must be something I'm doing to cause this to take so long. I know that the lock is a performance hit, but when I remove it I get a InvalidOperationException saying that the collection has been modified. When I look in the details of this exception, the only useful info I can find is that the collection is a dictionary. What's weird is that it doesn't look to me like the field dictionary in the work item is being modified at all. And the dictionary in my class is only being added to and that shouldn't be the culprit unless I'm missing something.
Please help me figure out what I'm doing wrong regarding the dictionaries. I did try moving the parallel foreach loop to the workitem.Fields collection but I can't seem to get that to work.
Edit: Read comments of Answer for answer to this question. Thank you.
A:
I found a another way that might work for anyone trying to do something similar.
// collect all of the IDs
var itemIDs = Store.Query(query).Cast<WorkItem>().Select(wi = wi.Id).ToArray();
IWorkItemData[] workitems = new IWorkItemData[itemIDs.Length];
// then go through the list, get the complete workitem, create the wrapper,
// and finally add it to the collection
System.Threading.Tasks.Parallel.For(0, itemIDs.Length, i =>
{
var workItem = Store.GetWorkItem(itemIDs[i]);
var item = new TFSWorkItemData(workItem);
workitems[i] = item;
});
Edit: changed list to array
|
[
"stackoverflow",
"0006538039.txt"
] | Q:
Strip parity bits in C
Say I have a stream of bits with 8 bits of data followed by 2 parity bits (pattern repeats).
Example (x are parity bits):
0001 0001 xx00 0100 01xx 0001 0001 xx00 ...
should become
0001 0001 0001 0001 0001 0001 ...
I feel like this should be easy and I'm just over thinking it, but how do you go about stripping these parity bits?
A:
The tricky bit here is C doesn't let you work with bits easily, only bytes. I am going to assume that your char holds 8 bits (check CHAR_BIT in limits.h) -- this is the case on almost all modern systems. The least common multiple of 8 and 10 is 40, so you want to work in a buffer of at least 40 bits that you can do integer arithmetic on as a whole -- in practice that means a 64-bit type. So here's one way to do it, reading from stdin and writing to stdout. Handling streams that are not a multiple of 40 bits in length is left as an exercise.
#include <stdint.h>
#include <stdio.h>
int main(void)
{
int c;
uint_least64_t buffer;
for (;;)
{
buffer = 0;
/* read in 4 10-bit units = 5 8-bit units */
c = getchar(); if (c == EOF) break;
buffer = ((buffer << 8) | c);
c = getchar(); if (c == EOF) break;
buffer = ((buffer << 8) | c);
c = getchar(); if (c == EOF) break;
buffer = ((buffer << 8) | c);
c = getchar(); if (c == EOF) break;
buffer = ((buffer << 8) | c);
c = getchar(); if (c == EOF) break;
buffer = ((buffer << 8) | c);
/* write out the non-parity bits */
putchar((buffer & 0xFF00000000ULL) >> 32);
putchar((buffer & 0x003FC00000ULL) >> 22);
putchar((buffer & 0x00000FF000ULL) >> 12);
putchar((buffer & 0x00000003FCULL) >> 2);
}
/* deal with incomplete block here */
return 0;
}
... If you wanted to be really clever you would check those parity bits before you threw them away, although then you would have to come up with something constructive to do when (not if) the checksum failed.
|
[
"tor.stackexchange",
"0000001229.txt"
] | Q:
How to chain proxy after Tor
How can I use a proxy after Tor? Few sites that I use refuse connections from Tor due to abuse, and because of DDOS many sites behind cloudfare/akamai constantly ask me to do captcha every refresh. So is there a way to do this me -> Tor exit node -> my_proxy -> www ???
A:
There are, probably thousands of combinations you might implement.
I'm trying to collect best Unix-like versions, if somebody know better, easiest, shortest way to setup proxy after Tor, you are welcome to complete my answer.
1) Read this article TransparentProxy and this IsolatingProxy, thereafter, you may start anything under transparently anonymized specific user. For example, start Firefox, go to settings -> connection settings, set your proxy for Firefox. Your Firefox will achieve target host by next chain:
localhost -> Transparent Port ( Tor ) -> Guard ( Tor ) -> Middle ( Tor ) ->
-> Exit ( Tor ) -> Your Proxy -> Target Host
2) Another perfect tool is proxychains.
Dedicated OS: Linux and other Unices.
Configuration file /etc/proxychains.conf should be like:
strict_chain
#
# Strict - Each connection will be done via chained proxies
# all proxies chained in the order as they appear in the list
# all proxies must be online to play in chain
# otherwise EINTR is returned to the app
# Make sense only if random_chain
chain_len = 2
# Proxy DNS requests - no leak for DNS data
proxy_dns
[ProxyList]
# add proxy here ...
socks5 127.0.0.1 9050 # Tor socks5
socks5 184.152.92.156:37071 # https://hidemyass.com/proxy-list/
Now you can launch any browser via proxychains:
$ proxychains firefox
|
[
"stackoverflow",
"0025704630.txt"
] | Q:
HTML::Tree: Can't call method "as_text" on an undefined value
I am parsing a real estate web page, using HTML::TreeBuilder, and have the following code:
$values{"Pcity"} = $address->look_down("_tag" => "span",
"itemprop" => "addressLocality")->as_text;
$values{"PState"} = $address->look_down("_tag" => "span",
"itemprop" => "addressRegion")->as_text;
Some pages don't contain city or state, and the parser exits with an error:
Can't call method "as_text" on an undefined value
To fix it I used the following method:
$values{"Pcity"} = $address->look_down("_tag" => "span",
"itemprop" => "addressLocality");
if(defined($values{"Pcity"}))
{
$values{"Pcity"} = $values{"Pcity"}->as_text;
}
else
{
$values{"Pcity"} = '';
}
It works, but now instead of 1 line I have 9. And as I have many places like this the code will become considerably bigger.
Is there any way to optimize?
A:
This is shorter:
$a = $address->look_down("_tag" => "span", "itemprop" => "addressLocality");
$values{"Pcity"} = $a ? $a->as_text : '';
|
[
"stackoverflow",
"0036184969.txt"
] | Q:
RESTful Routing - Header Authorization in APIs
In the context of an API, if you're using Authorization Header tokens to authenticate the user on each request, then how do you go about setting up RESTful routes which would otherwise use the 'User ID' in the URL request?
example:
POST /api/school/5/user
Adds User to School
DELETE /api/school/5/user/???
Removes User from School
However, the DELETE request would require the User ID in the request, which if you're using a Bearer Authorization token, wouldn't be passed in the URL, which then makes those sorts of Resources difficult to setup.
How is this handled generally?
A:
The best solutions I found for this are:
1) You can pass the User ID via the URL but just compare it to the User ID of the User retrieved from the Authorization Token. So you might have a URL like:
/api/school/5/user/7
And in you Middleware, check that that User in your Authorization Heaer, matches the User passed via the URL. This way you maintain RESTful routing.
OR
2) Alter the URL structure some and have a Me route prefix. So any routes that are based around the logged in User, should be prefixed with Me (or similar). Spotify, Facebook, and many other companies' APIs use this.
I prefer it to the first solution because even though the first seems more standard, the idea of passing a user's ID in URL unnecessarily seems less than ideal.
|
[
"stackoverflow",
"0062256014.txt"
] | Q:
Does Python forbid two similarly looking Unicode identifiers?
I was playing around with Unicode identifiers and stumbled upon this:
>>> , x = 1, 2
>>> , x
(1, 2)
>>> , f = 1, 2
>>> , f
(2, 2)
What's going on here? Why does Python replace the object referenced by , but only sometimes? Where is that behavior described?
A:
PEP 3131 -- Supporting Non-ASCII Identifiers says
All identifiers are converted into the normal form NFKC while parsing; comparison of identifiers is based on NFKC.
You can use unicodedata to test the conversions:
import unicodedata
unicodedata.normalize('NFKC', '')
# f
which would indicate that '' gets converted to 'f' in parsing. Leading to the expected:
= "Some String"
print(f)
# "Some String"
A:
Here's a small example, just to show how horrible this "feature" is:
ᵢ_fᵣₑ_ₕ_dₑᵢiℓy___ᵘg = 42
print(Tℹ_eᵣe_ₛº_eᵢⁱtᵉ_ℯ__)
# => 42
Try it online! (But please don't use it)
And as mentioned by @MarkMeyer, two identifiers might be distinct even though they look just the same ("CYRILLIC CAPITAL LETTER A" and "LATIN CAPITAL LETTER A")
А = 42
print(A)
# => NameError: name 'A' is not defined
|
[
"stackoverflow",
"0049765532.txt"
] | Q:
Javascript How to migrate promise.spread syntax to async/await with destructuring
I'm cleaning up some sequelize code and the findOrCreate function returns a promise that requires spreading to get the actual result object.
I'd like to rewrite my code to use await instead and, given ES6 supports array destructuring I'd have thought that instead of
User.findOrCreate({ where: { mcId }, defaults }).spread((user, created) => {
// do stuff
})
I'd just be able to do
const [user, created] = await User.findOrCreate({ where: { mcId }, defaults })
but alas that's not the case.
I get the error (intermediate value) is not iterable
Is there any special trick to doing this or is what I am trying to do just not possible?
A:
I'm using Sequelize v4.37.10 and this worked for me -
const [address, created] = await models.Address.findOrCreate({ where: { pid: 123}, defaults});
|
[
"stackoverflow",
"0030757432.txt"
] | Q:
Modify variables inside a function with javascript
I'd like to know if it is posible, having one or more variables to pass them into a function and get those variables modified. I think it is posible with objects, as they behave as references, but I don't know.
With 1 var you could do:
var something = increase(something);
but what if you have, for example, 2 variables with recipies, and would like to exchange them?
exchange_recipies(book1, book2);
You could do this but the variables are parameters inside the function... So is there another way that I'm missing?
EDIT: I know it can be done in many ways but I'll state some here that I don't like due to obvious limitations:
-Use global variables.
-Use objects
-Return an array and reasign.
EDIT2: this Is it possible to change the value of the function parameter? helped me, but I think that answer is uncomplet and there are ways of doing this.
A:
If the variables are declared globally then you wouldn't need to pass them into the function since they can be addressed inside the function.
var something = 1
function bar(){
something = increase(something);
}
For example.
This means you avoid changing the variables into parameters and can then address them from any function (dependant on nesting, ergo, if the variable is declared inside a function it can't be addressed outside of that function but can from a function inside)
function foo(){
var something = 1
function bar(){
//works because it exists in the parent function
something = increase(something)
}
}
function foobar()
//Something doesn't exist here so would return something = undefined
something = increase(something)
}
|
[
"stackoverflow",
"0030379811.txt"
] | Q:
Result based method call after a unittest in Python
How do you call a function after each test in a Python unittest.TestCase derived class based on the test result?
For instance, lets say we have the following test class:
import sys
from unittest import TestCase
class TestFeedback(TestCase):
def msg(self, text):
sys.stdout.write(text + ' ...')
def on_fail(self):
sys.stdout.write(' FAILED!\n')
def on_success(self):
sys.stdout.write(' SUCCEEDED!\n')
def test_something(self):
self.msg('Testing whether True == 1')
self.assertTrue(True == 1)
def test_another(self):
self.msg('Testing whether None == 0')
self.assertEqual(None, 0)
I would like the methods on_success() or on_fail() to be called after each test depending on the outcome of the test, e.g.
>>> unittest.main()
...
Testing whether True == 1 ... SUCCEEDED!
Testing whether None == 0 ... FAILED!
<etc.>
Can this be done and, if so, how?
A:
As of right now, I don't think you can do this. The TestResult object is gone before you get to your tearDown method, which would most likely be the easiest.
Instead, you could roll your own TestSuite (see here for a basic explanation), which should give you access to the results for each test. The downside is that you would have to add each test individually or create your own discovery method.
Another option would be to pass an error message into your asserts; the messages will be printed on fail:
self.assertEqual(None, 0, 'None is not 0')
What is your end goal here? Running the unittests will tell you which tests failed with traceback information, so I imagine you have a different goal in mind.
Edit:
Alright, I think one solution would be to write your own custom TestCase class and override the __call__ method (note: I haven't tested this):
from unittest import TestCase
class CustomTestCase(TestCase):
def __call__(self, *args, **kwds):
result = self.run(*args, **kwds)
<do something with result>
return result
Edit 2:
Another possible solution...check out this answer
|
[
"stackoverflow",
"0004296313.txt"
] | Q:
Django - Limit the entries in models.ForeignKey()
class UserCustomer(models.Model):
user = models.ForeignKey(User)
customer = models.ForeignKey(CustomerProfile)
In admin interface, while adding a new record, is it possible to restrict(remove) the 'user' in user drop down, if that user is already associated with any customer?
A:
Does this answer your question?
How about this one? He goes through multiple examples including filtering ModelAdmin inlines (which I think is what you're after).
|
[
"mathematica.stackexchange",
"0000059127.txt"
] | Q:
$Path hijacked by PacletManager?
Summary:
Since Mathematica version 6, the PacletManager seems to have engineered an escalating hijack of the $Path variable. Add-on packages need to have a PacletInfo.m file for their documentation to function correctly. However, use of this file also seems to trigger an override of the $Path variable's control of file loading. This breaks some of the functionality of Wolfram Workbench when using Mathematica 9 and 10.
Examples:
Suppose, as a minimal example, I have a Test directory in my $UserBaseDirectory/Applications directory that contains a PacletInfo.m file that reads
Paclet[
Name -> "Test",
Version -> "0.0.1"
]
as well as a file foo.txt containing the text "Applications directory".
Also, in my $HomeDirectory I have another Test directory containing just a text file foo.txt reading "Home directory".
Now, Mathematica 6 behaves as I would expect -- if I empty the $Path variable, Get can't find either foo.txt file, and if I put the $HomeDirectory in the $Path it will find the file in the $HomeDirectory (note: clearing the $Path variable will interfere with stuff like searching the documentation, so you probably want to run these in a fresh kernel and then restart):
$Path = {};
Get["Test/foo.txt"]
(* During evaluation of In[2]:= Get::noopen: Cannot open Test/foo.txt. *)
(* $Failed *)
$Path = {$HomeDirectory};
Get["Test/foo.txt"]
(* "Home directory" *)
In Mathematica 7 or 8, there is a different behavior -- even with an empty $Path it will find foo.txt in the Applications directory, but with $HomeDirectory in the path it will find foo.txt in the $HomeDirectory, as before:
$Path = {};
Get["Test/foo.txt"]
(* "Applications directory" *)
$Path = {$HomeDirectory};
Get["Test/foo.txt"]
(* "Home directory" *)
In Mathematica 9 or 10, however, it always finds the text file in the Applications directory, even if only the $HomeDirectory is in the $Path:
$Path = {};
Get["Test/foo.txt"]
(* "Applications directory" *)
$Path = {$HomeDirectory};
Get["Test/foo.txt"]
(* "Applications directory" *)
With no PacletInfo.m file we get the expected (version 6) behavior in all versions. As a side note, there is no effect on the results if we change the name of the Test directory in the $UserBaseDirectory/Applications directory to something else; Get behaves as if foo.txt were in a directory with whatever name is listed in the PacletInfo.m file.
Discussion:
What seems to be happening is that, when a new kernel is started (or if we manually call PacletManager`RebuildPacletData[]), a list of paths is scanned for PacletInfo.m files, and the Name entries in those files are registered as directory search paths, corresponding to the actual directories in which the PacletInfo.m files are located. In recent versions these paths take precedence over the search paths in $Path.
The behavior in versions 9 and 10 interferes with the way Wolfram Workbench is supposed to work. When launching Mathematica from the Workbench, it puts the local development folder at the beginning of the $Path variable directory list, so that the development version of the package is loaded, rather than any installed version in the Applications directory. When the PacletInfo.m file present, however, the installed version is always loaded.
My questions:
I'm curious if anyone has any insight as to whether the current behavior is considered desirable. Clearly a list of documentation directories has to be maintained, but is it necessary for the $Path to be overridden?
Does anyone have a workaround to get Workbench to load the development version of a package? The obvious method is to either overwrite or delete the installed version in the Applications directory, but this is clumsy. More elegant would be to manually add the development directory to the beginning of the paclet search path, as well as to the $Path, but I haven't found a way of doing that yet.
A:
Edit
From version 9 PacletInfo.m file requires "Kernel" extension with Context specification. Without it loading paclets using contexts doesn't work (see old answer).
Up to version 8 $Path has precedence over paclet search path no matter how package is loaded.
In versions 9.0 - 10.1 paclet search path has precedence over $Path no matter how package is loaded.
Since version 10.2 paclet search path is used and has precedence only when package is loaded using its context. When package is loaded using file path - paclet search path is not used at all - only $Path.
As noted in comment by Kuba, since version 9, when paclet is loaded using context, always newest version (determined by Version property from PacletInfo.m) from all available on paclet search path, is loaded, regardless of order of adding directories to paclet search path. Order of adding directories to paclet search path matters only when paclets in different directories have same version, then the one from directory added later has precedence.
Old Answer
Adding directory to the beginning of the paclet search path
One thing to note is that paclet search path is used only when getting files using a path with ordinary path separator. When getting packages using path with elements separated by context separator ` paclet search path is not used.
To add a directory to beginning of paclet search path in Mathematica versions 9.0 and 10.0 one can use PacletManager`PacletDirectoryAdd function.
To see how it works let's use slightly modified example from question i.e. instead of foo.txt let's use foo.m.
In Mathematica version 9 and 10 we get:
$Path = {};
Get["Test`foo`"]
(* Get::noopen: Cannot open Test`foo`. >> *)
(* $Failed *)
Get["Test/foo.m"]
(* "Applications directory" *)
(* Quit kernel *)
$Path = {$HomeDirectory};
Get["Test`foo`"]
(* "Home directory" *)
Get["Test/foo.m"]
(* "Applications directory" *)
(* Quit kernel *)
$Path = {};
PacletDirectoryAdd[$HomeDirectory];
Get["Test`foo`"]
(* Get::noopen: Cannot open Test`foo`. >> *)
(* $Failed *)
Get["Test/foo.m"]
(* "Home directory" *)
(* Quit kernel *)
$Path = {$HomeDirectory};
PacletDirectoryAdd[$HomeDirectory];
Get["Test`foo`"]
(* "Home directory" *)
Get["Test/foo.m"]
(* "Home directory" *)
So adding a directory to $Path and to paclet directories using PacletDirectoryAdd does the job and files will be always loaded from desired directory.
In Mathematica version 8 directories added with PacletDirectoryAdd are not put on the beginning of paclet search path, but it doesn't matter since in v8 ordinary $Path has precedence.
$Path = {};
Get["Test`foo`"]
(* Get::noopen: Cannot open Test`foo`. >> *)
(* $Failed *)
Get["Test/foo.m"]
(* "Applications directory" *)
(* Quit kernel *)
$Path = {$HomeDirectory};
Get["Test`foo`"]
(* "Home directory" *)
Get["Test/foo.m"]
(* "Home directory" *)
(* Quit kernel *)
$Path = {};
PacletDirectoryAdd[$HomeDirectory];
Get["Test`foo`"]
(* Get::noopen: Cannot open Test`foo`. >> *)
(* $Failed *)
Get["Test/foo.m"]
(* "Applications directory" *)
(* Quit kernel *)
$Path = {$HomeDirectory};
PacletDirectoryAdd[$HomeDirectory];
Get["Test`foo`"]
(* "Home directory" *)
Get["Test/foo.m"]
(* "Home directory" *)
Workaround for Workbench
To add elements of $Path, that are in Workbench workspace, to paclet search path one can create an init.m file with following contents:
If[$VersionNumber >= 9,
PacletManager`PacletDirectoryAdd @ Reverse @ Select[
$Path,
StringMatchQ[#, "/path/to/workspace/*"]&
]
]
Unfortunately I don't have a nice and clean method of executing this file every time it's needed.
A non-ideal solution is to start execution build command of each project with
Get["path/to/our/init.m"]
|
[
"stackoverflow",
"0057510361.txt"
] | Q:
Running a test with Mocha also launches the main program
I'm trying to use Mocha to test a CLI app. The tests are running fine but, when I launch the testing procedure, it also launches the main app:
$ npm run test
> [email protected] test C:\Users\Gaspard\Documents\Code\standardize-js
> mocha "./source/**/*.spec.js"
? Choose your project language or framework (Use arrow keys) //<-- THIS IS THE PROGRAM
> Javascript
Typescript
AngularJS
Main function //<-- THIS IS THE TEST
ask if the configuration is valid
Configuration is not valid, terminating program.
√ should return false if the configuration is not accepted
1 passing (29ms)
I'm kind of new to the testing world and I'm really struggling to understand what I'm doing wrong.
Here is the NPM script used to launch mocha :
"test": "mocha \"./source/**/*.spec.js\""
Here is my testing method:
/* eslint-disable func-names */
const { expect } = require("chai");
const main = require("./index").test;
describe("Main function", function() {
describe("ask if the configuration is valid", function() {
it("should return false if the configuration is not accepted", function() {
const fakeAnswer = false;
expect(main.validateConfiguration(fakeAnswer)).to.equal(false);
});
});
});
And here is my index.js file:
function validateConfiguration(answer) {
if (answer === false) {
console.log(chalk.red("Configuration is not valid, terminating program."));
return false;
}
return true;
}
const run = async () => {
//MAIN FUNCTION
};
run();
// Export functions and variables to be able to test
exports.test = {
validateConfiguration
};
A:
It's not a problem with mocha. It is simply now node.js modules work.
When you do this:
const main = require("./index").test;
Node.js will execute index.js and then check the value of module.exports. If the module (index.js) sets or modifies module.exports then node will export it for use by require(). But note, in order for node to know that the module has exported anything it must execute the javascript file.
Node.js does not have any ability to parse and analyze javascript syntax (that's V8's job). Unlike other languages such as C or Java, modules in node.js are not implemented at the syntax level. Therefore the javascript language does not need to be modified (eg. ES6 modules) for node.js to support modules. Modules are simply implemented as a design pattern.
In your index.js file you call run:
run();
When require() loads index.js it will therefore also cause run() to be called.
Test libraries, not main
The solution to this is to implement your own logic as modules and test that, not test index.js:
mylib.js:
function validateConfiguration(answer) {
if (answer === false) {
console.log(chalk.red("Configuration is not valid, terminating program."));
return false;
}
return true;
}
// Export functions and variables to be able to test
exports.test = { validateConfiguration };
index.js:
const validateConfiguration = require("./mylib").test;
const run = async () => {
//MAIN FUNCTION
};
run();
You can now use your test script as written.
How can you not test code??
The strategy to keep index.js bug free without testing is to remove all logic from it except for the minimum amount of code to wire all your other code up together to run the app. The code should be as simple as "Hello World". That way, the code in main is so small and so simple that you can test it for bugs using your eyeballs.
Any code in index.js that causes a bug should be refactored into its own library so that it can be tested separately. There are a small handful of corner cases, such as loading environment variables or opening port 80 where you can't really separate into a library because they literally are wiring logic. For such cases you just have to be really careful.
|
[
"math.stackexchange",
"0000670570.txt"
] | Q:
solve ratio word problem without algebra
Four gallons of yellow paint plus two gallons of red paint make orange paint. I assume this makes six gallons. So the ratio is 4:2, or 2:1.
Question: how many gallons of yellow paint, and how many gallons or red paint, to make two gallons of orange paint?
2y + r = 2
2y + y = 2
3y = 2
y = 2/3
or
4y + 2r = 6
(4y + 2r)/3 = 2
so I get 4/3 and 2/3.
However, in this section of the text book, I'm not sure that it's "allowed" to do any of that. Is it possible to solve this just with cross-multiplying a ratio?
Their examples setup a ratio with an unknown n, cross multiply and solve for n. I don't see how to solve this word problem with that technique.
A:
Hint
Take the problem in the other way.
You are told that $6$ gallons of orange paint are made mixing $4$ gallons of yellow paint and $2$ gallons of red paint.
Divide these numbers by 6 in order to come back to one gallon of orange paint. Then, one gallon of orange paint is made mixing $\frac{4}{6}=\frac{2}{3}$ gallons of yellow paint and $\frac{2}{6}=\frac{1}{3}$ gallons of red paint.
Now, multiply by $n$ which is the number of gallons of orange paint you want to make.
So, making $n$ gallons of orange paint require mixing $\frac{2n}{3}$ gallons of yellow paint and $\frac{n}{3}$ gallons of red paint.
Now, you want $n=2$; then ....
I am sure that you can take from here.
|
[
"superuser",
"0001236864.txt"
] | Q:
How to use vimium to select text from a page
Background
I'm a religious fanatical devoted believer of vimium. It speeds up my internet usage like nothing else. I'm also (naturally) a heavy user of vim itself.
Question
How can I actually select a certain text in a screen using vimium without using a keyboard? For example let's say I got this email on the page [email protected]. Is there a way i can for example search for that term first of all, then using vimium highlight the rest of the term as if I'm using a cursor?
so a more practical example
mailto@verycomplicatedandlonganduglydomainthatiwontsearachfor.com
so i simply search for mailto, then as that gets highlighted, i can move the cursor to the end of the term or at least highlight one word at a time. Idas?
A:
If you specifically want to search for mailto but then select verycomplicatedandlong... i.e. search one string in order to find the second (unknown) string, which you then want to select.
/ mailto Enter / veryl Enter v ww y
Shortcut explanation.
/ - Enter search mode.
mailto - Literal search string.
Enter - Normal mode.
/ - Now that you know your second search string, enter search mode again.
veryl - Literal search string.
Enter - Enter normal mode (optionally you can use nN to find other instances of the same search string).
v - Enter visual mode.
ww - Select two words (domain and TLD) or use hl to select one character at a time.
y - yank (copy).
|
[
"math.stackexchange",
"0000135810.txt"
] | Q:
Is injection from manifold to tangent manifold well defined?
I would like to know if the injection map $i : M\to TM$, given by $i(x)\mapsto (x,0)$, is a well-defined and canonical application (not dependent on any particular coordinate chart).
A:
The answer is "yes." You should prove it yourself as an exercise.
(Hint: the transition functions are smooth maps $\theta_{UV}:U\cap V\to Gl(n;\mathbb{R})$. In particular, for all $x\in U\cap V$, $\theta_{UV}(x)$ is a linear map. What does this say about how $i$ transforms between coordinate systems?)
|
[
"stackoverflow",
"0037968862.txt"
] | Q:
Import csv file into existing access table using VBA
Hi i have a quick question what is the VBA code that will allow me to import a CSV file into a existing table in Access 2010 with its own field names?
Thanks
A:
this should work
DoCmd.TransferText TransferType:=acLinkDelim, TableName:="tblImport", _
FileName:="C:\MyData.csv", HasFieldNames:=true
|
[
"gis.stackexchange",
"0000199291.txt"
] | Q:
Arcmap layout view zoom data
I have a map in ArcMap that I would like to export as an image, adding also a legend and so on. My issue is that when I go to the Layout View, my data occupy only a small part of the layout view. I would like to zoom in the data, but if I try I do not zoom the data, but the whole layout view.
How can I zoom in in layout view to enlarge the view of my data without zooming the layout view?
A:
Use the highlighted tool for zooming your data inside your Layout.
|
[
"stackoverflow",
"0033130290.txt"
] | Q:
How to stop a ball from bouncing after the position hasnt changed much libgx java
I am writing a physics engine and when the ball hits a surface it bounces up at half the velocity it came down at(velocity.y = -velocity). However when the ball is almost at rest it switches velocities constantly and starts falling through the platform incredibly slow but still will eventually fall through if I let it run long enough, and this is not acceptable. I tried writing some code to stop it but it checks way too fast here is the update method that attempts to check it.
public void update() {
velocity.y += Globals.GRAVITY.y;
if(canFall)
position.y += velocity.y;
position.x += velocity.x;
oldPosition.y = position.y;
oldPosition.x = position.x;
elapsedTime += 1 * Gdx.graphics.getDeltaTime();
if(elapsedTime >= 5){
if(oldPosition.y - 5 <= position.y && oldPosition.y + 5 >= position.y){
elapsedTime = 0;
canFall = false;
}else{
canFall = true;
elapsedTime = 0;
}
}
}
The collision handler knows when it hits the top of the ball which is the only solution I need for this. How do I check when the ball is at rest.
This code attempts to check if the ball hasn't moved in a couple seconds, if it hasn't it sets canFall to false. I need a generic check that will see if the ball should be at a stop. The velocity of the ball when it is falling through the platform you can see from the picture below. The picture shows the ball "at rest" after ten seconds so as you can see the ball is slowly but surely falling through. Every three seconds with this "rest" velocity the y position goes down 1, the velocity changes from positive to negative so the velocity you see in the picture isn't constantly negative. Ignore the elapsed time variable Any help is greatly appreciated!
A:
Why let time have anything to do with it? I'm not saying it coudln't, but should it? So maybe lose the if(elapsedTime ... ) conditional.
Isn't this what you want? If the magnitiude of the vertical difference between the last two positions is negligible (set tolerance accordingly; maybe it's 5), stop bouncing:
if(Math.abs(position.y - oldPosition.y) < tolerance)
{
canBounce = false;
...
}
else
{
canBounce = true;
...
}
or, if nothing else needs to change at the ... above:
canBounce = Math.abs(position.y - oldPosition.y) > tolerance;
Also, don't you need { and } somewhere in the segment below? Maybe not, if ball is bouncing vertically, but it looks like x can change, too, which might make the code above need adjusting. But the way code below is indented makes me think there's supposed to be more to do than just changing position.y:
if(canFall)
position.y += velocity.y;
position.x += velocity.x;
oldPosition.y = position.y;
oldPosition.x = position.x;
Finally, you're addding velocity to position. That seems questionable. Multiply velocity times time? Or is time = 1 always? (Doubt it.)
The problem may be external to this method. Something needs to keep ball's y from becoming less than the y of the top of the dark blue box. This code can't do that without knowing y of top of dark blue box (unless you apply physics formulas?). Maybe include this value in parameter list as topOfDarkBlueBox?
Then add code such as:
if(position.y < topOfDarkBlueBox.y) position.y = topOfDarkBlueBox.y
I'd rather see physics at work, but you might say, "Who'd notice?"
EDIT
You wrote, "The collision handler knows when it hits the top of the ball," but I assume you meant "when the ball hits the top of the dark blue box". Maybe call the collision handler instead of passing new parameter topOfDarkBlueBox?
|
[
"stackoverflow",
"0008258711.txt"
] | Q:
Why does one SpriteBatch.Draw causes frame rate to drop 23 fps?
I am having a major performance problem with a game I'm developing for Windows Phone 7 in C# XNA 4.0.
There's a lot of code going on, like collision, input, animations, physics and so on.
The frame rate has been set to 60fps, but is only running at 32fps. I have tried a lot of things, like disabling though stuff like collision detection, but nothing helped getting higher frame rate. Now randomly I discovered when disabling the drawing of the background, which is just a standard 480x800 sized image (Same as the Windows Phone Resolution), and uses the default method "spriteBatch.Draw(Textures.background, Vector2.Zero, Color.White)" the frame rate goes from 32 to 55 fps. I have also tried changing the texture to a plain white one, but that does not help either, and I have also tried moving the drawing of the background to another place in the code, but nothing changed either. I tried making a new project, and just having the background drawed, but the fps would be at 60 fps then as it should. I'm only having one SpriteBatch.Begin() and SpriteBatch.End(), where all the needed sprites are drawed inside. There's 256 Texture2Ds loaded into the game, which all is loaded at the beginning of the game. The game is a sidescroller, so the background needs to move to the left all the time, but even if I just set it to Vector2.Zero, it would still ruin the fps by -20fps. I hope anyone has a solution to this, or at least an idea of why this is happening.
A:
If you have 256 individual Texture2Ds being used within the same SpriteBatch Begiin/End call it's not surprising that performance isn't optimal unless you are ordering the sprites by texture, which you likely are not for a platformer. All that texture switching within the same batch will cause a decrease in framerate - it's likely that the background image is just the straw that breaks the camels back for your particular game setup.
Have you tried combining those 256 separate images into a smaller number of Texture2Ds (i.e. using spritesheets or a texture atlas)? Here is an older link about how proper sprite sorting can affect performance
|
[
"stackoverflow",
"0030120376.txt"
] | Q:
Select All Checkbox in AngularJS
I have a select all checkbox and list check-box like this.
A checkbox list receive data from
$scope.contacts = [
{"name": "Bambizo", "check": false},
{"name": "Jimmy", "check": false},
{"name": "Tommy", "check": false},
{"name": "Nicky", "check": false}
];
I want when i check a Select all checkbox, it make all checkbox in below list are checked or unchecked. And here my code:
Select All Checkbox:
<input type="checkbox" ng-model="checkAllContact" ng-change="checkAllContact(checkAllContact)">
checkAllContact function:
$scope.checkAllContact = function(){
var allChecked = false;
for(i = 0; i< $scope.contacts.length; i++){
if ($scope.contacts[i].check == true){
allChecked = true;
}else {
allChecked = false;
}
}
if (allChecked = true){
for(i = 0; i< $scope.contacts.length; i++){
$scope.contacts[i].check = false;
}
}else{
for(i = 0; i< $scope.contacts.length; i++){
$scope.contacts[i].check = true;
}
}
}
But when i run and click Select All checkbox. It make an error:
How to solve it or have any other way to do it? Thanks
A:
ng-model="checkAllContact" & method checkAllContact has same name.
checkAllContact scope variable is overriding by checkAllContact.
You need to change your function name will fix the issue.
|
[
"stackoverflow",
"0034247012.txt"
] | Q:
Having problems telling a div to change sizes based on screen size
I am making site in Dreamweaver(with bootstrap.) I am trying to tell the div to be at 75% width when screen is larger then 992px, and 100% width when screen is smaller then 992px. Any ideas what i might be doing wrong?
@media (min-width: 768px) and (max-width: 991px){
}
.bar {
width: 100%;
background-color: #C54345;
}
@media (min-width: 992px) {
}
.bar {
width: 75%;
background-color: #C54345;
}
A:
You have brackets in the wrong places, you've closed the media query braces immediately after you opened them! otherwise the code is fine.
Your code should look like this:
@media (min-width: 768px) and (max-width: 991px){
.bar {
width: 100%;
background-color: #C54345;
}
}
@media (min-width: 992px) {
.bar {
width: 75%;
background-color: #C54345;
}
}
working demo here
|
[
"stackoverflow",
"0022672503.txt"
] | Q:
How to customize different error messages for the same field?
I have the following field that uses it's own regular expression to validate:
<input type="text" name="first-name" class="form-control" id="first-name" placeholder="First Name"
data-parsley-trigger="change" required data-parsley-alpha data-parsley-pattern="^[A-Za-z]*$"/>
The field has multiple validation failure states, and I want each of those states to have a different error message.
For example, if the user enters a space, I want the error message to say "No spaces allowed", but if it has a numeric character, I want the error message to say "No numbers allowed".
I've tried to figure out how to do this by reading the docs, but I'm still confused on how to achieve this.
I'm using Parsley 2.0.0-rc4
A:
Yeah, this is not something easily doable with Parsley. Each validator have an unique error message.
If you want to do so, for UI/UX purposes, you may have two possibilities:
1) You'll need to define some custom validators of yours, and their related messages.
In your example:
create a validator nospaces and its message with 66 priority
create a validator nonumbers and its message with a 65 priority
still use your pattern validator (64 priority) and eventually change its message by something like 'only alphanum allowed'
Add then these 3 validators to your input, and depending on their respective priority they would be fired in the right order to display the right error message you want as described in your question.
Pros: easily reusable
Cons: some work is needed
2) Keep your pattern validator, and bind a custom function to the parsley:field:error event for this input, and do your check to display the right error message you want for this field, and not the default one
Pros: less work maybe, in a single function
Cons: not much reusable
|
[
"math.stackexchange",
"0000473210.txt"
] | Q:
In what cases the "rule" (a^b)^c=a^(bc) doesn't necessarily hold when a<0?
I just saw that someone said that $(a^b)^c = a^{(bc)}$ sometimes doesn't hold if $a<0$. Can someone explain why?
A:
Let $a=-5$, $b=2$, and $c=\frac{1}{2}$. If we use the convention that says $25^{1/2}=5$, we have a problem. And if we use the convention $25^{1/2}=\pm 5$ we have a problem.
|
[
"stackoverflow",
"0036360015.txt"
] | Q:
Configuring Jupyter notebooks for inline Retina Matplotlib figures
I want the effect of
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
%config InlineBackend.figure_format='retina'
at the launch of all my Jupyter notebooks, but I can't figure out what the current approach is for accomplishing this. There are many answers here and elsewhere, but none that I can find seem to be up to date.
How do I accomplish the above in the current versions of Jupyter notebooks (but not IPython generally!): what settings should I apply where is the configuration file I should put them in?
I've tried
c.InteractiveShellApp.matplotlib = "inline"
c.InlineBackend.figure_formats = set(['retina'])
in
~/.jupyter/jupyter_notebook_config.py
but this has no effect.
A:
I have
c.IPKernelApp.matplotlib = 'inline'
c.InlineBackend.figure_format = 'retina'
in my ~/.ipython/profile_default/ipython_kernel_config.py.
|
[
"stackoverflow",
"0018967420.txt"
] | Q:
Replacing a variable value doesn't work as expected in SQL
I want to create the following line into SQL statement:
If account code is XING replace the strategy to GRE?
I have the following which is not working:
/if($_Account Master.Account Code CNS$,/replace($_Account Master.Strategy$,$_Account Master.Strategy$,GRE))
Please let me know the correct method.
A:
If you're talking about replacing value in a variable based on variable go with
IF @AcciountCode = 'XING' @Strategy = 'GRE'
But I have a feeling you need to update respective fields in the table. If so, you need something like
UPDATE [Account Master] SET Strategy = 'GRE' WHERE [Account Code] = 'XING'
|
[
"stackoverflow",
"0057408230.txt"
] | Q:
Equivalent of Informix GLOBAL modifier in PostgreSQL
I need to find equivalent of Informix GLOBAL modifier in Postgresql.
From Informix guide:
The GLOBAL keyword indicates that the variables that follow have a scope of reference that includes all SPL routines that run in a given DB-Access or SQL administration API session.
A:
Postgres set session "configuration parameters" have session scope:
SET only affects the value used by the current session.
Example usage:
set session "myvars.var1" = '3.1415';
...
select current_setting('myvars.var1');
|
[
"stackoverflow",
"0033995735.txt"
] | Q:
lambda non static C#
I am trying to dynamically bind action handlers to radio buttons in UWP with a lambda function:
private void populateMenu(ListBar lb)
{
foreach (var item in lb.Groups)
{
leftMenuStackBar.Children.Add(ListBar.rbGrp(item));
foreach (var LItem in item.Items)
{
var radioButton = ListBar.rb(LItem);
radioButton.Click += (o, i) =>
{
loadFromMenuClick(LItem.Transl, frame);
};
leftMenuStackBar.Children.Add(radioButton);
}
}
the compiler says that the function "loadFromMenuclick" has to be static. In this function I want to use the Frame.Navigate function:
public void loadFromMenuClick(string test, Frame f)
{
Frame.Navigate(typeof(Themes.AbstractView), test);
}
I gave it the "Frame f" object, because I had this error before, but the way that the navigate function works, it is better to use the static Frame.Navigate in stead of f.Navigate.
When I try to use the Frame.Navigate, I get the "An object reference is required for the non-static field, method or property 'Frame.Navigate(Type, object)'" error...
How do I get this to work?
A:
The problem is in your "test" string. At the moment your eventhandler is called, there's no reference to LItem.Transl. Since we don't know what's in that item and how it's linked to a RadioButton, I'll continue my reply with the assumption that the string value of LItem.Transl is also stored in the Tag property of the RadioButton. This is the code for your loop where you attach the eventhandler
var radioButton = ListBar.rb(LItem);
radioButton.Tag = LItem.Transl; // maybe this is in .Text as well?
radioButton.Click += (o, i) => loadFromMenuClick(o);
Your function will be:
private void loadFromMenuClick(object sender)
{
RadioButton radioButton = (RadioButton) sender;
frame.Navigate(typeof (Themes.AbstractView), radioButton.Tag?.ToString());
}
|
[
"stackoverflow",
"0062764665.txt"
] | Q:
setting a vue variable within a JS function for Dropzone
I have a page (in Laravel) where I"m using Vue for the overall function of the page and the ultimate axios post for form submission, but I've run into a tricky situation.
I have a standard dropzone (using the plain JS dropzone code) where I'm dropping images for upload. When I drop the image, I have the console logging the file name, which is working perfectly fine. The issue is that I need to take that filename and push it into a variable, object in my vue code.
The dropzone code is like so:
Dropzone.options.imageWithZones = {
init: function() {
this.on("addedfile",
function(file) {
console.log(file.name);
});
}
};
But my vue code is here, and I need to set ImageZoneName with the file name from the previous function
new Vue({
components: {
Multiselect: window.VueMultiselect.default
},
el: "#commonDiv",
data() {
return{
ImageZoneName: [],
}
},
........
What is the best way to simply take the file name (when a file is added to dropzone) and set the vue ImageZoneName object to ahve a value of that file name?
A:
Two ways:
Move the dropzone event configuration and put it inside of the Vue mounted lifecycle method. Then you can easily access the Vue instance to set the variables.
new Vue({
el: "#app",
data: {
imageZoneNames: [],
},
mounted() {
const vm = this;
Dropzone.options.imageWithZones = {
init: function() {
this.on("addedfile",
function(file) {
vm.imageZoneNames.push(file.name);
}
);
}
};
} // end mounted
})
<link href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.7.1/dropzone.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.7.1/dropzone.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
Files:
<ul>
<li v-for="fileName in imageZoneNames" :key="fileName">
{{ fileName }}
</li>
</ul>
<form action="/file-upload"
class="dropzone"
id="imageWithZones"></form>
</div>
Assign the instance to a variable and access the data through that
const vm = new Vue({
el: "#app",
data: {
imageZoneNames: [],
},
})
Dropzone.options.imageWithZones = {
init: function() {
this.on("addedfile",
function(file) {
vm.imageZoneNames.push(file.name)
}
);
}
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.7.1/dropzone.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.7.1/dropzone.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
Files:
<ul>
<li v-for="fileName in imageZoneNames" :key="fileName">
{{ fileName }}
</li>
</ul>
<form action="/file-upload"
class="dropzone"
id="imageWithZones"></form>
</div>
|
[
"stackoverflow",
"0041661687.txt"
] | Q:
Node.js: how to poll a web resource for change?
Using node.js how do I poll a web resource (eg. example.org/data.json) for change in a asynchronous way so I can notify the clients whenever a certain resource has changed ?
I'm looking for a lib or at least a somewhat more elegant way to archive this rather than downloading the file myself, calculating and comparing the hashes every few seconds.
Everything I found so far is using inotify or fswatch under the hood so it cant be used for non local files.
A:
You could try the Last-Modified Header field, if this is supported by the web resource.
|
[
"stackoverflow",
"0054847624.txt"
] | Q:
TypeError: Cannot read property ‘getState’ of undefined
I want to try small redux example so I installed redux but I got this error
TypeError: Cannot read property ‘getState’ of undefined
new Provider
webpack-internal:///./node_modules/react-redux/es/components/Provider.js:24:25
Code:
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import './index.css';
const App = () => (<div>Hi </div>);
ReactDOM.render(<Provider><App /></Provider>, document.getElementById('root'));
What is wrong ?
A:
If we look inside react-redux <Provider />
<Provider /> expects to be provided a store prop:
this.state = {
storeState: store.getState(),
^^here
store
}
Hence the error.
You can create one, though, using a reducer, should be something similar to this:
import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { createStore } from 'redux'
import reducer from './reducer'
import App from './components/App'
const store = createStore(reducer)
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
|
[
"stackoverflow",
"0008446047.txt"
] | Q:
Accessing VMware's Bios
On a Mac in VMware Fusion when the vm is starting and the loading bar is displayed, how can you access the the boot order as if it were a stand alone windows machine?
I've tried "f8" "delete" with no luck.
A:
Don't know VMware on Mac, but on Windows, I'd use in Menu VM->Power->Power on to BIOS.
While startup of the VM, BIOS setup is launched with F2, boot order menu with F12.
|
[
"stackoverflow",
"0063058310.txt"
] | Q:
How to divide two columns in R for bigdata?
I had df contains 2 columns with ratio values, I'd like to divide these columns and put the resultant value into a new column. Some suggestions please.
2/120 = 0.01666667, 119/9238 = 0.01288158, A/B = ?
Example
A B new
2/120 119/9238 ?
1/120 47/9238
6/120 422/9238
1/120 50/9238
2/120 127/9238
1/120 52/9238
1/120 52/9238
3/120 205/9238
1/120 53/9238
1/120 53/9238
1/120 53/9238
A:
You can try this:
#Data
mdf <- structure(list(A = c("2/120", "1/120", "6/120", "1/120", "2/120",
"1/120", "1/120", "3/120", "1/120", "1/120", "1/120"), B = c("119/9238",
"47/9238", "422/9238", "50/9238", "127/9238", "52/9238", "52/9238",
"205/9238", "53/9238", "53/9238", "53/9238")), class = "data.frame", row.names = c(NA,
-11L))
#Code
mdf$Col1 <- apply(mdf[,'A',drop=F],1,function(x) eval(parse(text=x)))
mdf$Col2 <- apply(mdf[,'B',drop=F],1,function(x) eval(parse(text=x)))
mdf$Ratio <- mdf$Col1/mdf$Col2
A B Col1 Col2 Ratio
1 2/120 119/9238 0.016666667 0.012881576 1.293838
2 1/120 47/9238 0.008333333 0.005087681 1.637943
3 6/120 422/9238 0.050000000 0.045680883 1.094550
4 1/120 50/9238 0.008333333 0.005412427 1.539667
5 2/120 127/9238 0.016666667 0.013747564 1.212336
6 1/120 52/9238 0.008333333 0.005628924 1.480449
7 1/120 52/9238 0.008333333 0.005628924 1.480449
8 3/120 205/9238 0.025000000 0.022190950 1.126585
9 1/120 53/9238 0.008333333 0.005737173 1.452516
10 1/120 53/9238 0.008333333 0.005737173 1.452516
11 1/120 53/9238 0.008333333 0.005737173 1.452516
|
[
"stackoverflow",
"0008586088.txt"
] | Q:
Rotate rectangle around its center
I need to rotate a rectangle around it's center-point and display it in the center of a QWidget. Can you complete this specific code? If possible, could you also dumb-down the explaination or provide a link to the simplest explaination?
Please note: I have read the Qt documentation, compiled examples/demos that deal with rotation and I STILL cannot understand it!
void Canvas::paintEvent(QPaintEvent *event)
{
QPainter paint(this);
paint.setBrush(Qt::transparent);
paint.setPen(Qt::black);
paint.drawLine(this->width()/2, 0, this->width()/2, this->height());
paint.drawLine(0, this->height()/2, this->width(), this->height()/2);
paint.setBrush(Qt::white);
paint.setPen(Qt::blue);
// Draw a 13x17 rectangle rotated to 45 degrees around its center-point
// in the center of the canvas.
paint.drawRect(QRect(0,0, 13, 17));
}
A:
void paintEvent(QPaintEvent* event){
QPainter painter(this);
// xc and yc are the center of the widget's rect.
qreal xc = width() * 0.5;
qreal yc = height() * 0.5;
painter.setPen(Qt::black);
// draw the cross lines.
painter.drawLine(xc, rect().top(), xc, rect().bottom());
painter.drawLine(rect().left(), yc, rect().right(), yc);
painter.setBrush(Qt::white);
painter.setPen(Qt::blue);
// Draw a 13x17 rectangle rotated to 45 degrees around its center-point
// in the center of the canvas.
// translates the coordinate system by xc and yc
painter.translate(xc, yc);
// then rotate the coordinate system by 45 degrees
painter.rotate(45);
// we need to move the rectangle that we draw by rx and ry so it's in the center.
qreal rx = -(13 * 0.5);
qreal ry = -(17 * 0.5);
painter.drawRect(QRect(rx, ry, 13, 17));
}
You are in the painter's coordinate system. When you call drawRect(x, y, 13, 17), it's upper left corner is at (x,y). If you want (x, y) to be the center of your rectangle, then you need to move the rectangle by half, hence rx and ry.
You can call resetTransform() to reset the transformations that were made by translate() and rotate().
A:
Simple:
void rotate(QPainter* p, const QRectF& r, qreal angle, bool clock_wise) {
p->translate(r.center());
p->rotate(clock_wise ? angle : -angle);
p->translate(-r.center());
}
|
[
"stackoverflow",
"0048483986.txt"
] | Q:
How to reconfigure custom post type after it has been defined?
I'm using a WordPress theme that adds a custom post type.
This is somewhat useful, but would be even more useful if I could adjust some of the CTP's configuration.
In particular, I need to adjust the capabilities defined on the CTP. I already have an array of the capability values needed, e.g.,
$caps = array(
'publish_posts' => 'activate_plugins',
'read_post' => 'read',
... etc
);
Is there a generic way to reconfigure a CTP with these values after it has been defined, i.e, via functions.php?
Or would I need to overwrite whatever theme code is creating the CTP, perhaps using a child theme?
A:
Yes you can reconfigure the already defined CPT's properties. By using following filter: register_post_type_args
Src: https://developer.wordpress.org/reference/hooks/register_post_type_args/
Filters the arguments for registering a post type.
For example you can change slug like this:
add_filter('register_post_type_args', 'movies_to_films', 10, 2);
function movies_to_films($args, $post_type){
if ($post_type == 'movies'){
$args['rewrite']['slug'] = 'films';
}
return $args;
}
You can edit capabilities similarly see already answered question which solved exact problem:
https://wordpress.stackexchange.com/a/215697/30852
|
[
"stackoverflow",
"0059799643.txt"
] | Q:
How do I show one kml layer when the page is loaded?
I have a page with a google maps that shows several kml files that can be seen when you click on the checkboxes in the legend.
How can I configure the map so that when the page is loaded I see only layer2 as though it had already been clicked?
The source code is:
<script type="text/javascript">
var map;
var layers = [];
function initialize() {
var myLatLng = new google.maps.LatLng(37.18186,-3.58843);
var myOptions = {
zoom: 15,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
streetViewControl: false
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var legend = document.getElementById('legend');
map.controls[google.maps.ControlPosition.TOP_RIGHT].push
(document.getElementById('legend'));
var noPoi = [
{
featureType: "poi",
stylers: [
{ visibility: "off" }
]
}
];
map.setOptions({styles: noPoi});
layers [0] = new google.maps.KmlLayer('https://granadainfo.com/googlemaps/kml/L33-2018.kml',
{preserveViewport: true, suppressInfoWindows: false});
layers [1] = new google.maps.KmlLayer('https://granadainfo.com/googlemaps/kml/C31-2018.kml',
{preserveViewport: true, suppressInfoWindows: false});
layers [2] = new google.maps.KmlLayer('https://granadainfo.com/googlemaps/kml/C34-2018.kml',
{preserveViewport: true, suppressInfoWindows: false});
layers [3] = new google.maps.KmlLayer('https://granadainfo.com/googlemaps/kml/C30-2018.kml',
{preserveViewport: true, suppressInfoWindows: false});
for (var i = 0; i < layers.length; i++) {
layers[i].setMap(null);
}
}
function toggleLayer(i) {
if (layers[i].getMap() === null) {
layers[i].setMap(map);
}
else {
layers[i].setMap(null);
}
}
</script>
and the html code is:
<div id="map_canvas"></div>
<div id="legend">
<p>
<input type="checkbox" id="layer0" onClick="toggleLayer(0)"/> Bus 33<br />
<input type="checkbox" id="layer1" onClick="toggleLayer(1)"/> Bus C31<br />
<input type="checkbox" id="layer2" onClick="toggleLayer(2)"/> Bus C34<br />
<input type="checkbox" id="layer3" onClick="toggleLayer(3)"/> Bus C30<br />
</div>
A:
You need to do two things:
set the default checkbox to "checked".
<input type="checkbox" id="layer2" onClick="toggleLayer(2)" checked="checked"/> Bus C34<br />
call the toggleLayer function for the layer you want displayed.
Bus C34
toggleLayer(2);
proof of concept fiddle
code snippet:
var map;
var layers = [];
function initialize() {
var myLatLng = new google.maps.LatLng(37.18186, -3.58843);
var myOptions = {
zoom: 15,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
streetViewControl: false
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var legend = document.getElementById('legend');
map.controls[google.maps.ControlPosition.TOP_RIGHT].push(document.getElementById('legend'));
var noPoi = [{
featureType: "poi",
stylers: [{
visibility: "off"
}]
}];
map.setOptions({
styles: noPoi
});
layers[0] = new google.maps.KmlLayer('https://granadainfo.com/googlemaps/kml/L33-2018.kml', {
preserveViewport: true,
suppressInfoWindows: false
});
layers[1] = new google.maps.KmlLayer('https://granadainfo.com/googlemaps/kml/C31-2018.kml', {
preserveViewport: true,
suppressInfoWindows: false
});
layers[2] = new google.maps.KmlLayer('https://granadainfo.com/googlemaps/kml/C34-2018.kml', {
preserveViewport: true,
suppressInfoWindows: false
});
layers[3] = new google.maps.KmlLayer('https://granadainfo.com/googlemaps/kml/C30-2018.kml', {
preserveViewport: true,
suppressInfoWindows: false
});
for (var i = 0; i < layers.length; i++) {
layers[i].setMap(null);
}
toggleLayer(2);
google.maps.event.addListener(layers[2], 'defaultviewport_changed', function() {
map.fitBounds(layers[2].getDefaultViewport())
});
}
function toggleLayer(i) {
if (layers[i].getMap() === null) {
layers[i].setMap(map);
} else {
layers[i].setMap(null);
}
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map_canvas {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map_canvas"></div>
<div id="legend">
<p>
<input type="checkbox" id="layer0" onClick="toggleLayer(0)" /> Bus 33<br />
<input type="checkbox" id="layer1" onClick="toggleLayer(1)" /> Bus C31<br />
<input type="checkbox" id="layer2" onClick="toggleLayer(2)" checked="checked" /> Bus C34<br />
<input type="checkbox" id="layer3" onClick="toggleLayer(3)" /> Bus C30<br />
</p>
</div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initialize">
</script>
|
[
"stackoverflow",
"0021637748.txt"
] | Q:
load R.drawable in function android
I have a function
public void creacion_layout_items(R.drawable imagen_principal){
LinearLayout _33_1_layout=(LinearLayout)findViewById(R.id.layout_principal);
ImageView imagen=new ImageView(this);
LinearLayout.LayoutParams imagen_Params = new LinearLayout.LayoutParams(12,12);
imagen.setLayoutParams(imagen_Params);
imagen.setBackgroundResource(imagen_principal);
_33_1_layout.addView(imagen);
}
and I want to call the function
creacion_layout_items(R.drawable.all);
but does not work
A:
R.drawable.something is of int type. R.drawable is not type at all.
So use
public void creacion_layout_items(int yourResDrawableId){
...
imagen.setBackgroundResource(yourResDrawableId);
...
}
|
[
"stackoverflow",
"0062611352.txt"
] | Q:
sql does not order by order by with multiple variables and inner join in MYSQL
I have the following statement in sql, to show data from my mysql database.
SELECT o.*
, u.picture
, u.socialid
FROM operaciones o
JOIN users u
ON o.id_usuario = u.socialid
AND o.provincia = 'Cordoba'
AND o.divisa = 'Dolares'
AND o.fecha_op IN('27-06-20','26-06-20','25-06-20')
WHERE o.tipo = 'compra'
ORDER
BY o.cotizacion DESC
, o.fecha DESC
The problem is that it returns the messy data, for example, the "cotizacion" part is from highest to lowest and it returns everything mixed, I already saw several questions but I could not solve it.
A:
Your current results make it look like cotizacion is stored as a string, not as a number. String wise, '3' is greater than '22' (because '3' is greater than the first character of '22', that is '2'). You should fix your data model, and store numbers as numbers.
In the meantime, you can force numeric conversion like so:
ORDER BY 0 + o.cotizacion DESC, o.fecha DESC
|
[
"stackoverflow",
"0021344674.txt"
] | Q:
Can you safely return null from a custom ValidationRule, to signify no validation performed?
I am implementing a custom ValidationRule for WPF DataBinding. To do this, I just inherit from ValidationRule and implement one or more of a few abstract or virtual methods. This is the method I am implementing:
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo, System.Windows.Data.BindingExpressionBase owner)
The ValidationResult object I am returning must either have true or false for the IsValid property. This logically seems to me to be missing the third option Unknown or Undetermined. In some cases, a validator may not apply.
So what should I return in these cases? Can I safely return null?
A:
NO!! A validator should not return null from any overloads of the Validate method, and before you ask it should not throw exceptions either. In either of these cases your application will encounter an unhandled exception in framework code, and probably crash.
So just accept the less than perfect semantics, and return ValidationResult.ValidResult if you want your custom validator to essentially be a no-op.
Source: tested on .NET 4.5
|
[
"ru.stackoverflow",
"0001064422.txt"
] | Q:
Как дождаться окончания установки состояния с помощью хука useState
Всем привет! Столкнулся с тем, что после установки состояния с помощью хука. Обновление происходит не сразу. Как дождаться окончания установки состояния при использовании хука useState?
const AvailableLanguages = ({ onChange }) => {
const [activeLanguages, setActiveLanguages] = useState(["RU"])
const [addDialogActive, setAddDialogActive] = useState(false)
const addLanguage = (language) => {
const currentLanguages = activeLanguages
if (!currentLanguages.includes(language)) {
currentLanguages.push(language)
setActiveLanguages(currentLanguages)
// TODO: onChange(activeLanguages)
}
}
const removeLanguage = (language) => {
const filteredLangs = activeLanguages.filter(lang => lang != language)
setActiveLanguages(filteredLangs)
// TODO: onChange(activeLanguages)
}
...
}
A:
Сделал так) Работает. Надеюсь, что правильно)
const AvailableLanguages = ({ onChange }) => {
const [activeLanguages, setActiveLanguages] = useState(["RU"])
const [addDialogActive, setAddDialogActive] = useState(false)
useEffect(() => {
onChange(activeLanguages)
}, [activeLanguages])
const addLanguage = (language) => {
setActiveLanguages(currentLanguages => {
let langs = [...currentLanguages]
if (!currentLanguages.includes(language)) {
langs.push(language)
}
return langs
})
}
const removeLanguage = (language) => {
setActiveLanguages(currentLanguages => {
return currentLanguages.filter(lang => lang != language)
})
}
...
}
|
[
"stackoverflow",
"0001260969.txt"
] | Q:
Different user permisions for different sites on sharepoint
alt text http://img21.imageshack.us/img21/3262/snapshotosz.png
I want to add a new tab or site in sharepoint as shown for the above, but i want to allow some users to access one of them and not the other. when i remove a user it is removed from both of them or put for all.
Also how can I edit those of the one which is already done?
A:
You need to set the permissions of the subsite to not inherit from the parent. This is an option when you create the site. To stop inheriting permissions on an existing site, go to:
Site Actions -> Site Settings -> Advanced Permissions -> Actions -> Edit Permissions
Then you can set who has access to the subsite. A user with no permissions in the subsite will not see the tab.
It's all explained here.
|
[
"stackoverflow",
"0010491935.txt"
] | Q:
OHLCDataset: Get item from/having the date
I have a JFreechart, showing stocks data, the type of dataset i use to plot it is an OHLCDataset.
I can get the actual X value from the point where the user click on the plot (i mean, i get the real date corresponding to that point, not just the coordinate on the window).
Next step i need to make is get the data from the OHLCDataset corresponding to that date, to be able to get the Open.High,Close and Low values in that date, but i just can find ways to get the OHLCDataset date corresponding to an item (an integer wich indicates the ordinal), not even one way to obtain that item having the date.
¿Any ideas of how to get the item having the date?
Thanks.
A:
The approach suggested is tedious and error-prone. Instead, add a ChartMouseListener, as shown here. You can invoke getDataset() on any XYItemEntity you encounter.
|
[
"stackoverflow",
"0017599923.txt"
] | Q:
Trying to watch outer scope from inner scope in directive not working
I'm having some difficulty watching a scope variable from within a directive.
I have a controller with a scope variable called val:
$scope.val = { name: "hello" };
I have a directive which uses this value. So in the view for this controller I have something along the lines of:
<custom-component custom-attribute="val"></custom-component>
I've built a directive which has a scope
var myDir = function() {
return {
restrict: 'E',
scope: {
customAttribute: '=customAttribute'
},
link: function(scope, elem, attr) {
scope.$watch('customAttribute', function(val){ console.log(val); }
},
replace: true,
template:'<div class="hello"></div>'
};
}
The watch function fires of fine when I first run the app. Now I put a timeout in my controller and do something like:
setTimeout(function(){
console.log("Changed chart type name");
$scope.customAttribute.name="baz";
},5000);
This does not cause the watch function to trigger! I'm not sure what the issue is. I've also tried putting the timeout within the directives link function in case there were some object copying issues (below scope.$watch):
link: function(scope, elem, attr) {
scope.$watch('customAttribute', function(val){ console.log(val); }
setTimeout(function(){
console.log("Changed chart type name");
scope.customAttribute.name="baz";
},5000);
},
This still doesn't work!
EDIT:
So I've found that if in my controller I call $scope.$digest() after updating the variable everything works. Why do I need to call this function manually?
A:
Since you are using setTimeout which is called outside of angular context so you have to call scope.$apply , there are two ways to solve your problem
1) Use scope.$apply()
link: function(scope, elem, attr) {
scope.$watch('customAttribute', function(val){ console.log(val); }
setTimeout(function(){
console.log("Changed chart type name");
scope.customAttribute.name="baz";
scope.$apply();
},5000);
},
2) Wrap the function in angular $timeout
link: function(scope, elem, attr) {
scope.$watch('customAttribute', function(val){ console.log(val); }
$timeout(function(){
console.log("Changed chart type name");
scope.customAttribute.name="baz";
},5000);
},
A:
Instead of setTimeout, use $timeout, which is the AngularJS equivalent. It uses $scope.$apply internally. With setTimeout, things happen outside the "Angular World", and your application is not aware of them.
Don't forget to inject $timeout into your controller:
.controller('MyCtrl', ['$timeout', function($timeout) {
...
}]);
|
[
"stackoverflow",
"0052357361.txt"
] | Q:
Hashing functions checks for argon2id even when driver set to bcrypt
I am upgrading an older project to Laravel 5.7. User passwords were hashed with bcrypt previously. On the new setup hashing driver is set to bcrypt in the config file but still getting the following error.
local.ERROR: This password does not use the Argon2id algorithm. {"exception":"[object] (RuntimeException(code: 0): This password does not use the Argon2id algorithm. at vendor/laravel/framework/src/Illuminate/Hashing/Argon2IdHasher.php:20
Auth::attempt() returns true but login is not persisted on redirect.
A:
I've read a few posts about people having issues with this. Perhaps this github issue will help you out, they're having similar problems: https://github.com/laravel/framework/issues/25586
Edit: This may help also, https://github.com/laravel/framework/issues/24162
|
[
"stackoverflow",
"0005512471.txt"
] | Q:
test if a form input is a 1 or 2 digit integer with jquery and php
I have a form that has five fields that are all set to maxlength="2".
Basically, i want the only values that can be entered to either be a one or two digit integer, because calculations are performed on these fields before the values are stored in the database.
Is there any jquery that will not let a user even enter a value that isnt an integer?
Also what would be the best way to validate this with both jquery and php? I have found some ways of doing it, but i need to make sure its secure, avoiding characters, -2, .1 etc
SOLVED
For the php part i used
if(!ctype_digit($_POST['value']))
which only allows for positive whole numbers
And for javascript
$('.inputQuantity').keyup(function(){
this.value = this.value.replace(/[^0-9\.]/g,'');
});
which deletes any entry made into the input field that is not a number.
Both above work, although i think some people prefer to use focusout(function() rather than keyup(function() ;)
A:
SOLVED
For the php part i used
if(!ctype_digit($_POST['value']))
which only allows for positive whole numbers
And for javascript
$('.inputQuantity').keyup(function(){
this.value = this.value.replace(/[^0-9\.]/g,'');
});
which deletes any entry made into the input field that is not a number.
Both above work, although i think some people prefer to use focusout(function() rather than keyup(function() ;)
|
[
"stackoverflow",
"0021957005.txt"
] | Q:
using intent with button event
I am new to android development. I have several posts and tutorials but I am not quite understanding using/setting up Intents.
I created an app to get a better understanding but I cant get the code to work.
My thought process is as follows
i setup 2 activities with fragments.
on my main fragment I added a button, where once clicked it goes to another activity page
Question: when I use intent do I call the fragments or the activity?
my code:
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
public class PlanMeMainFragment extends Fragment {
private Button mNewButton, mExistingButton;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.planme_main_fragment, parent, false);
return v;
mNewButton = (Button)v.findViewById(R.id.new_event_button);
mNewButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent myIntent = new Intent(PlanMeMainFragment.this, NewEventSetupFragment.class);
startActivity(myIntent);
}
});
}
}
i have my manifest set up as
<activity
android:name=".PlanMeMainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".NewEventSetupActivity">
</activity>
A:
You can't invoke a Activity from the Fragment. As calling class you need to set the Activity that hosts the Fragment. You get that with getActivity().
If you want to call the 2nd Activity from the 1st Fragment (that lies on your first Activity) you go like that:
Intent myIntent = new Intent(getActivity(), SecondActivity.class);
getActivity().startActivity(myIntent);
In that Activity you just invoked you can instanciate the Fragment just as you did with your first one. But are you sure you need a second Activity? You could just host both Fragments on your Activity and replace the first with the second one (just FYI if you didn't know).
|
[
"linguistics.stackexchange",
"0000007041.txt"
] | Q:
anomaly in a Latin hexameter
I read in Ovid, Metamorphoses , 1.502-503 :
fugit ōcior aurā
illa leuī nequ(e) ad haec reuocantis uerba resistit.
My (rough) translation :
But she flees, quicker than the soft breeze,
and resists these words calling her back again.
I'm stuck with the scansion of the verse 503 :
illa leuī nequ(e) ad haec reuocantis uerba resistit.
1 -2- 3 4 5 -6- 7 8 9 -10- 11 12
With the "ad" word this verse seems to have 13 syllables, not 12. There at least one person thinking that this "ad" should be elided but this correction seems very curious.
I don't have any critic edition of the Metamorphoses. Is the text questionable ?
A:
The verse is correct. ne-qu(e)a-d(h)aec is three sylables: short + short + long.
|
[
"stackoverflow",
"0028560735.txt"
] | Q:
Title for mapreduce file output
I am developing an MapReduce based app and I want to add to my output file (txt file) title from inside the process.
this is my current out put:
Streptococcus_suis2 41581
Streptococcus_suis3 41581
this is how I want the file look like:
Sample1
Streptococcus_suis2 41581
Streptococcus_suis3 41581
Anybody has an idea?
A:
I'm assuming you are using the TextOutputFormat and writing your data with a call to context.write(key,value);
from your reducer of type
MyReducer extends Reducer<InKey,InValue,Text,LongWritable>
You may override the setup method of your reducer:
@Override
protected void setup(Context context) {
context.write(new Text("Sample1"),null);
}
and call context.write with null as second parameter to add the header line to your output files.
|
[
"stackoverflow",
"0014584623.txt"
] | Q:
Toggle with text in jQuery?
I have tried to make an anchor change it's text when you click on it. But instead of toggling it just goes invisible and doesn't work.
here's the code:
$('a#button').click(function(e) {
e.preventDefault();
findListingBoxList.slideToggle('200');
$(this).toggle(function() {
$(this).html('Hide All');
}, function() {
$(this).html('Show All');
});
});
HTML:
<a id="button" href="#"></a>
<div id="ListingBox">
<ul id="furniture">
<li>Beds</li>
<li>Chairs</li>
<li>Tables</li>
<li>Desks</li>
<li>Shelves</li>
<li>Cabinet</li>
<li>Miscellaneous</li>
</ul>
<ul id="games">
<li>PC</li>
<li>Mac</li>
<li>XBOX 360</li>
<li>Playstation 3</li>
<li>Nintendo Wii</li>
<li>PS Vita</li>
<li>Playstation 2</li>
<li>Playstation</li>
<li>Super Nintendo</li>
<li>Nintendo DS</li>
<li>Miscellaneous</li>
</ul>
</div>
I have already tried it with .html and .text.
A:
toggle event method is deprecated, you can use text method callback function, note that by 200ms slideToggle is executed too fast.
$('#button').click(function(e) {
e.preventDefault();
findListingBoxList.slideToggle(600);
$(this).text(function(i, currentText){
return currentText === 'Show All' ? 'Hide All' : 'Show All';
})
});
A:
.toggle() event is deprecated since 1.8
HTML :
<a href="#" id="button" class="hide_all">Hide ALL</a>
<div id="find">
<p>Here is some content</p>
<p>Here is some content</p>
</div>
JS :
var findListingBoxList = $('#find');
var labels = {
hide: 'Hide ALL',
show: 'Show ALL'
};
$('#button').click(function(e){
e.preventDefault();
if($(this).text() == labels.show) {
$(this).text(labels.hide);
findListingBoxList.slideDown();
} else {
$(this).text(labels.show);
findListingBoxList.slideUp();
}
})
Using slideDown/slideUp permit the link to work regardless its starting status (you could load the page with a Show ALL or a Hide ALL state.)
Look at this for a demo : http://codepen.io/ByScripts/pen/mbekK
|
[
"travel.stackexchange",
"0000103524.txt"
] | Q:
Where was this stock photo taken?
It's one of the background choices for Linux Mint. I tried doing a reverse Google image search and found this website, but it doesn't say where it was taken.
A:
You can eventually follow the link you sent out to the photographer's Flickr website:
https://www.flickr.com/photos/shontzphotography/15169016487/in/album-72157645951788784/
In the discussion area, it looks to be from an area in Te Mata Peak in Havelock North, New Zealand.
A:
Here's a similar view from Google Earth (you can see the exact coordinates in the lower right corner). It looks like the photographer used a wide angle lens and the sunrise really brings out the contours of the valley floor.
|
[
"stackoverflow",
"0029128575.txt"
] | Q:
How to save data in cassandra conditionally only if properties did not change
We have data model of article with lot of properties. Here is our table model:
CREATE TABLE articles (
organization_id bigint,
gtin text,
barcodes text,
code text,
brand text,
season text,
name text,
option text,
style text,
color text,
sizes text,
supplier text,
category text,
prices text,
last_updated timeuuid,
content_hash uuid,
markdown boolean,
PRIMARY KEY (organization_id, gtin)
) WITH COMMENT='Articles';
Where gtin uniquely identifies article and we save all articles of organization in one row. We have constraint to update each article only if something has changed. This is important since if article is changed, we update last_updated field and external devices know which articles to synchronizes since they have information when they synchronized last time.
We added one more table for that:
CREATE TABLE articles_by_last_updated (
organization_id bigint,
gtin text,
barcodes text,
code text,
brand text,
season text,
name text,
option text,
style text,
color text,
sizes text,
supplier text,
category text,
prices text,
last_updated timeuuid,
content_hash uuid,
markdown boolean,
PRIMARY KEY (organization_id, last_updated)
) WITH CLUSTERING ORDER BY (last_updated ASC) AND COMMENT='Articles by last updated field';
So we can easily return all articles updated after certain point in time. This table must be cleared from duplicates per gtin since we import articles each day and sync is done from mobile devices so we want to keep dataset small (in theory we could save everything in that table, and overwrite with latest info but that created large datasets between syncs so we started deleting from that table, and to delete we needed to know last_updated from first table)
Problems we are facing right now are:
In order to check if article fields are updated we need to do read before write (we partially solved that with content_hash field which is hash over all fields so we read and compare hash of incoming article with value in DB)
We are deleting and inserting in second table since we need unique gtins there (need only latest change to send to devices, not duplicate articles) which produces awful lot of tombstones
We have feature to add to search by many different combinations of fields
Questions:
Is cassandra good choice for this kind of data or we should move it to some other storage (or even have elasticsearch and cassandra in combination where we can index changes after time and cassandra can hold only master data per gtin)?
Can data be modeled better for our use case to avoid read before write or deletes in second table?
Update
Just to clarify use case: other devices are syncing with pagination (sending last_sync_date and skip and count) so we need table with all article information, sorted by last_updated without duplicates and searchable by last_updated
A:
If you are using Cassandra 2.1.1 and later, then you can use the "not equal" comparison in the IF part of the UPDATE statement (see CASSANDRA-6839 JIRA issue) to make sure you update data only if anything has changed. Your statement would look something like this:
UPDATE articles
SET
barcodes = <barcodes>,
... = <...>,
last_updated = <last_updated>
WHERE
organization_id = <organization_id>
AND gtin = <gtin>
IF content_hash != <content_hash>;
For your second table, you don't need to duplicate entire data from the first table as you can do the following:
create your table like this:
CREATE TABLE articles_by_last_updated (
organization_id bigint,
last_updated timeuuid,
gtin text,
PRIMARY KEY (organization_id, last_updated)
) WITH CLUSTERING ORDER BY (last_updated ASC) AND COMMENT='Articles by last updated field';
Once you've updated the first table, you can read the last_updated value for that gtin again and if it is equal or greater than the last_updated value you passed in, then you know that the update was successful (by your or another process), so you can now go ahead and insert that retrieved last_updated value into the second table. You don't need to delete the records for this update. I assume you can create distinct updated gtin list on the application side, if you do polling (using a range query) on a regular basis, which I assume pulls a reasonable amount of data. You can TTL these new records after a few poll cycles to remove a necessity to do manual deletes for example. Then, after you found the gtins affected, then you do a second query where you pull all of the data from the first table. You can then run a second sanity check on the updated dates to avoid sending anything that is supposed to be sent on the next update (if it is necessary of course).
HTH.
|
[
"stackoverflow",
"0063439248.txt"
] | Q:
Setting String Values of a Pandas Column with Indices
I am trying to generate a new column in my dataframe where a string is assigned for different index values. I'm not exactly skilled enough to do it with a loop, so I tried subsetting and indexing to see if I could make my life easier.
df['event_type'] = []
A = df[df['flags'].isin(['A'])].index
B= df[df['flags'].isin(['B'])].index
C = df[df['flags'].isin(['B'])].index
df.loc[A, 'event_type'] = 'Condition One'
df.loc[B, 'event_type'] = 'Condition Two'
df.loc[C, 'event_type'] = 'Condition Three'
I've gotten the length of values does not match length of index and Index.name must be a hashable type errors several times now. I just want to assign these strings to these indices in the new columns, all the other values in the column can be Nan.
A:
You can use Series.map,
df['event_type'] = df.flags.fillna('').map(
{"A": "Condition One", "B": "Condition Two", "C": "Condition Three"}
)
|
[
"es.stackoverflow",
"0000024837.txt"
] | Q:
Imagen venctorizada SVG no se muestra en IE, Chrome
estoy intentando insertar una imagen vectorizada en formato SVG, pero solo la logro ver en mozilla firefox, para IE y chrome no aparece. He buscado un poco de documentación sobre svg en navegadors, en muchos veo ejemplos dónde se dibujan formas colocando coordenadas, colores y el navegador renderiza en imagen svg, pero en mi casa tengo en archivo ese imagen svg.
Código :
<div class= "spacioLogos">
<p:graphicImage value="./images/logo_mexico.svg" width="120" height="55" styleClass="logoizquierda"/>
<p:graphicImage value="./images/logo_mexico.svg" width="120" height="55" styleClass="img"/>
</div>
Lo mismo se ve si coloco el html img:
<img src="./images/logo_mexico.svg" width="120" height="55" class="responsive" />
Muestra de como se renderiza en navegadores:
mozila firefox:
google chrome:
internet explorer edge:
A:
Quedo solucionado, modifiqué el web.xml de mi aplicación agregando el type-mime de imagenes svg, con esto ya se muestran en Mozilla firefox, IE, y Chrome.
<mime-mapping>
<extension>svg</extension>
<mime-type>image/svg+xml</mime-type>
</mime-mapping>
<mime-mapping>
<extension>svgz</extension>
<mime-type>image/svg+xml</mime-type>
</mime-mapping>
|
[
"stackoverflow",
"0002374795.txt"
] | Q:
VB (macro in excel) - compile error
i am try to create an uploader in excel using vb (macro) to store data in an access database. i believe in terms of the script everything is ok. its just that when i run the upload it gives me the error Compile error - User-Defined type not defined and once i click on OK it highlights the part where it finds the error which is:
Private Sub Upload_Click() <------ this part!!!!
Dim cs As ADODB.Connection
Dim rs As ADODB.Recordset
Dim ServerName As String
Dim DatabaseName As String
Dim TableName As String
Dim UserID As String
Dim Password As String
can anybody help me make this work....
A:
You need to add the reference Microsoft ActiveX Data Objects 2.0 Library'
Menu Item: Tools/References
|
[
"stackoverflow",
"0020301465.txt"
] | Q:
clojure contrib logging to file
Hi I have tried logging with clojure contrib but to no avail.
Its clojure 1.1
(ns com.class.main.service
(:gen-class)
(:require (clojure.contrib [logging :as log])))
(log/info "Hello world")
I have put a log4j.jar file in my bin and a log4j.properties in the same directory as the log4j.jar.
Below is the log4j.properties conifguration
log4j.rootLogger=INFO, file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=H:\\log\\loging.log
log4j.appender.file.MaxFileSize=1MB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n*
I have gone through some basic examples although they are limited due to most using the newer version with tool.logging.
But below are the examples i have used
https://github.com/macourtney/Conjure/wiki/How-to-use-logging
&
http://www.paullegato.com/blog/setting-clojure-log-level/
have helped me get this far the log prints out on the console of emacs but i can't find a log file anywhere.
A:
CLojure logging has three options commons-logging, log4j-logging, java-logging and it picks them in that order according to availability as per the document specification . After looking at my sources it showed the same however the compiled version was a completley different order it started with java-logging. So I simply recompiled my contrib with ant to match the order i required as i couldn't remove java-logging.
|
[
"stackoverflow",
"0034836398.txt"
] | Q:
Part of html not being rendered by thymeleaf
Using thymeleaf, I'm trying to generate the following structure:
<li class="active">
<a href="/bootstrap/dashboard">Dashboard</a>
</li>
<li>
<a href="#">Charts<span class="fa arrow"></span></a>
<ul class="nav nav-second-level">
<li><a href="/bootstrap/flot">Flot Charts</a></li>
</ul>
</li>
I modified it as below:
<li th:each="menu : ${sideForm.menu}" th:class="${activeItem} == ${menu.item} ? 'active' : null">
<a href="#" th:if="${#lists.isEmpty(menu.submenu)}" th:href="@{'/' + ${sideForm.parentMenu} + '/' + ${menu.item}}" th:text="#{${menu.title}}">Item</a>
<a href="#" th:unless="${#lists.isEmpty(menu.submenu)}" th:text="#{${menu.title}}">Item<span class="fa arrow" th:class="fa arrow"></span></a>
<ul class="nav nav-second-level" th:unless="${#lists.isEmpty(menu.submenu)}" th:class="'nav nav-second-level'">
<li th:each="submenu : ${menu.submenu}">
<a href="#" th:unless="${#lists.isEmpty(menu.submenu)}" th:href="@{'/' + ${sideForm.parentMenu} + '/' + ${submenu.item}}" th:text="#{${submenu.title}}">Sub Item</a>
</li>
</ul>
</li>
It rendered as below:
<li class="active">
<a href="/bootstrap/dashboard">dashboard</a>
</li>
<li>
<a href="#">Charts</a>
<ul class="nav nav-second-level">
<li><a href="/bootstrap/flot">Flot Charts</a></li>
</ul>
</li>
I added "<span class="fa arrow" th:class="fa arrow"></span>", why isn't it rendered in real html? How can I fix it?
A:
the th:text from the <a> tag causes thymeleaf to replace its content with the given value, replacing also the span tag
<a href="#" th:unless="${#lists.isEmpty(menu.submenu)}" th:text="#{${menu.title}}">
<!-- everything in the <a> tag will be deleted by the th:text -->
Item
<span class="fa arrow" th:class="fa arrow"></span>
</a>
You should wrap the title in another html tag such as a span or th:block (th:block doesn't get rendered after being processed)
<a href="#" th:unless="${#lists.isEmpty(menu.submenu)}">
<th:block th:text="#{${menu.title}}">Item</th:block>
<span class="fa arrow" th:class="fa arrow"></span>
</a>
Or, with inline text:
<a href="#" th:unless="${#lists.isEmpty(menu.submenu)}" th:inline="text" >
[[#{${menu.title}}]]
<span class="fa arrow" th:class="fa arrow"></span>
</a>
|
[
"stackoverflow",
"0048890287.txt"
] | Q:
PECL libzip not found
I'm trying to install zipArchive with pecl. After running the command, I get an error - "Please reinstall the libzip distribution".
I'm running PHP 7.2 on Amazon Linux 2.
Here's my output:
$ ./pecl install zip
WARNING: channel "pecl.php.net" has updated its protocols, use "pecl channel-update pecl.php.net" to update
downloading zip-1.15.2.tgz ...
Starting to download zip-1.15.2.tgz (249,280 bytes)
....................................................done: 249,280 bytes
8 source files, building
running: phpize
Configuring for:
PHP Api Version: 20170718
Zend Module Api No: 20170718
Zend Extension Api No: 320170718
building in /tmp/pear/install/pear-build-ec2-userIZcX1f/zip-1.15.2
running: /tmp/pear/install/zip/configure --with-php-config=/usr/bin/php-config
checking for grep that handles long lines and -e... /usr/bin/grep
...<snip up to warning>...
configure: WARNING: You will need re2c 0.13.4 or later if you want to regenerate PHP parsers.
checking for gawk... gawk
checking for zip archive read/writesupport... yes, shared
checking libzip... yes
checking PHP version... PHP 7.x
checking for pkg-config... /usr/bin/pkg-config
checking for libzip... not found
configure: error: Please reinstall the libzip distribution
ERROR: `/tmp/pear/install/zip/configure --with-php-config=/usr/bin/php-config' failed
But if I check libzip it's already installed:
$ sudo yum install libzip
Loaded plugins: langpacks, priorities, update-motd
amzn2-core | 2.0 kB 00:00:00
Package libzip-0.10.1-8.amzn2.x86_64 already installed and latest version
Nothing to do
I'm using ./pecl as I had to install a new version of pear from my home directory and the old version is still in the path. This is the command I used to get the updated version of pear.
$ wget http://pear.php.net/go-pear.phar
$ php go-pear.phar
I don't know if that makes any difference? I do have the correct version referred to in my php.ini:
;***** Added by go-pear
include_path=".:/home/ec2-user/pear/share/pear"
;*****
Any help appreciated.
A:
I have managed to compile PECL zip (partly due to snow in the UK cancelling my booked day!). I have not tested this in php, but it loads correctly into phpinfo();
Option 1: Update Libzip & Hope for the best
I used an external CentOS-7 repo (which amzn linux 2 is supposed to be pretty compatible with) and the following script:
#PECL requires libzip 11 - get it from a foreign repo
sudo rpm --import http://wiki.psychotic.ninja/RPM-GPG-KEY-psychotic
#this looks wrong but the repo uses a single release
sudo rpm -ivh http://packages.psychotic.ninja/6/base/i386/RPMS/psychotic-release-1.0.0-1.el6.psychotic.noarch.rpm
#YUM REPO HACKS START
#unfortunately amazon-linux-2 release numbering breaks it - force RHEL 7 numbering
sudo sed -i s/\$releasever/7/g /etc/yum.repos.d/psychotic.repo
#Need to exclude outdated amzn zip packages
sudo yum remove libzip libzip-devel
#check for an exclude line, add our one if not present (to the main repo)
grep -A 100 -m1 "\[amzn2-core" /etc/yum.repos.d/amzn2-core.repo | grep exclude= || sudo sed -i -E "s/($(grep -A 100 -m1 "\[amzn2-core" /etc/yum.repos.d/amzn2-core.repo | grep -m1 ^name=)$)/\1\nexclude=libzip libzip-devel/" /etc/yum.repos.d/amzn2-core.repo
#check this worked, if not modify the existing exclude line(s)
grep -A 100 -m1 "\[amzn2-core" /etc/yum.repos.d/amzn2-core.repo | grep "exclude=.*libzip" || sudo sed -i -E "s/exclude=/exclude=libzip libzip-devel /" /etc/yum.repos.d/amzn2-core.repo
#YUM REPO HACKS END
sudo yum install --enablerepo=psychotic-plus gcc libzip libzip-devel
#now install PECL
wget http://pear.php.net/go-pear.phar
sudo php go-pear.phar
#patch it to cope with the XML being a module
sudo sed -i "$ s|\-n||g" /usr/bin/pecl
#and this should now work
sudo pecl install zip
#may still need to manually add to the php.ini
grep "^extension=zip.so" /etc/php.ini || echo "extension=zip.so" | sudo tee -a /etc/php.ini
Be VERY careful with the bit of this script marked 'YUM REPO HACKS' - it intentionally includes commands to modify your repo configuration which have had minimal testing. All it is actually doing is replacing the '$releasever' variable in the pyschotic repo with '7' and adding 'exclude=libzip libzip-devel' to the amzn2-core repo. You could do this with vim!
Option 2: 2 versions of libzip
From my research: if you are not comfortable with a 'found-by-google' repo on your server (I don't blame you, depends on use case) then you could leave the amzn zip in place, use their source repo to install libzip 11.2 source, install that (and/or its libraries) to an alternate location (find the instructions elsewhere for that) and compile the php module manually.
To compile zip manually:
$ pecl download zip
$ tar -xf zip-*.tgz && cd zip-* && phpize
$ ./configure --with-libzip=/path/to/secondary/libzip
...etc
|
[
"puzzling.stackexchange",
"0000000183.txt"
] | Q:
Twelve balls and a scale
You are given twelve identical-looking balls and a two-sided scale. One of the balls is of a different weight, although you don't know whether it's lighter or heavier. How can you use just three weighings of the scale to determine not only what the different ball is, but also whether it's lighter or heavier?
A:
There is another way to do this problem, that doesn't involve any sort of conditional branching at all. It is in fact possible to set a fixed weighing schedule beforehand and still determine which ball is lighter or heavier in just 3 weighings. I'll explain how below.
The gist of problems like these is, how much information can you get from the procedure you're allowed to undertake? With each weighing, the scale can either tip to the left, tip to the right, or stay balanced. This gives you a total of 33 = 27 possible outcomes, and in this case you need to discern 24 results from them (one of 12 balls is either light or heavy, which is 12 × 2 = 24).
So, we need to begin the tedious task of mapping each result to an outcome.
One of the things we can immediately notice is that there are also three states each ball can be in during each weighing - on the left side of the scale, on the right side of the scale, or off the scale. Naturally, this maps to the states of the scale in a way that's intuitively analogous:
If the odd ball out is heavier...
and the ball is placed on the left side, the scale will tip to the left.
and the ball is placed on the right side, the scale will tip to the right.
and the ball is off the scale, the scale will remain balanced.
If the ball is lighter, the first two cases are inverted.
There are 27 possible ways to place each ball in all three weighings, each corresponding to a different outcome if that ball is the odd one out. We need to find an arrangement of balls where each possible set of placements and its inverse (for the heavy and light cases) is distinct.
Here's a preliminary arrangement that satisfies the distinctness property:
Ball 1 2 3 4 5 6 7 8 9 10 11 12 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10-11-12
W1 L L L L L L L R R R R R R R R L
W2 L R L L L L R L R L R R R R L R
W3 L R R L L R L L R L L R R L R R
L = place it on the left This second table lists the inverses.
R = place it on the right Notice that no possible arrangement
= leave it off appears more than once in both tables.
Right away, we run into the problem that we're not putting the same number of balls onto each scale. If you have seven balls on one side and one on the other, of course the scale is going to tip to the side with seven balls (unless your odd ball out is ridiculously heavy, but let's not entertain that scenario). So we need to invert a few of these configurations so that we're putting four on each side for each weighing. With some trial and error, we can get something like this:
Ball 1 2 3 4 5 6 7 8 9 10 11 12 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10-11-12
W1 L L R R L R R L R R L L R L L R
W2 L R L R L R L R R L R L R L R L
W3 R L R L L L R R L R L R R R L L
So our final weighing schedule of balls is as follows:
Weighing 1: 1 4 8 12 / 5 7 10 11
Weighing 2: 2 6 9 11 / 4 7 10 12
Weighing 3: 5 8 9 10 / 3 6 11 12
And the outcomes are interpreted as such:
= = L : 3L L = = : 1H R = = : 1L
= = R : 3H L = L : 8H R = L : 5H
= L = : 2H L = R : 5L R = R : 8L
= L L : 9H L L = : 7L R L = : 4L
= L R : 6H L L R : 10L R L L : 12L
= R = : 2L L R = : 4H R L R : 11H
= R L : 6L L R L : 11L R R = : 7H
= R R : 9L L R R : 12H R R L : 10H
= : scale balanced
L : scale tipped to the left
R : scale tipped to the right
nL : ball n is light
nH : ball n is heavy
And thus, we've created a weighing scheme where each weighing is completely predetermined beforehand, that still manages to determine which ball is the odd one out, and whether it's lighter or heavier.
You might notice that we didn't use LLL, RRR, or === in our arrangements.
We can't use LLL and RRR as a 13th pair for a 13th ball, because then we'd end up having to put nine balls onto the scale, and there's no way to do that since nine is odd. We could probably use it in place of one of the LLR/RRL pairs, but leaving LLL and RRR out makes for a symmetry in the result chart that I rather like.
However, what's interesting is that you can have a 13th ball that you never place on any scale, and if your scales balance out in all three weighings, the 13th ball you never weighed is the odd ball out (although you obviously can't tell without a fourth weighing whether it's lighter or heavier).
A:
Split this into three groups of four, A1, A2, A3, A4; B1, B2...; C1, C2... Each step here corresponds to one weighing.
Weigh A against B.
If A > B, then weigh A1, B1, and B2 against B3, B4, and C1.
If the weights are equal, then one of A2...4 is heavier; weigh A2 and A3. If they are equal, A4 is heavier. If one is heavier, then that ball is heaviest.
If the first group is heavier, then either A1 is heavier, or B3-4 is lighter. Compare B3 and B4; if they are equal, A1 is heavier; if they are different, the lightest is the lightest ball.
If the first group is lighter, then either B1 or B2 is lighter. Weigh them and see.
If A < B, renumber all A-balls to B-balls, and perform the above steps.
If A = B, weigh A1, A2, A3 against C1, C2, C3
If they are equal, then weigh A1 against C4. If A1 is lighter, then C4 is the odd ball and it is heavy. If A1 is heavier, then C4 is the odd ball and it is light.
If A is heavier than C, weigh C1 against C2. If they are equal, then C3 is the odd ball and it is lighter. If they are not equal, then the lighter of the two balls is the lightest ball
If A is lighter than C, weigh C1 against C2. If they are equal, then C3 is the odd ball and it is heavier. If they are not equal, then the heavier of the two balls is the heaviest ball.
We can work backwards from the third step to see, approximately, why this works. At the third weighing, the options need to be reduced to either two or three balls. This means that the second weighing must reduce to either two or three possible balls.
We know that the first step will remove either 1/3 or 2/3 of the possible solutions, no matter what you do. This means that, in the 1/3 case, you need to split the possibilities down from 8 into a group of 3, a group of 3, and a group of 2. From this, the third weighing points to the odd ball out. Because this case implies one set of balls is heavier, by virtue of finding the odd ball out, we know whether it's heavier or lighter, so we actually don't need to worry about this piece of information at all.
In the 2/3 case, you need to reduce the possibilities into a group of 3 and a group of 1, which is easy enough to do intuitively. Because we actually don't know the relative weight of the odd ball in this case, the information from the third weighing must be used to determine whether the ball is heavier or lighter.
A:
Some of the existing answers to this ancient question are excellent, but there's one famous answer that I think deserves mention here. It comes from an article in Eureka, the annual magazine of the University of Cambridge's student mathematical society, written by C A B Smith under the pseudonym of "Blanche Descartes".
It has two very nice features. The first is that it's an "unbranching" solution: you don't need to change what you do on later weighings depending on the results of earlier ones. The second is that once you've seen it it's almost impossible to forget.
Smith's solution is written entirely in verse and includes an explanation of how it all works, but I shall quote only the actual answer. "F" here is our protagonist Professor Felix Fiddlesticks, whose mother has asked him for help with the puzzle. I have made some trifling changes to the original formatting.
F set the coins out in a row
And chalked on each a letter, so,
To form the words: F AM NOT LICKED
(An idea in his brain had clicked.)
And now his mother he'll enjoin:
"MA, DO / LIKE
ME TO / FIND
FAKE / COIN!"
Each of the three lines of F's injunction describes one weighing. When you've done them all, the results uniquely determine which coin is fake and in which way.
|
[
"stackoverflow",
"0033368154.txt"
] | Q:
Moqui - Connecting to an IMAP server over an SSL connection?
I am trying to poll an email server in Moqui 1.5.4. I am using org.moqui.impl.EmailServices.poll#EmailServer from the 'tools' application.
The email server is set up as follows:
<moqui.basic.email.EmailServer emailServerId="testEmail" mailUsername="[email protected]" mailPassword="xxxxxxxx" smtpHost="" smtpPort="" smtpSsl="" storeHost="Webmail8.xxxxxxxxxxx.ie" storePort="993" storeProtocol="imap" storeDelete="N" />
All entries, passwords have been tested on Outlook and connect no problem to the server.
I get a javax.mail.AuthenticationFailedException.
Additional Information:
In initial tests I received the following error message, so I removed the 'static' modifier from the indicated line in the code. (I was not sure yet if it was an issue or if I may be doing something wrong.)
--- 98330 [ndlerThread[15]] WARN moqui.impl.context.TransactionFacadeImpl
Transaction rollback. The rollback was originally caused by: startup failed:
classpath_//org/moqui/impl/pollEmailServer_groovy: 28: Modifier 'static' not allowed here.
@ line 28, column 1.
final static Logger logger = LoggerFactory.getLogger("org.moqui.impl.pollEmailServer")
Some things I tried to see if I could resolve the problem include:
setting storeProtocol="imaps"
including the smtp details in the EmailServer entry (note I only need to poll, not send mail).
adding the following line to pollEmailServer.groovy (having looked at the com.sun.mail.imap package).
sessionProperties.put("mail.imap.ssl.enable", true)
Full Authentication failed error message is:
Error running service [org.moqui.impl.EmailServices.poll#EmailServer] (Throwable)
javax.mail.AuthenticationFailedException
at javax.mail.Service.connect(Service.java:306)
at javax.mail.Service.connect(Service.java:156)
at javax.mail.Service.connect(Service.java:105)
at pollEmailServer_groovy.run(pollEmailServer_groovy:47)
at org.moqui.impl.context.runner.GroovyScriptRunner.run(GroovyScriptRunner.groovy:50)
at org.moqui.impl.context.ResourceFacadeImpl.script(ResourceFacadeImpl.groovy:337)
at org.moqui.impl.service.runner.ScriptServiceRunner.runService(ScriptServiceRunner.groovy:49)
at org.moqui.impl.service.ServiceCallSyncImpl.callSingle(ServiceCallSyncImpl.groovy:260)
at org.moqui.impl.service.ServiceCallSyncImpl.call(ServiceCallSyncImpl.groovy:137)
at ServiceRun_xml_transition_run_actions.run(ServiceRun_xml_transition_run_actions:10)
at org.moqui.impl.actions.XmlAction.run(XmlAction.groovy:99)
at org.moqui.impl.screen.ScreenDefinition$TransitionItem.run(ScreenDefinition.groovy:659)
at org.moqui.impl.screen.ScreenRenderImpl.recursiveRunTransition(ScreenRenderImpl.groovy:223)
at org.moqui.impl.screen.ScreenRenderImpl.recursiveRunTransition(ScreenRenderImpl.groovy:217)
at org.moqui.impl.screen.ScreenRenderImpl.recursiveRunTransition(ScreenRenderImpl.groovy:217)
at org.moqui.impl.screen.ScreenRenderImpl.recursiveRunTransition(ScreenRenderImpl.groovy:217)
at org.moqui.impl.screen.ScreenRenderImpl.recursiveRunTransition(ScreenRenderImpl.groovy:217)
at org.moqui.impl.screen.ScreenRenderImpl.internalRender(ScreenRenderImpl.groovy:301)
at org.moqui.impl.screen.ScreenRenderImpl.render(ScreenRenderImpl.groovy:164)
at org.moqui.impl.webapp.MoquiServlet.doScreenRequest(MoquiServlet.groovy:71)
at org.moqui.impl.webapp.MoquiServlet.doPost(MoquiServlet.groovy:37)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:713)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:806)
at net.winstone.core.ServletCotion.execute(ServletConfiguration.java:270)
at net.winstone.core.SimpleRequestDispatcher.forward(SimpleRequestDispatcher.java:290)
at net.winstone.core.listener.RequestHandlerThread.processRequest(RequestHandlerThread.java:212)
at net.winstone.core.listener.RequestHandlerThread.run(RequestHandlerThread.java:143)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at net.winstone.util.BoundedExecutorService$1.run(BoundedExecutorService.java:81)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Addendum: Processing the messages once polled with Email ECA Rules.
I can see when I turn on logger info in EmailEcaRule.groovy that the condition in my Email ECA keeps evaluating to 'false'. But it shouldn't be?
======== EMECA Process Received Email conditionPassed? false My condition: TestEmail fields:
(Note that I inserted "My condition: ${fields.subject}" into the logger info to double check my condition expression was as it should be.)
My emeca is:
<emecas xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://moqui.org/xsd/email-eca-1.5.xsd">
<emeca rule-name="Process Received Email">
<condition><expression>fields.subject == 'TestEmail'</expression></condition>
<actions>
<service-call name="org.moqui.impl.EmailServices.save#EcaEmailMessage" />
</actions>
</emeca>
</emecas>
I have tested and re-tested this. I don't know why it is evaluating to false. Please let me know if any additional information is required.
Still no luck in solving this. I must be doing something stupid. I commented out if (conditionPassed) {} in the EmailEcaRule.groovy to bypass my condition in the Email ECA rule and just run the action, but now it gets hung up with a "Cannot invoke method get() on null object" error in org.moqui.impl.EmailServices.save#EcaEmailMessage, presumably on headers.get('message-id'). But I can see in the log information that the message Id is in the headers information, and successfully converted to lower case.
A:
There were a few issues with this. First is that Moqui was using an old version of JavaMail (now updated to 1.5.4). Another was how the password was passed through, and more generally there was lots of room for improvement in how the script for poll#EmailServer service was using the JavaMail API.
There are various changes in place as of commit #bf0f872. I was able to connect successfully using storeProtocol=imaps, storePort=993, etc.
To answer your question: without these code changes I don't think connection via SSL would be possible. In other words, this ended up being more of a bug report than a question.
|
[
"scifi.stackexchange",
"0000214582.txt"
] | Q:
Do ships in Pirates of Caribbean get a speed boost from magic?
In the Pirates of the Caribbean series, the ships have magical properties. Do these properties affect their speeds? That is, do they travel faster than equivalent real-world sailing ships?
A:
It depends
But for the most part, no.
There's a total of 4 notable ships that we know of:
The Flying Dutchman
This ship can sail through the water and also ascend. It is almost always with the wind and because of this, it is usually always faster than other ships including the Black Pearl. Unless the Black Pearl has the wind and/or the Dutchman doesn't, the Dutchman is faster.
The Black Pearl
This was raised by Davy Jones himself after it got sunk as The Wicked Wench. As part of the deal Jack made to Davy Jones, The Black Pearl became the fastest ship, so besides the Dutchman with the wind, The Black Pearl is the fastest ship and is because it got risen as the fastest ship-this could be interpreted as using magic for its speed, I however do not as it's more of a passive thing and doesn't actually use magic at all, it's simply one of Davy Jones' powers.
The HMS Endeavour
This ship was the ship of Lord Cutler Beckett and did not use any magic whatsoever. It simply was built well and had a lot of firepower.
The Queen Anne's Revenge
A good ship, and seems to be able to be controlled by a magic sword, also known as The Sword of Triton. When near other ships, if the user decides, they can control the masts and ropes and everything about the ships. This ship was under the command of Blackbeard who could and did use the sword to speed up the ship. It is now under the command of Barbossa who also used the sword for the same purposes.
So do ships get a speed boost from magic? Answer:
Only when the Sword of Triton is near and is wielded to speed it up.
Otherwise, all ships rely on how they're built for their speed, but the Black Pearl and/or The Flying Dutchman remain the fastest ships.
|
Subsets and Splits