INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
How to divide a column for one dataframe by the column from another dataframe
I have a data frame with numbers of doctors in some cities in Brazil (data frame A). I have another data frame (data frame B) with the cities population (all of them). How can I obtain the value of number of doctors divided by the city population. Note that I have more cities in B than in A.
> A
City Doctors
A 3
C 4
E 5
> B
City Pop
A 100
B 20
C 30
D 40
E 500
F 10
I expect the following:
> Doc_divided_by_Pop
City Doctors_Pop
A 3/100
C 4/30
E 5/500
|
Here's a way using `match` from base R -
A$Doctors_Pop <- A$Doctors / B$Pop[match(A$City, B$City)]
* * *
Another way using `merge` -
result <- merge(A, B, by = "City", all.x = TRUE)
result$Doctors_Pop <- result$Doctors / result$Pop
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "r"
}
|
The circle of Mega
> I follow a pattern.
What am I?
It appears to me that just the above two sentences are not enough. I should add more about what I've already tried to solve it. But I already solved it, and it wouldn't be fun if I told more. [this is a rant, not a clue]
|
I think the answer is
> 51
because
> The last two riddles of OP were 'the circle of three' and 'the circle of two' having answers 'two' and 'Mega'. So according to the pattern the next had to be 'the circle of Mega' whose answer should be the name of the next puzzle by OP which is 'Circle of 51'.
Great Series.
|
stackexchange-puzzling
|
{
"answer_score": 5,
"question_score": 3,
"tags": "riddle, lateral thinking"
}
|
Good practice to add to set in while condition?
I am trying to add a random number to a set. If it is already in the set, then the loop should continue and try again.
Which is better practice,
do {
nextChosenInt = rand.nextInt(48) + 1;
addFailed = !chosenInts.add(nextChosenInt);
}
while (addFailed);
or
do {
nextChosenInt = rand.nextInt(48) + 1;
}
while (!chosenInts.add(nextChosenInt));
|
I would vote for the second option here, with a slight change.
You are utilising the fact that the `.add` method returns a boolean which is a beneficial, in that you don't need to have a redundant flag variable which, from the context of your code, serves no other purpose than just terminating the loop.
Personally however I would choose to extract:
!chosenInts.add(nextChosenInt)
into its own method which is more descriptive and readable. By doing this, you are allowing anyone to understand this condition with no prior knowledge of the Collections API.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "java, while loop, set"
}
|
Filter App Template - ArcGIS Online
I would like to use the Filter App Template for an ArcGIS Online Map I'm creating. I'm working with a water system, and I want the user to be able to use the filters to search for certain junction types (e.g. manholes, fire hydrants, etc.).
While in "Map View" I created filters for each unique value in my "Junction" field. I selected "Apply Filter and Zoom," but when I go back to the Filter App it says, "Web map does not contain any interactive filters." Is there something I'm missing?
|
Following this walkthrough will help you: <
|
stackexchange-gis
|
{
"answer_score": 1,
"question_score": 1,
"tags": "arcgis online, filter, template"
}
|
get xml attribute value of element based on another attribute using linq
Having some difficulty retrieving the value of an attribute.
Assuming xml that looks like:
<g id="formSide1Main" class="formSideMain">
<g fdtFieldName="Forename1" fdtLorenzoField="lzoFnm">
.....
I'm trying to retrieve the value of 'fdtFieldName' attribute. Based on other similar questions, I've tried:
var svgDocument = XDocument.Parse(rpd.formmodeler);
var firstName = svgDocument.Elements("g")
.Where(x => (string)x.Attribute("fdtLorenzoField") == "lzoFnm").FirstOrDefault();
var attrVal = firstName?.Attribute("fdtFieldName").Value;
But firstName keeps coming up null. Any ideas?
|
In the end I achieved my goal with xml reader:
string firstName;
XmlReader xmlReader = XmlReader.Create(new System.IO.StringReader(rpd.formmodeler));
while (xmlReader.Read())
{
if ((xmlReader.NodeType == XmlNodeType.Element) && (xmlReader.Name == "g"))
{
var firstNameElement = xmlReader.GetAttribute("fdtLorenzoField");
if (firstNameElement == "lzoFnm")
{
firstName = xmlReader.GetAttribute("fdtFieldName");
}
}
}
I'm not sure if this is going to have poor performance with large xml documents, but I'll see how it goes.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "c#, xml, linq"
}
|
USAJMO 2017 P4: triples $(a,b,c)$ such that $(a-2)(b-2)(c-2)+12$ is a prime number that divides the positive number $a^2+b^2+c^2+abc-2017$?
> Are there any triples $(a,b,c)$ of positive integers such that $(a-2)(b-2)(c-2)+12$ is a prime number that properly divides the positive number $a^2+b^2+c^2+abc-2017$?
My progress: Let $x=a-2$, $y=b-2$, $z=c-2$, then we get $xyz+12 \mid \left( x+y+z+4 \right)^2 - 45^2 \implies xyz+12 \mid (x+y+z-41)(x+y+z+49)$. So $xyz+12 \mid (x+y+z-41)$ or $xyz+12|(x+y+z+49)$ .
Also $xyz+12 $ can't divide both or else then $xyz+12 |90$ ( which doesn't work ).
WLOG $x\ge y\ge z$, then clearly $x\ge 9$ , since $11^2\cdot 3+ 11^3\le 2017$ ( not satisfying properly divide property).
Also I got $x,y,z$ odd or not divisible by $1 \mod 3$, or else $(a-2)(b-2)(c-2)+12$ is not prime.
|
If we continue from here: $\;\;\;xyz+12 \mid x+y+z-41\;\;\;$ or $\;\;\;xyz+12|x+y+z+49$.
We can assume $x\leq y\leq z$. We see that $x,y,z\notin \\{0,2,3,4,6,8,9\\}$ since $xyz+12$ is prime.
* If $x>1$ then $x,y\geq 5$ and so $xyz+12\geq 25z+12$ so in
* first case: $$25z+1\leq |x+y+z-41|\leq 3z+41\implies z\le 1$$ and thus no solution.
* second case: $$25z+1\leq x+y+z+49\leq 3z+49\implies z\leq 2$$ so no solution again.
* If $x=1$ then $\;\;\;yz+12 \mid y+z-40\;\;\;$ or $\;\;\;yz+12|y+z+50$.
* If $y\neq 1$ then $y\geq 5$. In first case we have $5z+12\leq 2z+40\implies z\leq 9$ so $z=7$ (and $y=5$ or $y=7$) or $z=5$ (and $y=5$). None works. In second case we have $5z+12\leq 2z+50\implies z\leq 12$. So $z\in\\{11,7,5\\}$ but none works.
* If $y=1$ then $\;\;\;z+12 \mid z-39\;\;\;$ then $z+12\mid 51 \implies z=5$ or $\;\;\;z+12|z+51$, then $z+12\mid 39$ so $z=1$.
* If $x=-1$ then we proccede similary like in a previous case...
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 5,
"tags": "algebra precalculus, number theory, elementary number theory, prime numbers, contest math"
}
|
How set value when the property has the getter method using reflection in c#
public class test
{
public test()
{
ting=10;
}
private int ting{get;set;}
public int tring
{
get
{
return ting;
}
}
}
void Main()
{
var t= new test();
//Below line giving error
Console.Write(t.GetType().GetProperty("tring").SetValue(t,20));
}
How to resolve this using reflection?
|
Well yes - the property _can't_ be set. It's read-only, presumably deliberately.
If the designer of the class hasn't given you the opportunity of setting the value, you shouldn't be trying to set it. In many cases it would be impossible to do so, as the value may not even be backed by a field (think `DateTime.Now`) or may be computed some non-reversible way (as per Marcin's answer).
In this particular case if you were _really_ devious you could get hold of the IL implementing `tring.get`, work out that it's fetching from the `ting` property, and then call _that_ setter by reflection - but at that point you're going down a very dark path which you're almost certain to regret.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "c#, reflection"
}
|
Any "casual" translation for 遵命?
>
It's said from a person of lesser position to a person of higher position, ie from soldier to general.
What would be a more "casual" way of translating it into English other than "As you wish", because "as you wish" sounds like something that is said to royalty and whatnot, rather than a soldier to general (as an example).
|
Well, there are plenty of "casual" translations.
In a military setting,
* "Yes, Sir."
* "Roger that."
* "Copy that."
* "Affirmative."
*Note that the later three have the same implication as that of `` but is more accurately translated to ``
In a even less serious setting,
* "Will do."
* "Sure."
I will edit when I have thought of more.
|
stackexchange-chinese
|
{
"answer_score": 8,
"question_score": 5,
"tags": "translation, word choice"
}
|
How to convert password string to Renci.SshNet.PrivateKeyFile in C#?
My password and my username are strings and to initialize my `SftpClient` I need to convert them to `Renci.SshNet.PrivateKeyFile`.
I have tried to cast:
string myPassword = "root";
(Renci.SshNet.PrivateKeyFile)myPassword
It doesn't work.
Thank you in advance for you help.
|
That's just a nonsense.
Password and private key represent two different authentication methods. You cannot convert one to the other.
Either you authenticate with a password. Or you authenticate with a private key. The private key is typically stored in a file.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "c#, ssh, sftp, private key"
}
|
window.onload in IE7
I have this the javascript work perfectly in chrome but not work on IE7:
The click of id icsave , not work. Nothing happens, icsave save the page normaly
window.onload = function() {
if ($('#MODE').val() != 'U') {
$('#MOD_BY_JS').val( % 1);
clik('#ICSave')
}
};
function clik(element) {
try {
document.getElementById(element).click();
}
catch (e) {
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
var cb = document.getElementById(element);
cb.dispatchEvent(evt);
}
};
|
`window.onload` may not get executed for a number of reasons.
* Some resource on the page isn't loaded (images), since `window.onload` only fires after all resources have loaded.
* Something is overwriting `window.onload`
* You have a javascript error somewhere else
My suggestion to you is that since you're using jQuery, use either:
$(document).ready(function(){ /* initialize stuff */});
or if you actually need `onload`
$(window).load(function(){ /* initialize stuff */});
For your example I would recommend using the `$(document).ready(...)` method as it looks to me your script will work as soon as the dom is ready, which is when the `ready` event fires.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -3,
"tags": "javascript, jquery, internet explorer, internet explorer 7"
}
|
How to find intersection point of two 3D lines
I know the $x,y,z$ values of the 4 points that create two lines. I also know the $x,y$ value of the crossing point. How do I get the $z$ of the crossing point?
|
given four points $\mathbf{a,b,c,d}$, form the parametric equations
$\mathbf{a}+t \mathbf{(b-a)}$ and $\mathbf{c}+s \mathbf{(d-c)}$, where $s,t \in \mathbb R$ are parameters.
This will look like $\ell_1:=\\{(a_1,a_2,a_3)+t(b_1-a_1,b_2-a_2,b_3-a_3) \mid t \in \mathbb R\\}$, and analogous for $\ell_2$.
If you know the $x,y$ values for the intersection, then there is a system of linear equations:
$x=a_1+t(b_1-a_1)=c_1+s(d_1-c_1)$ and $y=a_2+t(b_2-a_2)=c_1+s(d_2-c_2)$. Solve these for $s,t$ and plug them back into the parametric equations to get the $z$ value.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "linear algebra, systems of equations, 3d"
}
|
Ruby: Great GUI builder?
I did some programming with Java and C# and they both have great GUI builders. Java has things like Netbeans and Eclipse, and C# has Visual Studio. It's pretty easy to build user interface with drag and drop. Lately I do some Ruby coding and I'm wondering if there is something similar?
Thank you!
|
It depends from UI toolkit: for wxWidgets you can take DialogBlocks, for Qt — QtDesigner or QtCreator.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "ruby, user interface"
}
|
Margin Auto renders to Margin 0px
I have the following css for a div :
#readWrite{
width:100%;
display: block !important;
margin-left: auto;
margin-right: auto;
}
But, when I open in Chrome, the margin renders to 0px and hence the div is not centered.
!enter image description here
How to resolve this?
If I do putmargin's exact values, it works. But no Responsiveness, obviously.
Here's a jsfiddle : <
|
Set your parent div
#jam {text-align: center; width: 100%;}
and your child div
#readWrite {margin: 0 auto;}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "jquery, html, css, materialize"
}
|
Are Rivers and Aquifers guaranteed to come together in Dwarf Fortress?
I've been interested in Dwarf Fortress, so I decided to start playing with it. It has a reputation for being quite difficult, so I decided to find a tutorial. **Every** tutorial I found recommended to start by a river, and not to start by an aquifer.
So, I started the game, generated my world, and what do I find? Every single area with a river, also has an aquifer. Are these tied together?
If it helps, I am running the latest version (0.31.10).
|
No, they're not guaranteed to come together, at least not when considering a brook the same as a river. A brook is easier for beginners to start with, and has the same benefits as a river.
I usually use the following settings in the `f`ind dialog to find a good place for starters:
* Evil: Medium
* Temperature: Medium
* Rain: Medium
* Flux Stone: Yes
* Aquifer: No
* River: Yes
You might also want to read my reponse on the question for a good starting location for beginners.
|
stackexchange-gaming
|
{
"answer_score": 7,
"question_score": 6,
"tags": "dwarf fortress"
}
|
How to communicate with Infinispan from outside JBoss?
I have the need to handle some messages with payload in the correct order and high performance in a cluster of JBoss EAP 6.1 nodes. The first idea was to use JMS to communicate these messages to JBoss, but that seems not to be easy at all (if you are interested in details, click here for a previous question regarding the scenario).
I had a look at infinispan, then, and have the feeling that i can handle all my requirements by using it. But what i didn't find out right now is: How can i communicate with Infinispan from outside JBoss? Is it possible to send data to (or to put a key-value pair into) a particular cache from a client, maybe using hotrod, while this cache is accessible and configurable inside JBoss?
|
EAP does not provide a way to access Infinispan remotely. You'd need to take Infinispan Server and somehow deploy it manually on top of EAP. The simplest thing might some kind of REST call that then puts stuff in Infinispan. However, based on your requirements, I'd have imagined that JMS would be a better choice.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "java, jboss, infinispan"
}
|
how to remove index.php from url in codeigniter
I had some big issues with removing the index.php. As a general rule the .htaccess below has been tested on several servers and generally works:
how to remove index.php below link in codeigniter <
|
You Have to add .htaccess file in you root folder .
DirectoryIndex index.php
RewriteEngine on
RewriteCond $1 !^(index\.php|(.*)\.swf|forums|images|css|downloads|jquery|js|robots\.txt|favicon\.ico)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ./index.php?$1 [L,QSA]
Save this file as .htaccess in System Folder
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -2,
"tags": "codeigniter"
}
|
Limitations of SQL Server 2012 Express version?
I'm aware that the SQL Server 2008 R2 Express was limited to 1 CPU and 10 GB Databases. It's not clear if Microsoft bumped those numbers up to be more reflective of 2012. I looked at several places but I still don't have a clear idea. Yes, I understand 2012 is not yet released but I have to assume it's software performance requirements are already set.
|
As far as I am aware there has been no official announcement of the capabilities of SQL Express 2012, although I have heard rumours that it will be the same as 2008 R2 (1 CPU and 10Gb database limit).
Microsoft have released specifications for the standard and enterprise editions.
|
stackexchange-serverfault
|
{
"answer_score": 8,
"question_score": 7,
"tags": "sql server, sql server 2012"
}
|
How to compute the intersection of an ideal with the maximal order of a subfield?
I asked this earlier on math.stackexchange but I think this is a better place for this question.
Computing the intersection of ideals belonging to the same maximal order of a number field $K$ can be reduced to computing the intersection of lattices of the same dimension.
How can I compute the intersection of an ideal with a maximal order of a subfield, where the underlying lattices no longer have the same dimension?
More concretely, given an ideal $\mathfrak{I} \subset \mathcal{O}_K$ and a subfield $L \subset K$, how can I compute a basis for $\mathfrak{I}\cap\mathcal{O}_L$?
This is relevant, but only leads me to intersection of lattices of equal rank: <
|
This reduces easily to computing the intersection of two $\mathbf{Z}$-lattices (not necessarily of full rank) inside $\mathbf{Q}^n$ for some $n$. If you have two lattices $L, M$ of ranks $r$ and $s$, and you let $A$, $B$ be the $r \times n$, resp. $s \times n$, matrices whose rows are bases of $L$ and $M$ respectively, then you can compute the intersection $L \cap M$ by computing the kernel of the $(r + s) \times n$ integer matrix given by stacking $A$ on top of $B$.
(Mathematically, this is relying on the fact that the map from the abstract direct sum $L \oplus M$, to the sum of $L$ and $M$ as submodules of $\mathbf{Q}^n$, has kernel $\\{ (v, -v): v \in L \cap M\\}$.)
See the Sage library code for the "intersection" method of free modules.
|
stackexchange-mathoverflow_net_7z
|
{
"answer_score": 3,
"question_score": 3,
"tags": "nt.number theory, ac.commutative algebra, algebraic number theory, lattice theory"
}
|
Changing global Variable from within function
Here im having a bit of an issue with this very simple script Ive written up. The aim for this script is to simply reduce the given number by one each time the button is clicked. I cannot appear to do this.. My global variable being the Number=100 doesnt appear to change, or change more than once.. Apologies for not being able to explain this well. Here is the part im working on..:
<script>
var Number = 100; // Number i want changed and to keep changing each button click
function outcome() { // Button calls this function
Number = Number - 1; // Tries to change Global Number.. :/
}
document.write(Number); // Has the Number written in the document
</script>
|
Yes, conceptually this is right. Only you are not calling the function, at least not before writing `Number` to the document.
Btw, `Number` is the global reference to the `Number` constructor so you should use another variable name, lowercase at best.
var num = 100;
function outcome() {
num--;
}
outcome();
document.write(num); // 99
or
<script>
var num = 100;
function outcome() {
num--;
alert(num);
}
</script>
<button onclick="outcome()">Decrease!</button>
(Demo at jsfiddle.net)
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 4,
"tags": "javascript, function, global, increment"
}
|
Why can't I use a "file" as the "body" of an http request?
"http.Post" expects a "Reader" as the body argument. "File" implements "Reader". But if I pass file as the body argument I always receive 0 bytes at the other end. Why?
Here is the code:
package main
import (
"fmt"
"net/http"
"os"
)
func main() {
file, err := os.Open("lala.txt")
if err != nil {
fmt.Printf("file open errrrr %v \n", err)
}
defer file.Close()
resp, err := http.Post(" "text/plain", file)
if err != nil {
fmt.Printf("errrrr %v \n", err)
} else {
fmt.Printf("resp code %d \n", resp.StatusCode)
}
}
I know that you could do "file.ReadAll" to a buffer and use that. But it feels like double work.
|
The site requestb.in seems to ignore POST data if the header `Content-Length` is not specified. This code works:
package main
import (
"fmt"
"net/http"
"os"
)
func main() {
file, err := os.Open("lala.txt")
if err != nil {
fmt.Printf("file open errrrr %v \n", err)
}
defer file.Close()
req, _ := http.NewRequest("POST", " file)
req.ContentLength = 5
resp, err := http.DefaultClient.Do(req)
if err != nil {
fmt.Printf("errrrr %v \n", err)
} else {
fmt.Printf("resp code %d \n", resp.StatusCode)
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "file, http, post, go"
}
|
Exception in thread, function add number to array
I am trying to implement a simple function which adds a number to existing array but I am getting an error in the following code, an exception is exactly at function addArrayToNumber in line: "number+= NUMBERS_ARRAY[i]". I don't want to catch the exception, just repair code.
public class Main {
private static final int[] NUMBERS_ARRAY = {1, 2, 3, 4, 5};
public static final void main(String[] args) {
int x = addArrayToNumber(1);
System.out.println("X = " + x);
int y = addArrayToNumber(10);
System.out.println("Y = " + y);
}
private static int addArrayToNumber(int number) {
for (int i = 0; i <= NUMBERS_ARRAY.length; i++) {
number += NUMBERS_ARRAY[i]; /** here it is */
}
return number;
}
|
Array of n members has indices 0, 1, ..., n-1. However, in your for loop, you're testing `i <= NUMBERS_ARRAY.length`, meaning if array has length 5, you're trying to access NUMBERS_ARRAY[5], which obviously doesn't exist. Instead, use `i < NUMBERS_ARRAY.length`, so loop becomes
for(int i=0; i < NUMBERS_ARRAY.length; i++)
Alternatively, when you're looping over all elements you can use for-each syntax, i.e.
for (int element : NUMBERS_ARRAY) {
number += element; /* add every element from NUMBERS_ARRAY to number */
}
and not think about indices at all.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "java, arrays, numbers"
}
|
is it possible to invoke function inside if statement only if it returns true
Im trying to is invoke function inside if statement only if it returns true. The below function checks the username field to make sure theres something in it if there is it sends it to the function validate form
function usernamecheck() {
if ($("#signupUsername").val().length < 4) {
return true;
}
}
function validateForm() {
if (usernamecheck(returns true)) {
//run code
}
}
Is it possible/ the best way to do it
|
function usernamecheck() {
//Updated this to just return the expression. It will return true or false.
return $("#signupUsername").val().length < 4;
}
function validateForm() {
//Here we just call the above function that will either return true or false.
//So by nature the if only executes if usernamecheck() returns true.
if (usernamecheck()) {
//Success..Username passed.
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "javascript"
}
|
Permutations of dictionary in python
I have a dictionary like this -
{'A': 0, 'B': 0, 'C': 0, 'D': 4}
I want to generate a list like this -
[{'A': 1, 'B': 0, 'C': 0, 'D': 4},
{'A': 0, 'B': 1, 'C': 0, 'D': 4},
{'A': 0, 'B': 0, 'C': 1, 'D': 4},
{'A': 0, 'B': 0, 'C': 0, 'D': 5}]
What is the most pythonic way to do this?
|
You can use list comprehension and dictionary comprehension together, like this
d = {'A': 0, 'B': 0, 'C': 0, 'D': 4}
print [{key1: d[key1] + (key1 == key) for key1 in d} for key in d]
**Output**
[{'A': 1, 'B': 0, 'C': 0, 'D': 4},
{'A': 0, 'B': 0, 'C': 1, 'D': 4},
{'A': 0, 'B': 1, 'C': 0, 'D': 4},
{'A': 0, 'B': 0, 'C': 0, 'D': 5}]
The idea is to generate a new dictionary for each `key`, and when the `key` matches the key of the dictionary being constructed with dictionary comprehension, then add `1` to it. `(key1 == key)` will evaluate to `1` only when both the keys match, otherwise it will be zero.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 3,
"tags": "python, permutation, python itertools"
}
|
CSS Style Question
In the following style:
.slider div div div h2 span { color:#ae663d;}
What is the purpose of "div div div"?
|
It specifies that the rule applies to span tags, contained in h2 tags, contained in three nested divs, under a tag with class 'slider'.
Something like this, where the `<span>` containing "here" will be matched:
<body class="slider">
<div>
<div>
<div>
<h2>Header text <span>here</span></h2>
</div>
</div>
</div>
</body>
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "css"
}
|
"I ordered us..." vs. "I ordered for us..." vs "I ordered ... for us"
I usually use a phrase such as:
> (1) I ordered us a box.
Would it be more correct to say:
> (2) I ordered for us a box.
Or, better still:
> (3) I ordered a box for us.
Example 3 sounds the most correct, but are 1 and 2 improper English or are they perfectly valid in written form?
|
(1) and (3) are equally grammatical, but (2) is ungrammatical. _Order_ is a ditransitive verb, which means it can be followed by an indirect and a direct object as in (1), but it is possible to replace the direct object with a prepositional phrase, as in (3).
|
stackexchange-english
|
{
"answer_score": 7,
"question_score": 2,
"tags": "grammaticality, word order"
}
|
d3.js unique colors when plotting an arbitrary number of lines from an array of array of objects
I am plotting an arbitrary number of lines with the following code, where `allLines` is an array of arrays of objects such that each array of objects produces a line. Right now all the lines are the same color. **How can I make each one a unique color?** I am looking for an alternative that would not involve shoehorning this into useing `nest()`
var lines = d3.select("svg").selectAll(".myLine")
.data(allLines)
lines.enter()
.append("path")
.attr("class", "myLine")
.attr("d", tweetLine)
.attr("fill", "none")
.attr("stroke", "darkred")
.attr("stroke-width", 2)
lines.exit().remove();
lines.attr("class", "myLine")
.attr("d", tweetLine)
.attr("fill", "none")
.attr("stroke", "darkred")
.attr("stroke-width", 2)
|
You can use one of the predefined scales, e.g. `d3.scale.category20()`. You use it like any other D3 scale:
var colours = d3.scale.category20();
colours(someData);
colours(someOtherData);
For your lines, you have an array as the data, so that won't work directly. However, you can compute something based on the values for the lines and use that, e.g.
.attr("stroke", function(d) {
return colors(d3.sum(d, function(e) {
return e.whateverTheNumberThatDeterminesTheLineIs;
}));
})
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript, d3.js"
}
|
Analog div for using in C# (server)
What is analog in C#?
js:
$('#MyDiv').show();
var d = document.getElementById('MyDiv');
d.innerHTML = someLargeHtmlCode;
html:
<div id="MyDiv" runat="server" style="display: none;">
</div>
Can I use ? Some like that:
html:
<asp:Panel id="MyDiv" runat="server" style="display: none;">
</asp:Panel>
But I don't know what C# code must be.
|
<asp:Panel id="MyDiv" runat="server" Visible="false">
<asp:Literal ID="literal" runat="server" />
</asp:Panel>
and in your code behind:
protected void Page_Load(object sender, EventArgs e)
{
MyDiv.Visible = true;
literal.Text = "Hello";
}
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "c#, html, asp.net"
}
|
Using $javascript helper issue in CakePHP: "Undefined variable: javascript"
I have problem when I want to use `$javascript->link('prototype')` in the `default.ctp` layout. It returns:
> Undefined variable: javascript [APP\views\layouts\default.ctp, line 6]
I also added this code into **app_controller.php** :
<?
class AppController extends Controller {
var $Helpers = array('Html','Javascript','Ajax','Form');
}
?>
The file `prototype.js` is already in `webroot/js` folder.
Where is the problem?
|
I have had this problem many times. It's usually either caused by the controller code being overwritten somewhere or some weirdness happening with Cake's automagic stuff. If you remove all of your helpers and then add them one by one it will probably work eventually.
Another perfectly valid way of generating JavaScript links is by using the following which doesn't access the $javascript variable:
echo $html->script(array('prototype'));
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "cakephp"
}
|
Windows CMD to find all .py files in subfolders exluding one
I had a command to search for all .py files end execute pep8 check on every file:
FOR /R %%i IN (*.py) DO pep8 %%i
Now, I need to execute the same command on all .py files, except those located in "migrations" directory
I tried everyting i found and nothing helps. I tried this but it still searches in migrations directories:
set "logDirectory=C:\workspace"
for /f "delims=" %%a in ('dir /a-d/b/s "%logDirectory%"^|findstr /riv "^.*[\\][^\\]*migrations[^\\]*$"') do pep8 %%a
Running Windows.
|
Don't use `FINDSTR` \-- that command is useful to filter files based on their _contents_. Use `FIND` instead:
for /f "delims=" %%a in ('dir /b/s "%logDirectory%\*.py" ^| find /v /i "\migrations\"') do pep8 %%a
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "windows, for loop, cmd"
}
|
How can I remove vim-plug, so I can migrate to Packer?
I upgraded to neovim, and I want to remove `vim-plug`. It randomly changes my style settings (literally turns on `syntax on` for no reason other than the author's preference), and it's not as nice as newer neovim plugin managers like Packer which are written in lua. I don't see what's pulling it in. How can I remove `vim-plug`.
|
* With vim, `vim-plug` is installed in
~/.vim/autoload/plug.vim*
* With neovim `vim-plug` is installed in
~/.local/share/nvim/site/autoload/plug.vim*
Simply removing those file will stop it from loading. You'll furhter want to delete the place where the plugins are stored, `~/.config/nvim/plugged/`.
You can then proceed with installing Packer
|
stackexchange-vi
|
{
"answer_score": 3,
"question_score": 2,
"tags": "plugin vim plug, packer"
}
|
set a data range in column 0 of an mts in Rstudio
I am new in Rstudio having a question. I have a created a multivariate ts using 3 ts of the same sample period, using the ts.union() function. So when I open this mts object I have in column 0 the number of the observations and my variables in the following columns. I wonder if it's possible to assign quarterly time periods in column 0 instead of having the number of the obs. This will give me a perfect look of my data set. To be more specific my quarterly range is 1971:Q1 up to 2014:Q3. Thank you very much.
|
If freq=4 is used it will assume it is a quarterly series:
n <- 4 * (2014 - 1971 + 1) # number of rows
ts(cbind(1:n, 1:n), start = 1971, freq = 4)
## Series 1 Series 2
## 1971 Q1 1 1
## 1971 Q2 2 2
## 1971 Q3 3 3
## 1971 Q4 4 4
## 1972 Q1 5 5
## ...snip...
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "r, time series"
}
|
Should I use Django's contrib applications or build my own?
The Django apps come with their own features and design. If your requirements don't match 100% with the features of the contib app, you end up customizing and tweaking the app. I feel this involves more effort than just building your own app to fit your requirements.
What do you think?
|
It all depends. We had a need for something that was 98% similar to contrib.flatpages. We could have monkeypatched it, but we decided that the code was so straightforward that we would just copy and fork it. It worked out fine.
Doing this with contrib.auth, on the other hand, might be a bad move given its interaction with contrib.admin & contrib.session.
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 3,
"tags": "python, django, django contrib"
}
|
Counting the depth of loops
I am not sure whether this question is suited for SO or not. I will delete if it is not.
I have to review a few KLOC of code. As a part of it I have to find out the depth of loops and condition checking. [Please see the examples below]
If it is more than five means I need to note it down.
My question is "Is there any tool that could do this for me?" I did searching the google, but did not get an answer.
Ex 1 : `for {}` // Block depth 1
Ex 2 : `for { if () {} }` // Block depth 2
Ex 3 : `for () { for () { if() {} } }` //Block depth 3
|
Program that simply counting
//>prog file
//>prog file max_depth
#include <stdio.h>
#include <stdlib.h>
#define DEPTH_MAX 5 //no count top level
int main(int argc, char *argv[]) {
FILE *fp;
int depth_max = DEPTH_MAX;
if(argc > 1){
if(NULL==(fp = fopen(argv[1], "r"))){
perror("fopen");
exit( EXIT_FAILURE);
}
} else {
fp = stdin;
}
if(argc == 3)
depth_max = atoi(argv[2]);
int ch, level = 0;
size_t line_no = 1;
while(EOF!=(ch=fgetc(fp))){
if(ch == '\n'){
++line_no;
} else if(ch == '{'){
if(++level > depth_max)
printf("found at number of line : %zu\n", line_no);
} else if(ch == '}'){
--level;
}
}
exit(EXIT_SUCCESS);
return 0;
}
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 3,
"tags": "c"
}
|
Is there any way, given user permission, for an android app to start on its own at a scheduled time in the future?
As the title suggests, is there any way to have an Android application be schedule to start on its own at some time in the future. For example, is it possible within the Android API for a developer to write an application that might initiate at 7am if previously scheduled by the user?
|
You can use the Alarm Manager.
> This class provides access to the system alarm services. These allow you to schedule your application to be run at some point in the future.
<
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "android, alarm"
}
|
iOS kernel overview!
I need an overview of the iOS architecture (Process management, system memory management, kernel) (just an overview).
|
iOS is very similar to Mac OS X at the kernel level. The major differences would revolve around sandboxing, application privileges, etc. If you're curious about stuff that isn't necessarily iOS-specific, the Kernel Programming Guide provides an overview for a lot of Mach and BSD concepts, like the virtual memory system, how thread scheduling works, etc.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "objective c, ios"
}
|
MathML - left subscript and superscript
How to write left subscript and superscript preserving correct syntax of MathML? I mean something like this:
!left sub- and superscript
Thanks for the hints.
|
Use `<mmultiscripts>` \- see < for details. In your case, it's:
<mmultiscripts>
<mi>a</mi>
<mprescripts/> <mi>c</mi> <mi>b</mi>
</mmultiscripts>
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "mathml, subscript, superscript"
}
|
How to set currency format for textbox?
I want enter numbers into textbox and textbox would convert automatically these number into currency.(12,345,654)
I can use FilteredTextBoxExtender
<ajaxToolkit:FilteredTextBoxExtender ID="ftbe" runat="server"
TargetControlID="TextBox3"
FilterType="Custom, Numbers"
ValidChars="," />
But i want to automatically add commas when user enters number.
|
I use javascript code.
function Comma(Num) { //function to add commas to textboxes
Num += '';
Num = Num.replace(',', ''); Num = Num.replace(',', ''); Num = Num.replace(',', '');
Num = Num.replace(',', ''); Num = Num.replace(',', ''); Num = Num.replace(',', '');
x = Num.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1))
x1 = x1.replace(rgx, '$1' + ',' + '$2');
return x1 + x2;
}
<asp:TextBox ID="aPriceTextBox" runat="server" Width="100px" onkeyup = "javascript:this.value=Comma(this.value);" />
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 1,
"tags": "javascript, asp.net"
}
|
Display template javascript array
Have an item display template in SharePoint 2013. The returned property has multiple entries and I'm trying to format them with a pipe between them.Here is the code that I put in the html file.
function makePretty(prop){
var tags = prop.split("\n");
for(var i = 0;i<tags.length;i++){
var str=tags[i];
...
For some reason when the html file is uploaded and processed into js it adds quotes to the str assignment.
var str="tags[i];"
Otherwise it all works, I just end up with output literally like this.
tags[i]; | tags[i]; | tags[i];
When I expected something like this
My tag1 | Tag2 | Value of tag 3
Any idea what is going on? How do I put that kind of function into a display template and tell SP to leave it alone?
|
Not sure if it is the only or correct answer, but we took the same code outside of a function and it works just fine. So
var tags = prop.split("\n");
for(var i = 0;i<tags.length;i++){
var str=tags[i];
...
Evidently display templates don't want to let functions have ambiguously typed things?
|
stackexchange-sharepoint
|
{
"answer_score": 0,
"question_score": 0,
"tags": "2013, display template"
}
|
OpenDJ - Intercepting LDAP Events
I use OpenDJ as the authentication module of a Glassfish server that hosts some EJB 3.1 beans. I currently use OpenDJ LDAP SDK in order to programmatically add or modify users, and I need my service to be informed of _every_ LDAP event.
How can I respond to LDAP events programmatically? (e.g., a user was added or removed, a user was added or removed from a certain group / organizational unit)
Thanks!
|
It's possible to get notifications of all updated entries (or only a filtered set of entries) using LDAP Persistent Search control which is supported by both OpenDJ and the LDAP SDK.
Kind regards,
Ludo
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "java, ldap, opends"
}
|
java.lang.NoClassDefFoundError when running libgdx app on Android
I got this error when running my libgdx project on Android, the Desktop project works fine.
FATAL EXCEPTION: GLThread java.lang.NoClassDefFoundError: com.alexdev.oldcrt.PostProcessing
PostProcessing is a new class that I've created, here I add pictures of Java Build Path. Thanks in advance.
<
<
|
I fixed it adding in the android-project's build path all the projects that were in the main-project, and mark to exporting them. The reason for this is that an Android Eclipse project no longer adds the sources of referenced Java projects to the APK it compiles.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "java, android, libgdx, noclassdeffounderror"
}
|
Prolog print numbers from 1 to N?
Assume the user gives an input N to the function, how would I print these numbers from 1 to N (recursively or other wise).
example
print_numbers(40).
->1
->2
->…
->40
|
You want to print numbers from 1 to N so print_numbers(N) can be translated in print_numbers(1, N).
Now what is print_numbers from X to Y ?
print_numbers from X to Y is print(X) and print_numbers from X+1 to N!
In Prolog, you will get :
print_numbers(N) :-
print_numbers(1, N).
% general case X must be lower than Y
print_numbers(X, Y) :-
X =< Y,
writeln(X),
X1 is X + 1,
print_numbers(X1, Y).
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "prolog"
}
|
Icons on mail sender in Gmail
In this little bit of screenshot from the GMail web client, you can see that the name of the sender of one message (chess.com) has a small icon associated with it (a chess piece.) It is not the favicon for the domain (although it's quite similar to it,) and I've never set up anything special on my end, nor added chess.com to any address book or other client-side database. Does anyone have any idea how this is implemented, and how it might be possible for a sender of email to include an icon like this?
!Screenshot of mail client showing icon
|
It could simply be that the character is a character in some font.
See if you can select it like you would a character.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "gmail"
}
|
Preposition needed: did not survive a certain timepoint
I have a sentence as follows. This should say that the patients who died during the observation period were excluded from analyses. Should I use a preposition after "survive"? I did a research but found nothing useful.
> Patients, who did not survive at the end of the observation period, were excluded from the analysis.
> Patients, who did not survive beyond the end of the observation period, were excluded from the analysis.
> Patients, who did not survive the end of the observation period, were excluded from the analysis.
|
Patients who did not survive the observation period were excluded from the analysis. (No commas because it's a restrictive appositive, meaning you need this information to understand the sentence.)
|
stackexchange-english
|
{
"answer_score": 1,
"question_score": 1,
"tags": "prepositions, british english, academic writing"
}
|
CentOS 7 server rebooted itself into rescue mode - how can I find out why?
I've switched it back to regular boot and it seems to boot up fine.
So why did it reboot?
Running "last" doesn't even show a log OF a reboot. What does that suggest?
When I try "smartctl -a /dev/sda1" I get "SMART support is: Unavailable - device lacks SMART capability."
Seems odd for what claim to be 15k HP drives. Maybe it's due to the RAID setup though?
It's a oneprovider.com box, and came described as "3x 4TB HW RAID 5".
Help?
Thank you!
|
As it happens in this instance, the datacenter had rebooted the box due to abuse notifications, which were based on previous activity of the IP address before I'd got it...
|
stackexchange-serverfault
|
{
"answer_score": 0,
"question_score": -1,
"tags": "raid, hard drive, centos7, diskmanagement, smart"
}
|
Rename string values in a column when multiple conditions are not met
I have an age range data column that looks like this:
data <- c("<18", "956", "675", "18-30", "31-50", "50+", "543" "Unknown")
Now, I want to rename the all whole number characters as "Unknown" with the new column looking like:
data <- c("<18", "18-30", "31-50", "50+", "Unknown")
I have tried using this:
if(data$age_range !="<18" || data$age_range !="18-30" || data$age_range !="31-50" || data$age_range !="50+")
{data$age_range2 = "Unknown"}
But it renames all the values to `"Unknown"`
I also tried using `ifelse`, but it's not working either. I'm quite new to R and would appreciate all the help I can get.
Thanks in advance!
|
You can convert data to numeric and rename whole numbers as "Unknown".
data <- c("<18", "956", "675", "18-30", "31-50", "50+", "543", "Unknown")
data[which(!is.na(as.numeric(data)))] <- "Unknown"
data
**Result**
[1] "<18" "Unknown" "Unknown" "18-30" "31-50" "50+" "Unknown" "Unknown"
If you want to keep only one "Unknown",
sort(unique(data))
# [1] "<18" "18-30" "31-50" "50+" "Unknown"
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "r"
}
|
Angular warning: swal is deprecated
I get the following message on building my project (Angular 9.0.5, sweetalert2 : 7.22.2):
> swal is deprecated: swal() overload for legacy alerts that use { useRejections: true }.
and it points to the following line, and other instance of similar code
private promptFormError(title: string, errorMessage: string) {
this.companyHelperService.errorPopup(title, errorMessage)
.catch(swal.noop);
}
I do understand that the issue is coming form the `swal.noop` part. I tried looking into the doc linked to swal through IntelliJ, but I did not find anything specific related to this matter.
Can anybody please point me to a documentation, or explain to me how I am supposed to refactor this properly?
P.S: Is this a "real warning"? I would like to fix and stop ignoring it anyway
|
< See Breaking change #1.
As for the "real warning", the answer is yes, since `swal.noop` has been removed in v8. That means your code will break if you ever migrate to version 8.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "angular, typescript, deprecation warning"
}
|
Dynamically set value of input box
I have an aspx page with an input textbox control for which i want to set a value. I want it so that the value dynamically changes based on the current text of the textbox when the form is submitted. Does anyone know how to do this without jquery?
|
I think this is what you are asking for, not sure though:
**JavaScript:**
function ChangeValue(currentTxtBox, newValue)
{
var otherTxtbox = document.getElementById('<%=otherTxtbox.ClientID%>');
otherTxtbox.value = currentTxtBox.value;
}
**Markup:**
<asp:textbox id="bla" runat="server" onchange="ChangeValue(this)" />
<asp:textbox id="otherTxtbox " runat="server" />
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "javascript, asp.net"
}
|
RxJs 6: Get ConnectableObservable from Observable
Angular 6 requires an update to RxJs 6 and with that RxJs update the `Observable.publish()` function is gone. I found a `publish` operator in `RxJs/operators` but I'm having trouble figuring out how to use it.
How could this RxJs 5 code be rewritten to work with RxJs 6?
`const myConnectableObservable = this.getObservable().publish()`
|
import { ConnectableObservable } from "rxjs"
import { publish } from "rxjs/operators";
const myConnectableObservable: ConnectableObservable<MyClass> = myService.getObservable().pipe(publish()) as ConnectableObservable<MyClass>;
Special thanks to @cartant
|
stackexchange-stackoverflow
|
{
"answer_score": 10,
"question_score": 8,
"tags": "angular, rxjs, rxjs6"
}
|
Visual Studio 2015 produces sameApp-VC.exe but try to execute sameApp.exe
My Environment:
IDE: Visual Studio 2015 Community
OS: Windows 8.1 pro
I am trying to use old Visual C++ project (prepared around 2010).
VisualStudio 2015 automatically updates the project file for 2015 version. And I can build the exe file.
However, I have one problem in debugging.
When I try to use "Local debugger", I have following error.
Program xxx\someApp.exe cannot be started.
File not found.
If I check the files, I found the following
* VS2015 produces a file named "someApp-VC.exe"
* VS2015 try to use "someApp.exe" in local debugger.
I am checking the options to avoid this problem, but not successfull up to now.
I would like to know the workaround for this.
|
I found the setting in the following menu.
[Project]->[property of someApp]->[Configuration Properties]->[Linker]->[Output File]
I changed from "Debug/someApp-VC.exe" to "Debug/someApp.exe".
Then the problem was solved.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "visual studio"
}
|
How does the Architect think Neo will be swayed by his revelation?
The Architect reveals to Neo that Trinity is about to die. How does he think Neo will be swayed by his revelation?
|
I think that Neo represents the accumulation of flaws in the system, that's Neo's compassion for humanity was expressed as love for Trinity, and coupled with the fact that the Architect made a calculation error. The Architect calculated that the chances that Neo would rationally choose the _desired_ door would be improved if Trinity was certain to die. However, Neo did not believe that Trinity's death was certain, and felt he could and needed to save her, couldn't live without her, and so made an irrational decision which is so common among humans when faced with a choice between what's right and what's _love_.
Neo chose love over rational behavior. That was the Oracle's gambit.
|
stackexchange-scifi
|
{
"answer_score": 6,
"question_score": 3,
"tags": "the matrix"
}
|
add blank space before image
I'm drawing two images, one on top and one in the bottom, and I want them to be aligned. One of them has some extra blank space one its left side, so I need to realign it manually:
\begin{minipage}{9em}
\includegraphics[height=3em]{images/img1.png} \\
\includegraphics[height=3em]{images/img2.png}
\end{minipage}
I tried to add `\hspace{some_number}` to either one of them to see the effect, but nothing happened. What should I use?
Thanks.
|
`\includegraphics` of package `graphicx` knows option `trim=<left> <bottom> <right> <top>`. Default unit is `bp`:
\includegraphics[trim=10 0 0 1mm]{img.png}% trims 10bp from the left and 1mm from the top
Or crop the image with image editing software.
|
stackexchange-tex
|
{
"answer_score": 2,
"question_score": 1,
"tags": "spacing, graphics"
}
|
Can you identify this resistor or resistance?
I was just cheking my batteries and noticed that one doesn't charge. When I opened it, I found that this resistor is broken and is not allowing the charge to travel to the battery.
I would like to buy one but I don't know how to look for it.

Don't know why it does that but it fixed my problem. Perhaps, in order to maintain those breakpoints, it was not refreshing my js files.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 3,
"tags": "javascript, macos, google chrome, caching"
}
|
Prove that the sum of lengths of two segments is minimum if point $M$ ....
Two points $A$ and $B$ are in the same semi-plan(take into consideration the line $d$), and their position is arbitrary. Point $A_1$ is the reflection of $A$. Prove that the sum of distances $MA+MB$ is minimum if point $M$(M is an arbitrary point on line $d$) belongs to $BA_1$ .
By intuition I suppose that I somehow have to prove that the measure of angle between the segments $AM$ and $MB$ is $90$ degree, but I don't have any idea. I hope you'll help me find the solution. Thank you!!!
!enter image description here
|
The angle between the segments $\overline{AM}$ and $\overline{MB}$ doesn't have to be $90^\circ$. Use that the straight line between two points is the shortest path betweeen them and that the distances from $M$ to $A$ and $A_1$ are the same.
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 2,
"tags": "geometry"
}
|
Magento: Hello World Page
I am currently dabbling in Magento and I want know how I can create a blank Hello World file whilst still including header, footer etc. I have read How to create a simple 'Hello World' module in Magento? \- however I feel that this is too much for a static page.
I want to create _www.site.com/magentolocation/helloworld.php_
I want a blank PHP file and rather go down the module and MVC approach can I not just do:
<?php
include magconfig;
mag->header;
echo 'hello world' // or other static html
mag->footer;
?>
Simple.
|
I'm sure there might be a prettier way but here is a quick snippet for you:
<?php
require_once ('app/Mage.php');
umask(0);
Mage::app('default');
Mage::getSingleton('core/session', array('name' => 'frontend'));
$Block = Mage::getSingleton('core/layout');
$head = $Block->createBlock('Page/Html_Head');
$head->addCss('css/styles.css');
$head->addJs('prototype/prototype.js');
$header = $Block->createBlock('Page/Html_Header');
$header->setTemplate('page/html/header.phtml');
$footer = $Block->createBlock('Page/Html_Footer');
$footer->setTemplate('page/html/footer.phtml');
?>
<html>
<head>
<?php echo $head->getCssJsHtml(); ?>
</head>
<body>
<?php
echo $header->toHTML();
echo 'hello world';
echo $footer->toHTML();
?>
</body>
</html>
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "php, magento"
}
|
Error in rbind(deparse.level, ...) : invalid list argument: all variables should have the same length
I am trying to use "rbind" to get the result but I am being shown an error "Error in rbind(deparse.level, ...) : invalid list argument: all variables should have the same length"
pm2 <- function(directory, id=1:322)
{
files <- list.files(path = directory, full.names = TRUE)
df <- data.frame()
for (i in 1:322)
{
fil <- read.csv(files[i])
df <- rbind(df, fil)
}
df2 <- data.frame(matrix(nrow = length(id), ncol = 2))
colnames(df2) <- c("id", "nobs")
for(i in id){
rbind(df2, c(df[[id[i]]],count((df[[id[i]]])),na.rm = TRUE))
}
df2
}
pm2("specdata", 1:10)
|
It sounds like your individual data frames do not have the same width (number of columns)
An easy fix is to use `plyr::rbind.fill` which will fill in missing columns with `NA` (although you might want to rethink why you're rbinding data frames of different widths). See the reproducible example below
test <- mtcars[1:2,]
ncol(test)
# [1] 11
modified <- test[,1:9]
ncol(modified)
# [1] 9
rbind(test, modified)
# Error in rbind(deparse.level, ...) :
# numbers of columns of arguments do not match
library(plyr)
rbind.fill(test, modified)
# mpg cyl disp hp drat wt qsec vs am gear carb
# 1 21 6 160 110 3.9 2.620 16.46 0 1 4 4
# 2 21 6 160 110 3.9 2.875 17.02 0 1 4 4
# 3 21 6 160 110 3.9 2.620 16.46 0 1 NA NA
# 4 21 6 160 110 3.9 2.875 17.02 0 1 NA NA
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 5,
"tags": "r, rbind"
}
|
How can I run qemu with KVM over ssh?
When I run `qemu -cpu kvm64 -snapshot -hda binary.img` at a local console, the image boots and runs as I expect. However, when I log in via `ssh -C -X`, I see:
$ qemu -cpu kvm64 -snapshot -hda binary.img
open /dev/kvm: Permission denied
Could not initialize KVM, will disable KVM support
qemu: pci_add_option_rom: failed to find romfile "pxe-rtl8139.bin"
(The `pxe-rtl8139` message is there when run locally as well, it doesn't seem to matter.)
Why does using SSH make a difference? How can I run `qemu` over SSH without needing root permissions?
Both machines are Ubuntu 11.10, qemu and qemu-kvm are 0.14.1+noroms-0ubuntu6.2
|
After additional information in the comments, You need to add your user to the kvm group.
|
stackexchange-askubuntu
|
{
"answer_score": 4,
"question_score": 4,
"tags": "ssh, qemu"
}
|
Why are the same notes written on different staves?
I am learning Chopin's Prelude No. 15 in D flat Major, and I was curious as to why the Db F notes in the bass are written in the lower stave in the first bar but then the upper stave in the second bar. What is the purpose/implication of this?
Also am I right in assuming that in the second bar, the Db and F notes are joined to the bass notes (instead of the Db) to indicate that it is to be played with the left hand? Or does it imply something else?
 hand:
$
I wanted to know orders of all subgroups of the group $AGL(1,16)$ (of order 240). Indeed, regarding to the problem mentioned in < we are looking for the smallest group(s) which does not have the property.
***** Now, is it true that there exist subsets $A$, $B$ of $AGL(1,16)$ such that $|A|=6$, $|B|=40$ [resp. $|A|=10$, $|B|=24$] and $AGL(1,16)=AB$?
|
You can find the answer in GAP or Magma with a few seconds typing. It is $$\\{1, 2, 3, 4, 5, 8, 12, 15, 16, 48, 80, 240 \\}.$$
So there are no subgroups of orders $6, 10, 20, 24, 30, 40, 60, 120$. But you should be able to prove that yourself!
|
stackexchange-math
|
{
"answer_score": 4,
"question_score": 3,
"tags": "group theory, finite groups"
}
|
¿Cómo obtener la fecha actual (dd, MM,HH, mm) en diferentes variables en java?
Necesito obtener por separado cada componente de la fecha actual, ya que necesito por ejemplo concatenar a un String el día a dos digitos, en otro String concatenar solo el mes, en otro String las horas y en otro String los minutos por ejemplo
tengo este formato , pero no se como obtener los componentes de toda la fecha actual en diferentes variables
Date todayDate = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String fechaActual = sdf.format(todayDate);
|
No se que versión de java usas, pero a partir de java 8 en adelante puedes usar el API `LocalDateTime`.
Ejemplo:
LocalDateTime hoy = LocalDateTime.now();
System.out.println("El día es: "+hoy.getDayOfMonth());
System.out.println("El mes es: "+hoy.getMonthValue());
System.out.println("El año es: "+hoy.getYear());
System.out.println("Minutos: "+hoy.getMinute());
|
stackexchange-es_stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "java, date, datetime, date format"
}
|
Android Select File Intent
I'm trying to pick a file via an Intent. What I tryed till now is this:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(intent, FILE_SELECT_CODE);
But with this, I can only pic Photos with the galery app.
My goal is to pic ANY file via the standard file manager of Android/Samsung.
This didn't work either:
String manufactures = android.os.Build.MANUFACTURER;
if(manufactures.equalsIgnoreCase("samsung"))
{
Intent intent = new Intent("com.sec.android.app.myfiles.PICK_DATA");
intent.putExtra("CONTENT_TYPE", "*/*");
startActivityForResult(intent, FILE_SELECT_CODE);
}
Thx for your help!
|
> My goal is to pic ANY file via the standard file manager of Android/Samsung.
Android does not have a "standard file manager".
If your `minSdkVersion` is 19 or higher, you are welcome to use the Storage Access Framework (e.g., `ACTION_OPEN_DOCUMENT`), which is the closest thing that Android now has to a "standard file manager".
Otherwise, you are limited to whatever `ACTION_GET_CONTENT`-supporting apps that the user has installed, or creating your own file-selection UI, or using one of many existing libraries for selecting files.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "java, android, file, android intent"
}
|
Considering 27" iMac. Can I use it as a TV?
I may be considering to get the iMac.
I don't own a TV, but I would love to be able to use it as such. I understand it has a DisplayPort input for these types of purposes.
What would I need to get to get my Wii and analogue TV (PAL) hooked up to this?
|
The best way to get TV hooked up to a Mac is through a TV Tuner. The best TV Tuners for Mac are by far the EyeTV tuners. The TV tuner could also be used to hook up to your Wii, however that is a bit impractical. Instead consider buying an adapter from RCA to Mini-Display Port to use your iMac as a Monitor for the Wii.
|
stackexchange-apple
|
{
"answer_score": 5,
"question_score": 6,
"tags": "imac"
}
|
Android - Kill camera process in the background
Nowadays how does it work to kill the camera process in the background?
I tried a couple of solutions:
val pid = Process.getUidForName("camera")
Process.killProcess(pid)
or
activityManager.killBackgroundProcesses("com.android.camera");
I'm also using the kill background process permission in my Manifest: `android.permission.KILL_BACKGROUND_PROCESSES`
I also tried to figure out how I could get all the background processes running with `activityManger.runningAppProcesses` but this code only return an array with my current active app, I can't see the camera or anything else.
Although with the `PackageManager` I managed to get all app installed on the phone and check if they are flagged has "stopped" or not so I can filter which one is running or not. But still the `Process.killprocess` is not working. I guess I'm missing some permissions to make it work.
|
You can not do it with the regular app, and one thing you can do it try implementing the device manager. you can use DeviceAdministration class to **control the camera source** (block and unblock). Check out this Github repo with an example.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "android, kotlin, android camera, background process, kill process"
}
|
Оформление длинной фразы в диалоге
Следующая ситуация: между персонажами книги происходит диалог. Затем один из них начинает рассказывать длинную историю. Естественно, она не может идти сплошным абзацем, но как её пунктуационно оформить? Смущает то, что если просто продолжить писать с новой строки, то новый абзац можно спутать с речью от автора (различие по контексту считаю недостаточным критерием для разграничения).
Есть два варианта, которые приходят в голову:
а) текст, заключённый в кавычки;
б) косвенная речь, вроде: «сказав это, он продолжил, упомянув, что»… ну и т.п. по такому же принципу.
Однако интересует именно пунктуационное оформление подобного диалога.
|
Цитирую правило:
Если передается длинный рассказ со многими абзацами, то тире ставится только перед первым абзацем (ни перед промежуточными абзацами, ни перед последним тире не ставится). Например:
/ -- Это было давно... - начал свой рассказ Петров.
/ К нам в город приехал...
/ (Продолжает рассказ) и т. д.
/ Вот что я хотел вам рассказать, - закончил Петров.
Косыми чертами я отметила абзацные отступы - они тут почему-то не выставляются.
Речь одного и того же лица не может оформляться в одном диалоге то с абзаца, то в подбор (то есть с кавычками). Такое сочетание возможно, если рассказчик в диалоге пересказывает диалог других лиц, тогда это позволяет выделить диалог в диалоге.
В вашем случае надо как-то намекнуть на конец рассказа.
|
stackexchange-rus
|
{
"answer_score": 4,
"question_score": 0,
"tags": "диалог, пунктуация"
}
|
Notepad ++ How to remove day and month from date?
i have text like this :
EU 1097-2002-25-06-2002.pdf
EU 1255-2007-26-10-2007.pdf
EU 1513-2002-EC-27-06-2002.pdf
EU 2001-18-EC-22-09-2003.pdf
EU 2001-47-EC-15-01-2003.pdf
in last part of any row the full date is apear
i need to remove day and month without year from this lines
EU 1097-2002-2002.pdf
EU 1255-2007-2007.pdf
EU 1513-2002-EC-2002.pdf
EU 2001-18-EC-2003.pdf
EU 2001-47-EC-2003.pdf
|
* Find what : `-\d{2}-\d{2}(?=-\d{4}[.]\w+)`
* Replace with :
* Search mode : Regular Expression
It tries to find : dash & 2 digits & dash & 2 digits.
But only if those are followed by : dash & 4 digits & extension.
Since only the day and month part get matched, replacing with nothing will remove them.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -2,
"tags": "regex, notepad++"
}
|
aa-genprof will not scan to create profiles!
I'm currently messing around with apparmor and creating profiles etc. When I run aa-genprof and try to scan I am presented with following error.
ERROR: Include file /etc/apparmor.d/abstractions/lightdm_chromium-browser not found
I get the same error regardless of what executable I give.
Running ubuntu 17
|
It seems that you should install `lightdm` package to get this file
with `sudo apt-get install lightdm`.
Below is a clue:
$ dpkg -S lightdm_chromium-browser
lightdm: /etc/apparmor.d/abstractions/lightdm_chromium-browser
|
stackexchange-askubuntu
|
{
"answer_score": 1,
"question_score": 0,
"tags": "apparmor"
}
|
Find words in lists using python by entering part of them
Given the list:
my_list = ['barrow', 'yellow', 'green', 'red', 'mellow']
I'd like to find the words inside that list that would match '****ow' ('*' is any letter). This should return 'barrow', 'yellow' and 'mellow' (words included in thet list, formed by six letters whose two last letters are 'ow')
|
Another way to approach your problem is to use fnmatch, provided your hay stack is a list of string. In case if its not, you may have to do a pre-convertion to a string
>>> import fnmatch
>>> my_list = [2345, 3245, 2343, 8746]
>>> fnmatch.filter(map(str, my_list), "2*4*")
['2345', '2343']
>>> my_list = ['barrow', 'yellow', 'green', 'red', 'mellow']
>>> fnmatch.filter(map(str, my_list), "*ow")
['barrow', 'yellow', 'mellow']
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "python, list, find"
}
|
Local eigenvectors frame of a isometric immersion
I have a little (possible dumb) technical question about local eigenvectors frame of a isometric immersion.
Let $N^n$ a smooth manifold and $(M^{n+1},g)$ a smooth Riemannian manifold. Consider $\phi: N\to M$ a isometric immersion and let $S$ be the shape operator of $N$.
Given $p\in N$, we can always assume that exists a local orthonormal frame $\\{e_1,e_2,\cdots,e_n\\}$ on a neighborhood of $p$, such that diagonalizes $S$? Or we need to put the condition that $p$ is not a umbilical point?
Thanks!
|
At each point $p$, of course, there's always an orthonormal basis for $T_pN$ diagonalizing $S_p$. You may likely have local smoothness issues whenever there are repeated eigenvalues. However, in dimension $n>2$, it's not good enough to say there are no umbilic points; you actually need to require distinct eigenvalues.
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 1,
"tags": "geometry, differential geometry, riemannian geometry"
}
|
Why create a reverse DNS record for every device that connects to a wireless network?
There's this network I connect to often. After some experimentation, I figured out that when you connect to the network, the DHCP server assigns you an FQDN that usually follows the scheme `<your-hostname>.subdomain.sld.tld` (obviously the DHCP server also assigns you an IP address). A DNS record is created for you that maps your FQDN to your current IP address. In addition to that, a reverse DNS record is created mapping your IP address to your hostname. When you leave the network (when your lease expires), both DNS records are deleted.
My question is, what's the purpose of having a reverse DNS record for all devices on the network? They're all private IP addresses. The only thing it does AFAICS is make it easy to enumerate all the devices (hostnames) on the network - just run a reverse scan of 10.0.0.0/8 (and/or 192.168.0.0/16, and/or 172.16.0.0/12).
|
It is a kind of zero-configuration networking, probably done by a small `DHCP/DNS/TFTP` server called **dnsmasq**. The `PTR` record allows you to see the hostname of other machines connecting to your computer, which might be meaningful on a small network, where people know each other.
As for scanning the network, other technologies announce on broadcast or multicast the presence of computers and their hostnames:
1. NetBIOS in the Windows world (yes, it is still alive),
2. LLMNR/SSDP in the Windows world,
3. mDNS/DNS-SD in the Apple/UNIX world,
4. ARP broadcasts might give a hint on which IPs are active.
|
stackexchange-serverfault
|
{
"answer_score": 1,
"question_score": 0,
"tags": "domain name system, dhcp, internal dns, reverse dns"
}
|
How to connect to LDAP from Powershell in another server
I have to query my Active Directory from another windows server using PowerShell through LDAP. I got LDAP connection details, port number, login credential. However, after googling for hours I couldnt find a soultion to connect PowerShell to LDAP. I tried below cmdlet but all returned the error "the term ** is not recognised as the the name of a cmdlet".
New-AdfsLdapServerConnection
Test-LDAPConnection
Can someone please help. I want to connect to my LDAP and run a simple command like
Get-ADGroup -Filter 'Name -like "Sec-abc-xyz-123-U"'
later I want to write my full Powershell script and then use Task scheduler to automate my powershell script. Can someone please let me know how I could connect to LDAP?
|
As @Santiago Squarzon suggested, you need to install RSAT to use the AD PS Module
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "powershell, active directory, ldap"
}
|
Get recommended video with API 3.0
I've read the Youtube API documentation and I've read that the GData 2.0 API had the recommended videos:
I've to use the API 3.0, but I wasn't able to find anything about recommended: does anyone know a way to retrieve them?
Thanks
|
Call the url:
token]&part=[your parts]&home=true
the response is the recommended videos.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 2,
"tags": "ios, youtube, youtube api"
}
|
When using a path string in a shell script, it would be trans to a string containing children
Here is some bash code
path='*'
echo $path
If I execute the code in terminal directly, the output is
*
But if I put it in a shell script e.g., **test.sh**. Then I execute the **test.sh** , the output will be like this
test.sh file1 file2 file3
I got a string contains all items under the path.
Why the two outputs is different? If I want the second output to be the first one, which means do not trans a path string when I use it, what should I do?
|
I tested a little. You could change your script to this:
path='*'
echo "$path"
and it will print * instead of files if you run it as a bash script.
Seems echo can be used as a alternative of `ls` command:
`echo *` means list all files under current folder.
`echo *.jpg` will list all files with jpg as suffix, and if there is no such file in current folder, `echo *.jpg` will just print "*.jpg".
I think this answer should be posted as a comment, since I don't really know why `echo` command behave like this. But I do not have enough reputation to add comment, so...
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "bash, shell"
}
|
Is there a way to search for user defined strings in different outlook attachments using python?
Currently i am working on a project where i have to extract attachments and e-mails from outlook and check whether a user defined string present in them or not. I've completed the extraction part but still searching for a way to search for text/string within the attached documents. Is there a way to this by using python?
|
For Microsoft Office files you can:
1. Automate Office applications.
2. Use the open xml SDK if you deal with open XML documents only.
3. Use third-party libraries for dealing with documents.
It is up to you which way is to choose.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "python, full text search, ms office"
}
|
iPhone transition effect to reveal an updated version of the same view
So I have an app on the main page is details of the current date. The page has left and right buttons to move to previous and next dates and a table of info below. This all works.
However I want to add a swipe between the days, now doing the swipe control is easy and I have done that.
However I want to give the visual indication of a swipe. I am not changes views , I am simply refreshing the current view.
If you look at myfitnesspal (free app) , that swipes between dates in the same way I am after.
It scrolls off (a copy?) of the screen to one side , slides in the latest version to replace it.
I am at a loss on how to achieve such a simple effect without going for multiple views which unless I am misunderstanding would be over complex.
|
Use a UIPageControl, here is a tutorial of how to implement one using only two views: Cocoa with Love UIPageControl sample
Both views can be identical, (instances of the same Class, created programmatically or 2 CustomView outlets on IB)
This way you only need to update the view that's going to slide in the screen.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "iphone, transition"
}
|
MySQL query optimization: IN() vs OR
I've been reading, that MySQL has a problem with queries that use IN() statement - sometimes indexes can't be used. Is that really so, if I don't use a subquery?
Which approach is better? Is there a performance difference?
# 1
SELECT *
FORM `somewhere`
WHERE
`id` = 3
OR `id` = 5
OR `id` = 15
OR `id` = 56
OR `id` = 34
OR `id` = 47
# 2
SELECT *
FORM `somewhere`
WHERE
`id` IN (3,5,15,56,34,47)
|
The second approach is better. MySQL can optimize this.
> MySQL has a problem with queries that use IN() statement - sometimes indexes can't be used. Is that really so, if I don't use a subquery?
There can be a problem with IN when you write `IN(SELECT ...)`, but I don't think there is a problem with a simple list of values.
|
stackexchange-stackoverflow
|
{
"answer_score": 9,
"question_score": 7,
"tags": "mysql, query optimization"
}
|
What is Ol' George's Nail Wail?
This has been sitting on the bookshelf in my parents' house since I was a kid, and to this day, I still have no idea what it is or how to play:
!enter image description here
It was given to us by my grandma, and the best my dad can remember is that "it's a puzzle of some sort". He claims to have solved it once, but can't recall anything beyond that.
I tried Googling "Ol' George's Nail Wail" to no avail. Here are a couple more pics from other angles:
!enter image description here
!enter image description here
|
It looks like a "nail balance" puzzle. It is very similar to some of the results of this Google Image Search.
|
stackexchange-boardgames
|
{
"answer_score": 12,
"question_score": 13,
"tags": "puzzles"
}
|
Embedding flv (flash) player in windows forms
I'm trying to the the flv Flash player from here in a windows forms application. I currently have it playing 1 .flv file with no problems but I really need to be able to play multiple files. Has anyone had experienace of using the playlists that this control offers or is there a better way to do this?
|
Can you get the control to run the way you want it in a webpage/browser? If yes (and the problem is with winforms, I'd just embed it in a browser control. If no, I'd as the creators directly.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "c#, winforms, flash, flv, embedded flashplayer"
}
|
Как заполнить массив числами от 1 до Н?
Я изучаю Python. К примеру я вожу число '5', мне должен вывести ответ '1 2 3 4 5', или вожу 3, тогда ответ '1 2 3'. Так так сделать?
|
n = input('Введите число: ')
nums = list(range(1, int(n) + 1))
print(*nums)
Крайне рекомендую изучать по учебнику, так как для новичка очень важна правильная и систематизированная подача материала.
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "python"
}
|
Extract and calculate frequency of occurrence in column using R
I have a .csv file, which is like
COLUMN1 COLUMN2 COLUMN3 COLUMN4
1 a 12/16/17 1 1
2 b 15 1 2
3 c 18 1 3
4 d 12/15 4 5
5 e 13/12 1 5
How to count the times of a number x appears in COLUMN2? The result I expect is
12 15 13 16 17 18
3 2 1 1 1 1
|
We can use `scan` with `table`
table(scan(text=df1$COLUMN2, sep="/", what=numeric(), quiet = TRUE))
# 12 13 15 16 17 18
# 3 1 2 1 1 1
If the column is `factor`, convert to `character` and use it in `scan`
table(scan(text=as.character(df1$COLUMN2), sep="/",
what=numeric(), quiet = TRUE))
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "r, dataframe"
}
|
How do I use the axis as an anchor for horizontal alignment?
 -- (current page.south);
\end{tikzpicture}
\end{document}
;
$data = json_decode($json, true);
print_r($data);
?>
Output given is `{"EventTitle":"Game","EventBody":"body","EventDate":"20 November, 2016","EventType":"party"}`
Json Data posted is:
{"EventTitle":"Game","EventBody":"body","EventDate":"20 November, 2016","EventType":"party"}
Writing the json data in a variable and passing it to json_decode works but posting the same from the "php://input" returns a JSON data instead of associative array.
|
It looks like @tkausl is correct. The JSON you're receiving has been double-encoded. Since it's double-encoded, a temporary solution would be to double-decode it.
$data = json_decode(json_decode($json), true);
But the real solution is to figure out why it's like that to begin with and fix it (if it's yours to fix).
|
stackexchange-stackoverflow
|
{
"answer_score": 9,
"question_score": 2,
"tags": "php, json, ajax"
}
|
add an image and it span in multiple pages using itextsharp
How can I add a large image, that spans over in multiple PDF pages using iTextSharp. I have an image that exceeds the PDF page height and because of it, the image is not fully displaying in the PDF page. Image's last portion is missing.
|
Please check if this solves your issue:
Document oDocument = new Document();
oDocument.Open();
PdfPTable table = new PdfPTable(1);
table.WidthPercentage = 100;
PdfPCell c = new PdfPCell(image, true);
c.Border = PdfPCell.NO_BORDER;
c.Padding = 5;
c.Image.ScaleToFit(750f,750f); /*The new line*/
table.AddCell(c); // <-- Add the cell to the table
oDocument.Add(table);
I hope using `PDfPTable` will probably solve your issue.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": ".net, image, itext"
}
|
What is the right way to work with ISODate in Mongoose
I am trying to call a mongodb collection with mongoose but I am having trouble using dates in the call
const siteReviews = await Review.countDocuments({
'clientId': clientObj.ClientBrandID,
'siteSource': 'SomeSite',
'reviewDate':{
$gt:"2018-12-24T18:04:47.806Z",
$lt:"2019-04-03T17:04:47.806Z"
}
})
I know for a fact that I have data between these two dates but i get 0 back.I have also tried to use ISODate("") directly in the code but it is breaking
|
Actually, You have defined the `type` of the `reviewDate` field as `Date` in your schema and here you are passing it as `String`.
So basically you need to convert the `String` date to `Date` Object and can be easily done using **`moment`** library
const googleReviews = await Review.countDocuments({
clientId: clientObj.ClientBrandID,
siteSource: "SomeSite",
reviewDate: {
$gt: moment("2018-12-24T18:04:47.806Z").toDate(),
$lt: moment("2019-04-03T17:04:47.806Z").toDate()
}
});
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "node.js, mongodb, mongoose"
}
|
Detecting displacement of camera around something flat
What approaches could be to the subj problem? I mean, there is a camera, looking to a plane (say, a picture, list of paper). Initially, it's assumed to be placed right normally to surface. Then, it starts to move, and i want to recognize:
1) small translations, shifting image on surface
2) scalings of image due to camera moves up/down
3) small transformations, due to camera small rotations
Specifically, it'll be run on Android, so, free Android libs are preffered
Upd.: image on surface is not going to be apriori known, but it can be assumed to be black curves on white, say a text.
|
For sure openCV will help.. but there is gonna be quite a lot of work...
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "android, image processing, computer vision"
}
|
Unexpected render partial with locals behaviour
I have a partial with yeild blocks, which I set using content_for, when I render partial I am also trying to pass in locals. The locals never get picked up in the partial.
<%= render :partial => 'shared/block', :locals => { :cssclass => 'medium' } %>
When I try to access the partial using
<%= :cssclass %>
All I get is the bare "cssclass" as a string rather than the variable I have set it to. Can you not use content_for and render partial at the same time?
**Update** I tried rendering a partial with locals, no yield or content_for and the the values I setup while rendering the partial are getting picked up. Is there something I am missing?
|
use <%= cssclass %> instead of symbol. locals set a variable, not a symbol, and when you output symbol it is just converted to string.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "ruby on rails 3, partial views, yield, locals"
}
|
FMX.Grid.TColumn.CellControlByRow function
I tried to compile file FMXTee.Chart.Grid.pas from TeeChart 9 for XE10 that used CellControlByRow function in FMX.Grid.pas for the following code :
**with TColumnAccess(Columns[Col]).CellControlByRow(Row).BoundsRect.BottomRight do begin ... end;**
I get running well when using RAD XE10 Seattle, and now I tried with RAD XE10.1 Berlin but get error message : **[dcc32 Error] FMXTee.Chart.Grid.pas(1507): E2003 Undeclared identifier: 'CellControlByRow'**
Then I compare file FMX.Grid.pas from XE10 packages versus FMX.Grid.pas from XE10.1 packages, and there are a lot of differences especially CellControlByRow() function does not exist any more in FMX.Grid.pas from XE10.1.
Now, I want ask how to change the code that use CellControlByRow function so it will run in RAD XE10.1 Berlin ?
|
I would like suggest you replace the code below:
result:=TColumnAccess(Columns[Col]).CellControlByRow(Row).BoundsRect.BottomRight;
For next :
...
var tmp : TFmxObject;
begin
tmp:=TColumnAccess(Columns[Col]).CellControl;
result:=TControl(tmp).BoundsRect.BottomRight
...
The above code should fix the compilation problem you’re experiencing. Could you confirm that?
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "delphi, teechart, delphi 10 seattle, delphi 10.1 berlin"
}
|
How does Evade/Dodge/Block trigger?
I'm a bit confused on how it triggers. Can you _always_ use these, or do you have to take an action beforehand to use these (and if so do they count vs. all enemies of the turn or only vs. 1), ... ?
Rules system is: 4C (Four Color System): It is an OGL/public-domain successor to the old percentile Marvel RPG system (with enough changes to essentially be a 2nd edition).
|
You (always) declare/state your actions during the turn (abstract time that fits into a single comic book panel)
> A character can perform any action that would fit into a standard panel including attack, dodge, or move.
and act according to initiative (p. 21). You repeat that 6-step combat process until the combat is over.
Evade is for melee combat only, to see the different d% roll tables for block and evade read p. 26 (Advanced combat section), and p. 25 for dodging.
Dodging works, unless a failure, against:
> Anyone attacking you this turn
Blocking works, unless a failure, against:
> the attacker’s Brawn
Evade works, unless a failure, against:
> You successfully evade the attack
|
stackexchange-rpg
|
{
"answer_score": 4,
"question_score": 9,
"tags": "actions, four color system"
}
|
Strange location on my network
I am not sure if this is the right place to ask this. But I noticed sometimes on my network strange location. Here are the pictures. I am using Windows 7 Professional.
Under **Network** :
!enter image description here
And **after doubleclick** :
!enter image description here
|
It's just another computer in your network.
In other words, wifi? If you've a router at home, which has multiple devices connected to it, they will list under your network.
You tried to access it, and it asked you to enter credidentials.
* * *
This is off topic, but very important:
**Always** set a proper password for wireless connections, or anyone can connect.
Because anyone can connect, anyone can also hijack your traffic. This includes passwords sent in plain text, website sessions (facebook etc.) or even access your online banking service, if you use it and the session is active.
MITM ( **Man-In-The-Middle)** attacks are extremely easy to perform, for example, you can do all the things listed above with a single application on a rooted android device.
|
stackexchange-superuser
|
{
"answer_score": 6,
"question_score": 0,
"tags": "windows 7, networking"
}
|
Why does np.float('nan') cause problems with dicts, but math.nan does not?
As in this question that shows how using nan from numpy causes problems with a dict, why does math.nan behave differently? (Python3)
import math
import numpy as np
d = {math.nan:'baz', math.nan:'bip' }
print(d)
e = {np.float('nan'):'foo', np.float('nan'):'bar' }
print(e)
Output
{nan: 'bip'}
{nan: 'foo', nan: 'bar'}
|
It's because `math.nan` is a module level attribute, so you get the identical object both times. CPython dicts have a shortcut† for identity checks
>>> any(k == math.nan for k in d)
False
>>> math.nan in d
True
With `np.float('nan')` you have a function call, returning different instance each time. Using Python's built-in `float('nan')` would be similar again, this is not really related to numpy.
>>> np.float('nan') is np.float('nan')
False
>>> math.nan is math.nan
True
>>> float('nan') is float('nan')
False
†Lists, tuples, etc also have this. See [Making an object x such that “x in [x]” returns False]( for more about that.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "python, numpy"
}
|
Liferay 6.2 Hook deployment strange behaviour
I have deployed a document library hook which includes many jsp files under custom_jsps.
Recently, I wanted to change folder_action.jsp, so I changed it and deployed it normally in document library portlet. As it was expected, a folder_action.portal.jsp was created containing the original file.
However, I've noticed something strange. After stopping Tomcat both folder_action.jsp and folder_action.portal.jsp are deleted(this is not happening for the other files that come from the hook), and when it is up again a really strange thing happens. The folder_action.portal.jsp contains the changed file and the folder_action.jsp is the original file.
Has anyone met something similar ever? Any help would be appreciated.
|
You might run into a very nasty issue: You must only override a particular jsp from exactly one hook. If you override the same jsp from two different hooks, the scenario that you describe might happen (on undeploy). Worse: Order is not maintained, you might have some "wrong" files left over.
Find the two hooks that override the same jsp and determine which you like better (or merge the two). Find some more horror in this answer to a similar question
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "liferay, hook, liferay 6"
}
|
How to filter choices in Django2's autocomplete_fields?
In Django 2.0, autocomplete_fields was added, which is great.
Without autocomplete_fields, I can change the queryset of a ForeignKeyField using formfield_for_foreignkey.
But combining the two together doesn't work - it looks like the list of options for autocomplete is dynamic and coming from a different url, instead of from the current form.
So the question is -
How can I change the queryset in the autocomplete widget?
|
Override the ModelAdmin's `get_search_results` method to use the query you want. You can see in the `get_queryset` method for the view providing the data for autocomplete fields that it's used to get the queryset - the source as of this answer is <
|
stackexchange-stackoverflow
|
{
"answer_score": 8,
"question_score": 29,
"tags": "python, django, django admin, django 2.0"
}
|
android HTML template as resource
is there any way to have an html file (i.e. an html template) be a resource in android? I'd like to reference it in a similar way that i store strings in the res/values/strings.xml. However, when i do this, it appears the HTML is not getting rendered correctly when i use `myTextView.setText(Html.fromHtml(MessageFormat .format(getResources().getString(R.string.myHtmlFile), ...)`
|
You can place raw HTML or other format files in /res/raw or /assets directory of your project. You can access the first with this method), and the second with this.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "html, android, resources"
}
|
swiftsuspenders constructor parameters?
Once I read in some google document about coding guidelines that every new instance of a class should go from a factory class, and I use SwiftSuspenders for it.
Now my question is, is it possible to create a new instance of an object that requires constructor parameters using SS's dependency injection?
|
Yes, Swiftsuspenders fully supports constructor injection.
You can either inject into a field (or a method or another constructor) requiring an instance of your class, or you can use `injector.getInstance` to directly query the injector for an instance that's created using the injector's mappings.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "actionscript 3, dependency injection, robotlegs, swiftsuspenders"
}
|
jqPlot Data Label Color Pie Chart
Im trying to create a theme something like in the sample:
temp = {
seriesStyles: {
seriesColors: ['red', 'orange', 'yellow', 'green', 'blue', 'indigo'],
highlightColors: ['lightpink', 'lightsalmon', 'lightyellow', 'lightgreen', 'lightblue', 'mediumslateblue']
},
legend: {
fontSize: '8pt'
},
title: {
fontSize: '18pt'
},
grid: {
backgroundColor: 'rgb(211, 233, 195)'
}
};
plot3.themeEngine.newTheme('uma', temp);
plot5.themeEngine.newTheme('uma', temp);
How can i change the data label color in chart?
|
You can change the data label color for JQPlot using css.
Apply style to these class
`.jqplot-data-label` for Pie-charts
`.jqplot-point-label` for Line-charts/Bar-Charts
You can also check this link: <
Hope it helps !!
Regards, Anish
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "javascript, html, jqplot"
}
|
Regular Expression With Partial Date Variable
Looking to build a reg expression that does the following:
If given a date-string in the format: a/b/c
I need to build a regular expression that would return true if:
1. month = a
2. date is between x and y (including both limits)
3. year = c
An example:
Date is 3/6/12, RegExp return true if:
* month = 3
* day is between 2 and 6 (including limits)
* year = 12
|
Try this: `\b3/[23456]/12\b`
Unless that above was just an example, then you'll need to clarify what you are after
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript, regex, string, search"
}
|
What connections do I make to this Through hole DC Power connector
I'd like to have one of these on a PCB I'm designing but I'm not completely sure how it works. Can somebody please explain to me how to connect this power jack to my circuit?
 - you need to check the details of the supply you're going to plug in to it.
**Sleeve** connects to the other contact on the plug - usually earth (ground, 0 V) but sometimes positive supply.
**Sleeve shunt** is probably a spring-loaded contact which connects to the sleeve pin when there is no plug inserted, but is open circuit when a plug is present - this can be used to disconnect an internal power source, for example. Test your connector with a resistance meter though, to check how it actually behaves.
|
stackexchange-electronics
|
{
"answer_score": 0,
"question_score": 0,
"tags": "power, pcb, circuit design"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.