qid
int64
1
74.6M
question
stringlengths
45
24.2k
date
stringlengths
10
10
metadata
stringlengths
101
178
response_j
stringlengths
32
23.2k
response_k
stringlengths
21
13.2k
3,015,046
This question comes from a Chinese high school olympiad training program. It seems remarkably more difficult (and indeed, interesting!) than all other problems arising in the same program, especially since an elementary (high-school level) solution is probably available. > > Show that there exists integers $a,b,c,d,e>2018$ so that the equation $$a^2+b^2+c^2+d^2+e^2+65=abcde$$ is satisfied. > > > For what it's worth, here's what I have tried. Rewriting the equation as a quadratic polynomial in $a$, $$a^2-(bcde)a+b^2+c^2+d^2+e^2+65=0.$$ For there to be integer solutions, the discriminant must be a perfect square. Hence $$ b^2c^2d^2e^2-4b^2-4c^2-4d^2-4e^2-4\cdot5\cdot13=n^2.$$ I don't however see how I can solve this equation, especially due to the large number of unknowns. Any ideas? --- **Edit:** Ivan Neretin presents an excellent answer by Vieta Jumping, which I'm sure will yield results. However, the training program I mentioned has not discussed such advanced tactics as Vieta Jumping yet, and only covered $\gcd$, $\operatorname{lcm}$, factorisation of polynomials, discriminants, modular arithmetic, divisibility and quadratic residues. Hence despite Ivan's excellent solution, I would still be extremely appreciative of a more elementary solution.
2018/11/26
['https://math.stackexchange.com/questions/3015046', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/496634/']
You are supposed to bruteforce or guess $(a,b,c,d,e)=(1,2,3,4,5)$ or any other small solution, and then go up by [Vieta jumping](https://en.wikipedia.org/wiki/Vieta_jumping). That is, once you have a solution, you rewrite it as a quadratic polynomial in $a$ (just like you did), and since one root is integer, so is the other. Then you do the same to $b,\;c...$ and repeat until the roots are big enough.
Here is the output of the [Maxima](http://maxima.sourceforge.net/) commands I used to calculate a solution according to [Ivan Neretin's answer](https://math.stackexchange.com/a/3015056/11206). ``` (%i2) ev(x^2-b*c*d*e*x+b^2+c^2+d^2+e^2+65,x = 1,b = 2,c = 3,d = 4,e = 5) (%o2) 0 (%i3) ev(solve(x^2-b*c*d*e*x+b^2+c^2+d^2+e^2+65,x),b = 2,c = 3,d = 4,e = 5) (%o3) [x = 1, x = 119] (%i4) ev(solve(x^2-b*c*d*e*x+b^2+c^2+d^2+e^2+65,x),b = 119,c = 3,d = 4,e = 5) (%o4) [x = 7138, x = 2] (%i5) ev(solve(x^2-b*c*d*e*x+b^2+c^2+d^2+e^2+65,x),b = 119,c = 7138,d = 4,e = 5) (%o5) [x = 3, x = 16988437] (%i6) ev(solve(x^2-b*c*d*e*x+b^2+c^2+d^2+e^2+65,x),b = 119,c = 7138, d = 16988437,e = 5) (%o6) [x = 72151760667066, x = 4] (%i7) ev(solve(x^2-b*c*d*e*x+b^2+c^2+d^2+e^2+65,x),b = 119,c = 7138, d = 16988437,e = 72151760667066) (%o7) [x = 1041175313471572184867943319, x = 5] (%i8) ev(solve(x^2-b*c*d*e*x+b^2+c^2+d^2+e^2+65,x), b = 1041175313471572184867943319,c = 7138,d = 16988437, e = 72151760667066) (%o8) [x = 9109630532627114315851511163018235051842553960810405, x = 119] (%i9) ev(x^2-b*c*d*e*x+b^2+c^2+d^2+e^2+65, x = 9109630532627114315851511163018235051842553960810405, b = 1041175313471572184867943319,c = 7138,d = 16988437, e = 72151760667066) (%o9) 0 ```
3,015,046
This question comes from a Chinese high school olympiad training program. It seems remarkably more difficult (and indeed, interesting!) than all other problems arising in the same program, especially since an elementary (high-school level) solution is probably available. > > Show that there exists integers $a,b,c,d,e>2018$ so that the equation $$a^2+b^2+c^2+d^2+e^2+65=abcde$$ is satisfied. > > > For what it's worth, here's what I have tried. Rewriting the equation as a quadratic polynomial in $a$, $$a^2-(bcde)a+b^2+c^2+d^2+e^2+65=0.$$ For there to be integer solutions, the discriminant must be a perfect square. Hence $$ b^2c^2d^2e^2-4b^2-4c^2-4d^2-4e^2-4\cdot5\cdot13=n^2.$$ I don't however see how I can solve this equation, especially due to the large number of unknowns. Any ideas? --- **Edit:** Ivan Neretin presents an excellent answer by Vieta Jumping, which I'm sure will yield results. However, the training program I mentioned has not discussed such advanced tactics as Vieta Jumping yet, and only covered $\gcd$, $\operatorname{lcm}$, factorisation of polynomials, discriminants, modular arithmetic, divisibility and quadratic residues. Hence despite Ivan's excellent solution, I would still be extremely appreciative of a more elementary solution.
2018/11/26
['https://math.stackexchange.com/questions/3015046', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/496634/']
You are supposed to bruteforce or guess $(a,b,c,d,e)=(1,2,3,4,5)$ or any other small solution, and then go up by [Vieta jumping](https://en.wikipedia.org/wiki/Vieta_jumping). That is, once you have a solution, you rewrite it as a quadratic polynomial in $a$ (just like you did), and since one root is integer, so is the other. Then you do the same to $b,\;c...$ and repeat until the roots are big enough.
*This expands upon @Ivan Neretin 's answer* This is what is meant by Vieta jumping, when it comes to this problem--we can use Vieta jumping to prove the following claim: > > Proposition 1: For any $A \in \mathbb{Z}^+$ there is a solution $(a,b,c,d,e)$; $a,b,c,d,e \in \mathbb{Z}^+$ to the equation $a^2+b^2+c^2+d^2+e^2+65 = abcde$ such that $A \leq \min\{a,b,c,d,e\}$. > > > *Proof:* We first claim the following: > > Claim 1: Let us suppose that there is a solution $a^2+b^2+c^2+d^2+e^2+65=120$; $a,b,c,d,e \in \mathbb{Z}^+$, and let us assume WLOG that $a= \min\{a,b,c,d,e\}$. Then > there is a solution $(a',b',c',d',e')$; $a',b',c',d',e' \in \mathbb{Z}^+$ s.t. $a'>a$ and $b'=b,c'=c,d'=d,e'=e$. > > > [*Proof of Claim 1:* Indeed, iff there exists an integer $a'> a$ is that satisfies the following: $a'^2 + (b^2+c^2+d^2+e^2)+65 > a'(bcde)$. Then Claim 1 will follow. However, the above is a quadratic equation in $a'$ of the form $a'^2 - xa' + z$; both $x$ and $z$ positive integers, that has at least one integer solution, namely $a$, and so the other solution is an integer; as $z$ is at least $b^2+c^2+d^2+e^2+65$ $> 4a^2$ and $aa'=z$ with $a$ positive it follows that $a'$ must be strictly greater than $4a$. So indeed Claim 1 does follow. $\surd$ ] We note that Proposition 1 follows immediately from Claim 1, and the existence of at least one solution $(a\_0,b\_0,c\_0,d\_0,e\_0); a\_0,b\_0,c\_0,d\_0,e\_0 \in \mathbb{Z}^+$ such that the equation $a\_0^2+b\_0^2+c\_0^2+d\_0^2+e\_0^2+65 = a\_0b\_0c\_0d\_0e\_0$ holds; namely $(a\_0,b\_0,c\_0,d\_0,e\_0) =(1,2,3,4,5)$. $\surd$
7,610,254
My trying to make an Ajax call to a PHP function that pulls out data from my database. I've run into a problem though. My query looks like this ``` $query = "SELECT * FROM mytable WHERE field LIKE '%$string%'" ``` I then check on the number of rows returned by the query, but when i type in æ ø å then i my query returns 0 rows, although I know there are entries in the database that have æ ø å.. why is this
2011/09/30
['https://Stackoverflow.com/questions/7610254', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/626535/']
Set the connection to use UTF-8: ``` <?php // MySQLi: $connection = new MySQLi( /* ... credentials ...*/); $connection->set_charset("utf8"); // MySQL: $connection = mysql_connect(/* ... credentials ... */); mysql_set_charset("utf8", $connection); ?> ```
in my case, I had to add this line: ``` mysqli_set_charset($con,"utf8mb4"); ```
37,307,901
I was messing around with transitions and I noticed some stuttering and flickering when the transitions are applied to the selection in a different function. If, however, the transition is applied with method chaining, it works exactly as prescribed. Below is small example ([Fiddle](https://jsfiddle.net/Fjotten/k8kv4arv/1/)) of simply moving some text. The first, leftmost, string magically teleports down the page before the transition starts. The second, rightmost, string has a smooth transition from the top to the bottom of the page. Why does this 'teleport' happen? Obviously applying the transitions in a separate function is not the same as chaining it, but is there a way to achieve this? Say, I want to apply the same transition to many different objects - retrieved from different selects - then is there a way to relegate the transition to its own function without getting this stuttering? ``` var svg = d3.select('svg'); var textElem = svg.append('text') .data(['hello world']) .attr('x', 30) .attr('y', 100) .attr('fill', '#000') .attr('id', 'a') .text(function (d) { return d; }); var textElem2 = svg.append('text') .data(['some text']) .attr('x', 230) .attr('y', 100) .attr('fill', '#000') .attr('id', 'a') .text(function (d) { return d; }); setTimeout(foo, 3000); function foo() { textElem.data(['hello world, again!']); applyTextTransitions(textElem); textElem.attr({ x: 30, y: 150 }); textElem.text(function (d) { return d; }); textElem2.data(['some more text!']) .transition() .duration(1000) .style('opacity', 0) .transition() .duration(1000) .style('opacity', 1) .attr({ x: 230, y: 150 }) .text(function (d) { return d; }); } function applyTextTransitions(element) { element .transition() .duration(1000) .style('opacity', 0) .transition() .duration(1000) .style('opacity', 1); } ```
2016/05/18
['https://Stackoverflow.com/questions/37307901', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4231740/']
You could use a simple circle collision detection such as described on msdn website: <https://msdn.microsoft.com/en-us/library/dn265052(v=vs.85).aspx> ``` function circlesOverlap(circleA, circleB) { // Returns true if the SVG circles A and B overlap, false otherwise. var deltaX = circleA.cx.baseVal.value - circleB.cx.baseVal.value; var deltaY = circleA.cy.baseVal.value - circleB.cy.baseVal.value; var distance = Math.sqrt( (deltaX*deltaX) + (deltaY*deltaY) ); // The classic distance-between-two-points formula. var radiusA = circleA.r.baseVal.value; // The radius of circle A. var radiusB = circleB.r.baseVal.value; // The radius of circle B. if (circleA.id == circleB.id) // If true, circleA and circleB are the same circle. return false; return distance <= (radiusA + radiusB); }; ``` Using your fiddle, this is what it gives: <https://jsfiddle.net/odubuc/qk3qrwbp/15/> Your animate function is now as simple as: ``` function animate () { var earth = document.getElementById("Earth"), sun = document.getElementById("Sun"); planetrotation("Earth"); if( circlesOverlap(earth, sun) ) { earth.setAttribute("fill-opacity", "0.0"); sun.setAttribute("fill-opacity", "0.0"); } } ```
Try using .offset() rather than .position() (check the console, with position, the values are never changing, with offset, they change) ``` var positionplanet = $("#Earth").offset(); var positionsun = $("#Sun").offset(); ``` <https://jsfiddle.net/zkuhpjwf/> As far as a good collision detection, you could write something saying if the planet's top offset is greater than the sun's top offset, but less than the sun's top offset + the sun's height and something similar for left offset/height. To trigger just when the planet touches the sun in any direction, you could throw in the planet's height and width to the equation. It would take some playing ``` if ( (positionplanet.left > positionsun.left && positionplanet.left < positionsun.left + SUNWIDTH) && (positionplanet.top > positionsun.top && positionplanet.top < positionsun.top + SUNHEIGHT) ) { //the planet is completely inside of the sun } if ( (positionplanet.left > positionsun.left - PLANETWIDTH && positionplanet.left < positionsun.left + SUNWIDTH - PLANETWIDTH) && (positionplanet.top > positionsun.top - PLANETHEIGHT && positionplanet.top < positionsun.top + SUNHEIGHT - PLANETHEIGHT) ) { //the planet is touching the sun (will need some fiddling I'm sure..) } ```
37,307,901
I was messing around with transitions and I noticed some stuttering and flickering when the transitions are applied to the selection in a different function. If, however, the transition is applied with method chaining, it works exactly as prescribed. Below is small example ([Fiddle](https://jsfiddle.net/Fjotten/k8kv4arv/1/)) of simply moving some text. The first, leftmost, string magically teleports down the page before the transition starts. The second, rightmost, string has a smooth transition from the top to the bottom of the page. Why does this 'teleport' happen? Obviously applying the transitions in a separate function is not the same as chaining it, but is there a way to achieve this? Say, I want to apply the same transition to many different objects - retrieved from different selects - then is there a way to relegate the transition to its own function without getting this stuttering? ``` var svg = d3.select('svg'); var textElem = svg.append('text') .data(['hello world']) .attr('x', 30) .attr('y', 100) .attr('fill', '#000') .attr('id', 'a') .text(function (d) { return d; }); var textElem2 = svg.append('text') .data(['some text']) .attr('x', 230) .attr('y', 100) .attr('fill', '#000') .attr('id', 'a') .text(function (d) { return d; }); setTimeout(foo, 3000); function foo() { textElem.data(['hello world, again!']); applyTextTransitions(textElem); textElem.attr({ x: 30, y: 150 }); textElem.text(function (d) { return d; }); textElem2.data(['some more text!']) .transition() .duration(1000) .style('opacity', 0) .transition() .duration(1000) .style('opacity', 1) .attr({ x: 230, y: 150 }) .text(function (d) { return d; }); } function applyTextTransitions(element) { element .transition() .duration(1000) .style('opacity', 0) .transition() .duration(1000) .style('opacity', 1); } ```
2016/05/18
['https://Stackoverflow.com/questions/37307901', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4231740/']
You could use a simple circle collision detection such as described on msdn website: <https://msdn.microsoft.com/en-us/library/dn265052(v=vs.85).aspx> ``` function circlesOverlap(circleA, circleB) { // Returns true if the SVG circles A and B overlap, false otherwise. var deltaX = circleA.cx.baseVal.value - circleB.cx.baseVal.value; var deltaY = circleA.cy.baseVal.value - circleB.cy.baseVal.value; var distance = Math.sqrt( (deltaX*deltaX) + (deltaY*deltaY) ); // The classic distance-between-two-points formula. var radiusA = circleA.r.baseVal.value; // The radius of circle A. var radiusB = circleB.r.baseVal.value; // The radius of circle B. if (circleA.id == circleB.id) // If true, circleA and circleB are the same circle. return false; return distance <= (radiusA + radiusB); }; ``` Using your fiddle, this is what it gives: <https://jsfiddle.net/odubuc/qk3qrwbp/15/> Your animate function is now as simple as: ``` function animate () { var earth = document.getElementById("Earth"), sun = document.getElementById("Sun"); planetrotation("Earth"); if( circlesOverlap(earth, sun) ) { earth.setAttribute("fill-opacity", "0.0"); sun.setAttribute("fill-opacity", "0.0"); } } ```
You should be able to use either `position` or `offset` according to jQuery docs - > > The `.position()` method allows us to retrieve the current position of > an element relative to the offset parent. Contrast this with > `.offset()`, which retrieves the current position relative to the > document. When positioning a new element near another one and within > the same containing DOM element, `.position()` is the more useful. > > > So, what your issue is here, is that the position/offset will be different for elements of differing sizes. Even if they are on top of each other. The reasoning, is because when you ask for the `left` positioning of the sun, since it's radius is bigger, thus a larger circle, it's left offset/position is less than what the earth would be. So now, you just have a simple math problem to solve for concentric circles - aka finding the distance between the edge of the sun and the edge of the earth, then you would need to subtract/add to whichever offset you want to check against. The way you find the distance between the two is by subtracting the radii. Now, I know that the `r` value does not refer to pixels, so I wasn't sure how to do that in your situation, but I think this should get you most of the way.
61,417,816
I wrote a simple Node.js program with a nice menu system facilitated by [inquirer.js](https://github.com/SBoudrias/Inquirer.js/). However, after selecting an option in the menu and completing some action, the program exits. I need the menu to show again, until I select the Exit [last] option in the menu. I would like to do this using Promise, *instead* of async/await. I tried using a function to show the menu and called that function within a forever loop (E.g. `while (true) { ... }`), but that made the program unusable. I changed that to a for-loop just to observe the problem. Below is the simple program and the resulting output. **`PROGRAM`** ``` "use strict"; const inquirer = require('inquirer'); const util = require('util') // Clear the screen process.stdout.write("\u001b[2J\u001b[0;0H"); const showMenu = () => { const questions = [ { type: "list", name: "action", message: "What do you want to do?", choices: [ { name: "action 1", value: "Action1" }, { name: "action 2", value: "Action2" }, { name: "Exit program", value: "quit"} ] } ]; return inquirer.prompt(questions); }; const main = () => { for (let count = 0; count < 3; count++) { showMenu() .then(answers => { if (answers.action === 'Action1') { return Promise.resolve('hello world'); } else if (answers.action === 'Action2') { return new Promise((resolve, reject) => { inquirer .prompt([ { type: 'input', name: 'secretCode', message: "Enter a secret code:" } ]) .then(answers => { resolve(answers); }) }); } else { console.log('Exiting program.') process.exit(0); } }) .then((data) => { console.log(util.inspect(data, { showHidden: false, depth: null })); }) .catch((error, response) => { console.error('Error:', error); }); } } main() ``` **`OUTPUT`** ``` ? What do you want to do? (Use arrow keys) ❯ action 1 action 2 Exit program ? What do you want to do? (Use arrow keys) ❯ action 1 action 2 Exit program ? What do you want to do? (Use arrow keys) ❯ action 1 action 2 Exit program (node:983) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 keypress listeners added to [ReadStream]. Use emitter.setMaxListeners() to increase limit ``` How can I block after the first call to generate the menu, wait for an option to be selected and the corresponding action to complete, and then cycle back to the next iteration of showing the menu?
2020/04/24
['https://Stackoverflow.com/questions/61417816', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/371392/']
You can use `async/await` syntax: Declare your `main` function `async`, and `await` the returned Promise from inquirer: ```js const main = async () => { for (let count = 0; count < 3; count++) { await showMenu() .then(answers => { [...] } }; ``` Your code doesn't work as you expect because, in short, the interpreter executes synchronous code before running any callbacks (from promises). As a consequence your synchronous `for` loop executes before any I/O callbacks are resolved. All calls to `showMenu()` returns promises which are resolved asynchronously, meaning nothing will be printed, and no inputs will be interpreted until after looping. Writing `await` blocks succeeding synchronous code inside an `async` function, which is what it seems you're trying to do.
Using your code as a starting point, I hacked together my own library for displaying cli menus. It strips away a lot of Inquirer's boilerplate, letting you declare a menu graph/tree concisely. The main.ts file shows how you use it. You declare a dictionary of MenuPrompts, which you add Menus, Actions and LoopActions to. Each prompt has a key, which other prompts can route to. ```js // main.ts import { Menu, Action, MenuPrompt, openMenuPrompt, LoopAction } from "./menus"; // Set of prompts let prompts = { menu_1: new MenuPrompt("Menu 1 - This list is ordinal - What would like to do?", 20, true, [ new Menu("Menu 2", "menu_2"), new LoopAction("Action", () => console.log("Menu 1 action executed")), new Action("Back", context => context.last), new Action("Exit", () => process.exit(0)), ]), menu_2: new MenuPrompt("Menu 2 - This list is NOT ordinal - What would like to do?", 20, false, [ new Menu("Menu 1", "menu_1"), new LoopAction("Action", () => console.log("Menu 2 action executed")), new Action("Back", context => context.last), new Action("Exit", () => process.exit(0)), ]), }; // Open the "menu_1" prompt openMenuPrompt("menu_1", prompts); ``` This is the lib file, which contains types & the function for opening the initial prompt. ```js // menus.ts import * as inquirer from "inquirer"; // MAIN FUNCTION export let openMenuPrompt = async (current: string, prompts: Dict<MenuPrompt>, last?: string): Promise<any> => { let answer: Answer = (await inquirer.prompt([prompts[current]])).value; let next = answer.execute({current, last}); if (!next) return; return await openMenuPrompt(next, prompts, current == next? last : current ); }; // PUBLIC TYPES export class MenuPrompt { type = "list"; name = "value"; message: string; pageSize: number; choices: Choice[]; constructor(message: string, pageSize: number, isOrdinalList: boolean, choices: Choice[]) { this.message = message; this.pageSize = pageSize; this.choices = choices; if (isOrdinalList) { this.choices.forEach((choice, i) => choice.name = `${i + 1}: ${choice.name}`) } } } export interface Choice { name: string; value: Answer; } export class Action implements Choice { name: string; value: Answer; constructor(name: string, execute: (context?: MenuContext) => any) { this.name = name; this.value = {execute}; } } export class LoopAction implements Choice { name: string; value: Answer; constructor(name: string, execute: (context?: MenuContext) => any) { this.name = name; this.value = {execute: context => execute(context) ?? context.current}; } } export class Menu implements Choice { name: string; value: Answer; constructor(name: string, menuKey: string) { this.name = name; this.value = {execute: () => menuKey}; } } // INTERNAL TYPES type Dict<T = any> = {[key: string]: T}; interface Answer { execute: (context: MenuContext) => any; } interface MenuContext { current: string; last: string; } ```
20,066,413
Here is what I wanna do: 1. Check if a folder exists 2. If it does not exists, create the folder 3. If it doest exists do nothing 4. At last create a file in that folder Everything is working fine in Windows 7, but when I run the application in Ubuntu it doesn't create the folder, it is just creating the file with the folder name, example: (my file name is xxx.xml and the folder is d:\temp, so in Ubuntu the file is generated at d: with the name temp\xxx.xml). Here is my code: ``` File folder = new File("D:\\temp"); if (folder.exists() && folder.isDirectory()) { } else { folder.mkdir(); } String filePath = folder + File.separator; File file = new File(filePath + "xxx.xml"); StreamResult result = new StreamResult(file); transformer.transform(source, result); // more code here ```
2013/11/19
['https://Stackoverflow.com/questions/20066413', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1966049/']
`D:\temp` does not exists in linux systems (what I mean is it interprets it as if it were any other foldername) In Linux systems the file seperator is `/` instead of `\` as in case of Windows so the solution is to : ``` File folder = new File("/tmp"); ``` instead of ``` File folder = new File("D:\\temp"); ```
Consider both solutions using the getProperty static method of System class. ``` String os = System.getProperty("os.name"); if(os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0 || os.indexOf("aix") > 0 ) // Unix File folder = new File("/home/tmp"); else if(os.indexOf("win") >= 0) // Windows File folder = new File("D:\\temp"); else throw Exception("your message"); ```
20,066,413
Here is what I wanna do: 1. Check if a folder exists 2. If it does not exists, create the folder 3. If it doest exists do nothing 4. At last create a file in that folder Everything is working fine in Windows 7, but when I run the application in Ubuntu it doesn't create the folder, it is just creating the file with the folder name, example: (my file name is xxx.xml and the folder is d:\temp, so in Ubuntu the file is generated at d: with the name temp\xxx.xml). Here is my code: ``` File folder = new File("D:\\temp"); if (folder.exists() && folder.isDirectory()) { } else { folder.mkdir(); } String filePath = folder + File.separator; File file = new File(filePath + "xxx.xml"); StreamResult result = new StreamResult(file); transformer.transform(source, result); // more code here ```
2013/11/19
['https://Stackoverflow.com/questions/20066413', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1966049/']
You directory (D:\temp) is nos appropriate on Linux. Please, consider using linux File System, and the File.SEPARATOR constant : ``` static String OS = System.getProperty("OS.name").toLowerCase(); String root = "/tmp"; if (OS.indexOf("win") >= 0) { root="D:\\temp"; } else { root="/"; } File folder = new File(ROOT + "dir1" + File.SEPARATOR + "dir2"); if (folder.exists() && folder.isDirectory()) { } else { folder.mkdir(); } ``` Didn't tried it, but whould work.
Before Java 7 the File API has some possibilities to create a temporary file, utilising the operating system configuration (like temp files on a RAM disk). Since Java 7 use the utility functions class [Files](http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#createTempDirectory%28java.nio.file.Path,%20java.lang.String,%20java.nio.file.attribute.FileAttribute...%29).
20,066,413
Here is what I wanna do: 1. Check if a folder exists 2. If it does not exists, create the folder 3. If it doest exists do nothing 4. At last create a file in that folder Everything is working fine in Windows 7, but when I run the application in Ubuntu it doesn't create the folder, it is just creating the file with the folder name, example: (my file name is xxx.xml and the folder is d:\temp, so in Ubuntu the file is generated at d: with the name temp\xxx.xml). Here is my code: ``` File folder = new File("D:\\temp"); if (folder.exists() && folder.isDirectory()) { } else { folder.mkdir(); } String filePath = folder + File.separator; File file = new File(filePath + "xxx.xml"); StreamResult result = new StreamResult(file); transformer.transform(source, result); // more code here ```
2013/11/19
['https://Stackoverflow.com/questions/20066413', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1966049/']
Linux does not use drive letters (like D:) and uses forward slashes as file separator. You can do something like this: ``` File folder = new File("/path/name/of/the/folder"); folder.mkdirs(); // this will also create parent directories if necessary File file = new File(folder, "filename"); StreamResult result = new StreamResult(file); ```
Since Java 7, you can use the [Files](http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html) utility class, with the new [Path](http://docs.oracle.com/javase/7/docs/api/java/nio/file/Path.html) class. **Note that exception handling has been omitted in the examples below.** ``` // uses os separator for path/to/folder. Path file = Paths.get("path","to","file"); // this creates directories in case they don't exist Files.createDirectories(file.getParent()); if (!Files.exists(file)) { Files.createFile(file); } StreamResult result = new StreamResult(file.toFile()); transformer.transform(source, result); ``` this covers the generic case, create a folder if it doesn't exist and a file on that folder. --- In case you actually want to create a temporary file, as written in your example, then you just need to do the following: ``` // this create a temporary file on the system's default temp folder. Path tempFile = Files.createTempFile("xxx", "xml"); StreamResult result = new StreamResult(Files.newOutputStream(file, CREATE, APPEND, DELETE_ON_CLOSE)); transformer.transform(source, result); ``` Note that with this method, the file name will not correspond exactly to the prefix you used (`xxx`, in this case). Still, given that it's a temp file, that shouldn't matter at all. The DELETE\_ON\_CLOSE guarantees that the file will get deleted when closed.
20,066,413
Here is what I wanna do: 1. Check if a folder exists 2. If it does not exists, create the folder 3. If it doest exists do nothing 4. At last create a file in that folder Everything is working fine in Windows 7, but when I run the application in Ubuntu it doesn't create the folder, it is just creating the file with the folder name, example: (my file name is xxx.xml and the folder is d:\temp, so in Ubuntu the file is generated at d: with the name temp\xxx.xml). Here is my code: ``` File folder = new File("D:\\temp"); if (folder.exists() && folder.isDirectory()) { } else { folder.mkdir(); } String filePath = folder + File.separator; File file = new File(filePath + "xxx.xml"); StreamResult result = new StreamResult(file); transformer.transform(source, result); // more code here ```
2013/11/19
['https://Stackoverflow.com/questions/20066413', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1966049/']
`D:\temp` does not exists in linux systems (what I mean is it interprets it as if it were any other foldername) In Linux systems the file seperator is `/` instead of `\` as in case of Windows so the solution is to : ``` File folder = new File("/tmp"); ``` instead of ``` File folder = new File("D:\\temp"); ```
Since Java 7, you can use the [Files](http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html) utility class, with the new [Path](http://docs.oracle.com/javase/7/docs/api/java/nio/file/Path.html) class. **Note that exception handling has been omitted in the examples below.** ``` // uses os separator for path/to/folder. Path file = Paths.get("path","to","file"); // this creates directories in case they don't exist Files.createDirectories(file.getParent()); if (!Files.exists(file)) { Files.createFile(file); } StreamResult result = new StreamResult(file.toFile()); transformer.transform(source, result); ``` this covers the generic case, create a folder if it doesn't exist and a file on that folder. --- In case you actually want to create a temporary file, as written in your example, then you just need to do the following: ``` // this create a temporary file on the system's default temp folder. Path tempFile = Files.createTempFile("xxx", "xml"); StreamResult result = new StreamResult(Files.newOutputStream(file, CREATE, APPEND, DELETE_ON_CLOSE)); transformer.transform(source, result); ``` Note that with this method, the file name will not correspond exactly to the prefix you used (`xxx`, in this case). Still, given that it's a temp file, that shouldn't matter at all. The DELETE\_ON\_CLOSE guarantees that the file will get deleted when closed.
20,066,413
Here is what I wanna do: 1. Check if a folder exists 2. If it does not exists, create the folder 3. If it doest exists do nothing 4. At last create a file in that folder Everything is working fine in Windows 7, but when I run the application in Ubuntu it doesn't create the folder, it is just creating the file with the folder name, example: (my file name is xxx.xml and the folder is d:\temp, so in Ubuntu the file is generated at d: with the name temp\xxx.xml). Here is my code: ``` File folder = new File("D:\\temp"); if (folder.exists() && folder.isDirectory()) { } else { folder.mkdir(); } String filePath = folder + File.separator; File file = new File(filePath + "xxx.xml"); StreamResult result = new StreamResult(file); transformer.transform(source, result); // more code here ```
2013/11/19
['https://Stackoverflow.com/questions/20066413', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1966049/']
`D:\temp` does not exists in linux systems (what I mean is it interprets it as if it were any other foldername) In Linux systems the file seperator is `/` instead of `\` as in case of Windows so the solution is to : ``` File folder = new File("/tmp"); ``` instead of ``` File folder = new File("D:\\temp"); ```
Before Java 7 the File API has some possibilities to create a temporary file, utilising the operating system configuration (like temp files on a RAM disk). Since Java 7 use the utility functions class [Files](http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#createTempDirectory%28java.nio.file.Path,%20java.lang.String,%20java.nio.file.attribute.FileAttribute...%29).
20,066,413
Here is what I wanna do: 1. Check if a folder exists 2. If it does not exists, create the folder 3. If it doest exists do nothing 4. At last create a file in that folder Everything is working fine in Windows 7, but when I run the application in Ubuntu it doesn't create the folder, it is just creating the file with the folder name, example: (my file name is xxx.xml and the folder is d:\temp, so in Ubuntu the file is generated at d: with the name temp\xxx.xml). Here is my code: ``` File folder = new File("D:\\temp"); if (folder.exists() && folder.isDirectory()) { } else { folder.mkdir(); } String filePath = folder + File.separator; File file = new File(filePath + "xxx.xml"); StreamResult result = new StreamResult(file); transformer.transform(source, result); // more code here ```
2013/11/19
['https://Stackoverflow.com/questions/20066413', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1966049/']
Linux does not use drive letters (like D:) and uses forward slashes as file separator. You can do something like this: ``` File folder = new File("/path/name/of/the/folder"); folder.mkdirs(); // this will also create parent directories if necessary File file = new File(folder, "filename"); StreamResult result = new StreamResult(file); ```
On Unix-like systems no logical discs. You can try create on `/tmp` or `/home` Below code for create `temp` dirrectory in your home directory: ``` String myPathCandidate = System.getProperty("os.name").equals("Linux")? System.getProperty("user.home"):"D:\\"; System.out.println(myPathCandidate); //Check write permissions File folder = new File(myPathCandidate); if (folder.exists() && folder.isDirectory() && folder.canWrite()) { System.out.println("Create directory here"); } else {System.out.println("Wrong path");} ``` or, for `/tmp` - system temp dicecrory. Majority of users can write here: ``` String myPathCandidate = System.getProperty("os.name").equals("Linux")? System.getProperty("java.io.tmpdir"):"D:\\"; ```
20,066,413
Here is what I wanna do: 1. Check if a folder exists 2. If it does not exists, create the folder 3. If it doest exists do nothing 4. At last create a file in that folder Everything is working fine in Windows 7, but when I run the application in Ubuntu it doesn't create the folder, it is just creating the file with the folder name, example: (my file name is xxx.xml and the folder is d:\temp, so in Ubuntu the file is generated at d: with the name temp\xxx.xml). Here is my code: ``` File folder = new File("D:\\temp"); if (folder.exists() && folder.isDirectory()) { } else { folder.mkdir(); } String filePath = folder + File.separator; File file = new File(filePath + "xxx.xml"); StreamResult result = new StreamResult(file); transformer.transform(source, result); // more code here ```
2013/11/19
['https://Stackoverflow.com/questions/20066413', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1966049/']
Linux does not use drive letters (like D:) and uses forward slashes as file separator. You can do something like this: ``` File folder = new File("/path/name/of/the/folder"); folder.mkdirs(); // this will also create parent directories if necessary File file = new File(folder, "filename"); StreamResult result = new StreamResult(file); ```
Consider both solutions using the getProperty static method of System class. ``` String os = System.getProperty("os.name"); if(os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0 || os.indexOf("aix") > 0 ) // Unix File folder = new File("/home/tmp"); else if(os.indexOf("win") >= 0) // Windows File folder = new File("D:\\temp"); else throw Exception("your message"); ```
20,066,413
Here is what I wanna do: 1. Check if a folder exists 2. If it does not exists, create the folder 3. If it doest exists do nothing 4. At last create a file in that folder Everything is working fine in Windows 7, but when I run the application in Ubuntu it doesn't create the folder, it is just creating the file with the folder name, example: (my file name is xxx.xml and the folder is d:\temp, so in Ubuntu the file is generated at d: with the name temp\xxx.xml). Here is my code: ``` File folder = new File("D:\\temp"); if (folder.exists() && folder.isDirectory()) { } else { folder.mkdir(); } String filePath = folder + File.separator; File file = new File(filePath + "xxx.xml"); StreamResult result = new StreamResult(file); transformer.transform(source, result); // more code here ```
2013/11/19
['https://Stackoverflow.com/questions/20066413', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1966049/']
You directory (D:\temp) is nos appropriate on Linux. Please, consider using linux File System, and the File.SEPARATOR constant : ``` static String OS = System.getProperty("OS.name").toLowerCase(); String root = "/tmp"; if (OS.indexOf("win") >= 0) { root="D:\\temp"; } else { root="/"; } File folder = new File(ROOT + "dir1" + File.SEPARATOR + "dir2"); if (folder.exists() && folder.isDirectory()) { } else { folder.mkdir(); } ``` Didn't tried it, but whould work.
Since Java 7, you can use the [Files](http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html) utility class, with the new [Path](http://docs.oracle.com/javase/7/docs/api/java/nio/file/Path.html) class. **Note that exception handling has been omitted in the examples below.** ``` // uses os separator for path/to/folder. Path file = Paths.get("path","to","file"); // this creates directories in case they don't exist Files.createDirectories(file.getParent()); if (!Files.exists(file)) { Files.createFile(file); } StreamResult result = new StreamResult(file.toFile()); transformer.transform(source, result); ``` this covers the generic case, create a folder if it doesn't exist and a file on that folder. --- In case you actually want to create a temporary file, as written in your example, then you just need to do the following: ``` // this create a temporary file on the system's default temp folder. Path tempFile = Files.createTempFile("xxx", "xml"); StreamResult result = new StreamResult(Files.newOutputStream(file, CREATE, APPEND, DELETE_ON_CLOSE)); transformer.transform(source, result); ``` Note that with this method, the file name will not correspond exactly to the prefix you used (`xxx`, in this case). Still, given that it's a temp file, that shouldn't matter at all. The DELETE\_ON\_CLOSE guarantees that the file will get deleted when closed.
20,066,413
Here is what I wanna do: 1. Check if a folder exists 2. If it does not exists, create the folder 3. If it doest exists do nothing 4. At last create a file in that folder Everything is working fine in Windows 7, but when I run the application in Ubuntu it doesn't create the folder, it is just creating the file with the folder name, example: (my file name is xxx.xml and the folder is d:\temp, so in Ubuntu the file is generated at d: with the name temp\xxx.xml). Here is my code: ``` File folder = new File("D:\\temp"); if (folder.exists() && folder.isDirectory()) { } else { folder.mkdir(); } String filePath = folder + File.separator; File file = new File(filePath + "xxx.xml"); StreamResult result = new StreamResult(file); transformer.transform(source, result); // more code here ```
2013/11/19
['https://Stackoverflow.com/questions/20066413', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1966049/']
Linux does not use drive letters (like D:) and uses forward slashes as file separator. You can do something like this: ``` File folder = new File("/path/name/of/the/folder"); folder.mkdirs(); // this will also create parent directories if necessary File file = new File(folder, "filename"); StreamResult result = new StreamResult(file); ```
Before Java 7 the File API has some possibilities to create a temporary file, utilising the operating system configuration (like temp files on a RAM disk). Since Java 7 use the utility functions class [Files](http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#createTempDirectory%28java.nio.file.Path,%20java.lang.String,%20java.nio.file.attribute.FileAttribute...%29).
20,066,413
Here is what I wanna do: 1. Check if a folder exists 2. If it does not exists, create the folder 3. If it doest exists do nothing 4. At last create a file in that folder Everything is working fine in Windows 7, but when I run the application in Ubuntu it doesn't create the folder, it is just creating the file with the folder name, example: (my file name is xxx.xml and the folder is d:\temp, so in Ubuntu the file is generated at d: with the name temp\xxx.xml). Here is my code: ``` File folder = new File("D:\\temp"); if (folder.exists() && folder.isDirectory()) { } else { folder.mkdir(); } String filePath = folder + File.separator; File file = new File(filePath + "xxx.xml"); StreamResult result = new StreamResult(file); transformer.transform(source, result); // more code here ```
2013/11/19
['https://Stackoverflow.com/questions/20066413', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1966049/']
You directory (D:\temp) is nos appropriate on Linux. Please, consider using linux File System, and the File.SEPARATOR constant : ``` static String OS = System.getProperty("OS.name").toLowerCase(); String root = "/tmp"; if (OS.indexOf("win") >= 0) { root="D:\\temp"; } else { root="/"; } File folder = new File(ROOT + "dir1" + File.SEPARATOR + "dir2"); if (folder.exists() && folder.isDirectory()) { } else { folder.mkdir(); } ``` Didn't tried it, but whould work.
On Unix-like systems no logical discs. You can try create on `/tmp` or `/home` Below code for create `temp` dirrectory in your home directory: ``` String myPathCandidate = System.getProperty("os.name").equals("Linux")? System.getProperty("user.home"):"D:\\"; System.out.println(myPathCandidate); //Check write permissions File folder = new File(myPathCandidate); if (folder.exists() && folder.isDirectory() && folder.canWrite()) { System.out.println("Create directory here"); } else {System.out.println("Wrong path");} ``` or, for `/tmp` - system temp dicecrory. Majority of users can write here: ``` String myPathCandidate = System.getProperty("os.name").equals("Linux")? System.getProperty("java.io.tmpdir"):"D:\\"; ```
1,468,037
Using Flex 3, I had created a employer profile application where I could view 10 profiles in a page using repeater, however, when I tried to load 20 profiles in a page, all of the component go haywire, became non-function. It would not happen if I set the application height to 100% but due to native scrollbar requirement, I use Swffit to enable web browser scrollbar and hide the Flex scrollbar and set the height of the flex application with exact viewable contents in pixel. How do I solve the canvas height issue?
2009/09/23
['https://Stackoverflow.com/questions/1468037', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
Have you tried placing the Canvas inside of some other container with an explicit height? That might be all you need. eg: ``` <mx:VBox id = "theFakeContainer" verticalScrollPolicy = "off" height = "{EXPLICIT HEIGHT}" > <mx:Canvas id = "theRealCanvas" verticalScrollPolicy = "off" height = "100%" /> </mx:VBox> ``` I'm not sure if this will work, but it seems like it is worth a try.
I have this part of the code as you have shown me. I was think of creating a custom components with canvas and loop with the repeater or another idea is that I might use one of the working solution I have just thought of it to overcome the issue.
59,116,410
I'm trying to replace any global variables in my example to a specific value `$var` as shows in the following example: (example.php) ``` <?php // before $firstname = $_GET['firstname']; $lastname = $_POST['lastname']; $age = $_REQUEST['age']; ?> ``` As shown in the example above, I want to change any global variables `$_POST, $_GET, $_REQUEST` automatically in the php file to specific value `$var` in the php file. Here is what I did to get each line and check if the line of code have `$_POST` or `$_GET` or `$_REQUEST`, then I'm trying to change any global variables in the file to specific value `$var`. (test.php) ``` <?php $file = file_get_contents("example.php"); $lines = explode("\n", $file); $var = '$var'; foreach ($lines as $key => &$value) { if(strpos($value, '$_GET') !== false){ // Replace $_GET['firstname'] and put $var } elseif(strpos($value, '$_POST') !== false){ // Replace $_POST['lastname'] and put $var } elseif(strpos($value, '$_REQUEST') !== false){ // Replace $_REQUEST['age'] and put $var } } ?> ``` The expected results to be after replace any global variables to `$var` is as following: (example.php) ``` <?php // The expected results to be after replace all global variables by $var // This is how I expect the file to looks like after replace $firstname = $var; $lastname = $var; $age = $var; ?> ``` I appreciated if anyone anyone can help me to find a suitable way to replace any `$_GET, $_POST, $_REQUEST` exist in the file by `$var`. * note: I want to replace any `$_GET[], $_POST[], $_REQUEST` by `$var`, $var to be stored as following: ``` <?php $firstname = $var; // Just change text (remove $_GET['firstname', and put $var] in php file $lastname = $var; // Just change text (remove $_POST['lastname', and put $var] in php file $age = $var; // Just change text (remove $_REQUEST['age', and put $var] in php file ?> ``` * Note: This is how I hope the php file to be looks like.
2019/11/30
['https://Stackoverflow.com/questions/59116410', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10092475/']
Is that what you want? ``` $file = file_get_contents("example.php"); $lines = explode("\n", $file); $var = '$var'; foreach ($lines as $key => &$value) { if(strpos($value, '$_GET') !== false){ $value = preg_replace('/\$_GET\[.+?\]/', $var, $value); } elseif(strpos($value, '$_POST') !== false){ $value = preg_replace('/\$_POST\[.+?\]/', $var, $value); } elseif(strpos($value, '$_REQUEST') !== false){ $value = preg_replace('/\$_REQUEST\[.+?\]/', $var, $value); } } ```
**Solution:** The following code will turn `$_REQUEST['thisvar']` into `$thisvar`, as well as any other `$_GET`/`$_POST` variables you have set. As mentioned in the comments `$_REQUEST` covers both `$_GET` and `$_POST`. ``` foreach($_REQUEST as $key => $value) $$key = $value; ``` **If I modify your example:** ``` $file = file_get_contents("example.php"); $lines = explode("\n", $file); foreach($lines as $key => $value) $$key = $value; ```
59,116,410
I'm trying to replace any global variables in my example to a specific value `$var` as shows in the following example: (example.php) ``` <?php // before $firstname = $_GET['firstname']; $lastname = $_POST['lastname']; $age = $_REQUEST['age']; ?> ``` As shown in the example above, I want to change any global variables `$_POST, $_GET, $_REQUEST` automatically in the php file to specific value `$var` in the php file. Here is what I did to get each line and check if the line of code have `$_POST` or `$_GET` or `$_REQUEST`, then I'm trying to change any global variables in the file to specific value `$var`. (test.php) ``` <?php $file = file_get_contents("example.php"); $lines = explode("\n", $file); $var = '$var'; foreach ($lines as $key => &$value) { if(strpos($value, '$_GET') !== false){ // Replace $_GET['firstname'] and put $var } elseif(strpos($value, '$_POST') !== false){ // Replace $_POST['lastname'] and put $var } elseif(strpos($value, '$_REQUEST') !== false){ // Replace $_REQUEST['age'] and put $var } } ?> ``` The expected results to be after replace any global variables to `$var` is as following: (example.php) ``` <?php // The expected results to be after replace all global variables by $var // This is how I expect the file to looks like after replace $firstname = $var; $lastname = $var; $age = $var; ?> ``` I appreciated if anyone anyone can help me to find a suitable way to replace any `$_GET, $_POST, $_REQUEST` exist in the file by `$var`. * note: I want to replace any `$_GET[], $_POST[], $_REQUEST` by `$var`, $var to be stored as following: ``` <?php $firstname = $var; // Just change text (remove $_GET['firstname', and put $var] in php file $lastname = $var; // Just change text (remove $_POST['lastname', and put $var] in php file $age = $var; // Just change text (remove $_REQUEST['age', and put $var] in php file ?> ``` * Note: This is how I hope the php file to be looks like.
2019/11/30
['https://Stackoverflow.com/questions/59116410', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10092475/']
[See Regex Demo](https://regex101.com/r/FdiQgh/1/) `/\$_(GET|POST|REQUEST)\[[^\]]*\]/'` will match, for example, `$_GET[anything-other-than-a-right-bracket]` and all we have to do is replace it with `$var` and rewrite the file: ``` <?php $file = file_get_contents("example.php"); $file = preg_replace('/\$_(GET|POST|REQUEST)\[[^\]]*\]/', '$var', $file); file_put_contents("example.php", $file); ```
**Solution:** The following code will turn `$_REQUEST['thisvar']` into `$thisvar`, as well as any other `$_GET`/`$_POST` variables you have set. As mentioned in the comments `$_REQUEST` covers both `$_GET` and `$_POST`. ``` foreach($_REQUEST as $key => $value) $$key = $value; ``` **If I modify your example:** ``` $file = file_get_contents("example.php"); $lines = explode("\n", $file); foreach($lines as $key => $value) $$key = $value; ```
59,116,410
I'm trying to replace any global variables in my example to a specific value `$var` as shows in the following example: (example.php) ``` <?php // before $firstname = $_GET['firstname']; $lastname = $_POST['lastname']; $age = $_REQUEST['age']; ?> ``` As shown in the example above, I want to change any global variables `$_POST, $_GET, $_REQUEST` automatically in the php file to specific value `$var` in the php file. Here is what I did to get each line and check if the line of code have `$_POST` or `$_GET` or `$_REQUEST`, then I'm trying to change any global variables in the file to specific value `$var`. (test.php) ``` <?php $file = file_get_contents("example.php"); $lines = explode("\n", $file); $var = '$var'; foreach ($lines as $key => &$value) { if(strpos($value, '$_GET') !== false){ // Replace $_GET['firstname'] and put $var } elseif(strpos($value, '$_POST') !== false){ // Replace $_POST['lastname'] and put $var } elseif(strpos($value, '$_REQUEST') !== false){ // Replace $_REQUEST['age'] and put $var } } ?> ``` The expected results to be after replace any global variables to `$var` is as following: (example.php) ``` <?php // The expected results to be after replace all global variables by $var // This is how I expect the file to looks like after replace $firstname = $var; $lastname = $var; $age = $var; ?> ``` I appreciated if anyone anyone can help me to find a suitable way to replace any `$_GET, $_POST, $_REQUEST` exist in the file by `$var`. * note: I want to replace any `$_GET[], $_POST[], $_REQUEST` by `$var`, $var to be stored as following: ``` <?php $firstname = $var; // Just change text (remove $_GET['firstname', and put $var] in php file $lastname = $var; // Just change text (remove $_POST['lastname', and put $var] in php file $age = $var; // Just change text (remove $_REQUEST['age', and put $var] in php file ?> ``` * Note: This is how I hope the php file to be looks like.
2019/11/30
['https://Stackoverflow.com/questions/59116410', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10092475/']
[See Regex Demo](https://regex101.com/r/FdiQgh/1/) `/\$_(GET|POST|REQUEST)\[[^\]]*\]/'` will match, for example, `$_GET[anything-other-than-a-right-bracket]` and all we have to do is replace it with `$var` and rewrite the file: ``` <?php $file = file_get_contents("example.php"); $file = preg_replace('/\$_(GET|POST|REQUEST)\[[^\]]*\]/', '$var', $file); file_put_contents("example.php", $file); ```
Is that what you want? ``` $file = file_get_contents("example.php"); $lines = explode("\n", $file); $var = '$var'; foreach ($lines as $key => &$value) { if(strpos($value, '$_GET') !== false){ $value = preg_replace('/\$_GET\[.+?\]/', $var, $value); } elseif(strpos($value, '$_POST') !== false){ $value = preg_replace('/\$_POST\[.+?\]/', $var, $value); } elseif(strpos($value, '$_REQUEST') !== false){ $value = preg_replace('/\$_REQUEST\[.+?\]/', $var, $value); } } ```
35,522,805
Something strange here with Meteor 1.2.1 and Iron Router 1.0.12. ``` Router.route('/news/:_id', function() { this.render('l_basic'); console.log (newsCollection.findOne().title); }); ``` This works perfect. I’ve got the title of my last post in the console. But there is an unwanted exception too. No matter where I would place database query: into the main router function, to the onAfterAction or any other hook. Doesn't matter, if I'll surround it with `if (this.ready())`. If I comment console.log statement, no exception appears. This is what I get in console. I've completely broken my head, trying to find out what is going on here. ``` Exception in callback of async function: http://localhost:3000/app/both/router.js?4bb8a45e172aaff7cfe3c5a6bff0f87a62d217d0:17:59 boundNext@http://localhost:3000/packages/iron_middleware-stack.js?3370bd57ef7b310cca3f5dddb11b77fafdcfc1eb:418:35 http://localhost:3000/packages/meteor.js?9730f4ff059088b3f7f14c0672d155218a1802d4:999:27 onRerun@http://localhost:3000/packages/iron_router.js?c564289eeaa191561eba900052037432ebfcbe4a:515:13 boundNext@http://localhost:3000/packages/iron_middleware-stack.js?3370bd57ef7b310cca3f5dddb11b77fafdcfc1eb:418:35 http://localhost:3000/packages/meteor.js?9730f4ff059088b3f7f14c0672d155218a1802d4:999:27 onRun@http://localhost:3000/packages/iron_router.js?c564289eeaa191561eba900052037432ebfcbe4a:499:15 boundNext@http://localhost:3000/packages/iron_middleware-stack.js?3370bd57ef7b310cca3f5dddb11b77fafdcfc1eb:418:35 http://localhost:3000/packages/meteor.js?9730f4ff059088b3f7f14c0672d155218a1802d4:999:27 dispatch@http://localhost:3000/packages/iron_middleware-stack.js?3370bd57ef7b310cca3f5dddb11b77fafdcfc1eb:442:7 _runRoute@http://localhost:3000/packages/iron_router.js?c564289eeaa191561eba900052037432ebfcbe4a:538:17 dispatch@http://localhost:3000/packages/iron_router.js?c564289eeaa191561eba900052037432ebfcbe4a:848:27 route@http://localhost:3000/packages/iron_router.js?c564289eeaa191561eba900052037432ebfcbe4a:705:19 boundNext@http://localhost:3000/packages/iron_middleware-stack.js?3370bd57ef7b310cca3f5dddb11b77fafdcfc1eb:418:35 http://localhost:3000/packages/meteor.js?9730f4ff059088b3f7f14c0672d155218a1802d4:999:27 boundNext@http://localhost:3000/packages/iron_middleware-stack.js?3370bd57ef7b310cca3f5dddb11b77fafdcfc1eb:365:18 http://localhost:3000/packages/meteor.js?9730f4ff059088b3f7f14c0672d155218a1802d4:999:27 dispatch@http://localhost:3000/packages/iron_middleware-stack.js?3370bd57ef7b310cca3f5dddb11b77fafdcfc1eb:442:7 http://localhost:3000/packages/iron_router.js?c564289eeaa191561eba900052037432ebfcbe4a:385:21 _compute@http://localhost:3000/packages/tracker.js?7776276660c988c38fed448d8262b925dffb5bc3:349:36 Computation@http://localhost:3000/packages/tracker.js?7776276660c988c38fed448d8262b925dffb5bc3:237:18 autorun@http://localhost:3000/packages/tracker.js?7776276660c988c38fed448d8262b925dffb5bc3:588:34 http://localhost:3000/packages/iron_router.js?c564289eeaa191561eba900052037432ebfcbe4a:383:17 nonreactive@http://localhost:3000/packages/tracker.js?7776276660c988c38fed448d8262b925dffb5bc3:615:13 dispatch@http://localhost:3000/packages/iron_router.js?c564289eeaa191561eba900052037432ebfcbe4a:382:19 dispatch@http://localhost:3000/packages/iron_router.js?c564289eeaa191561eba900052037432ebfcbe4a:1692:22 onLocationChange@http://localhost:3000/packages/iron_router.js?c564289eeaa191561eba900052037432ebfcbe4a:1776:33 _compute@http://localhost:3000/packages/tracker.js?7776276660c988c38fed448d8262b925dffb5bc3:349:36 Computation@http://localhost:3000/packages/tracker.js?7776276660c988c38fed448d8262b925dffb5bc3:237:18 autorun@http://localhost:3000/packages/tracker.js?7776276660c988c38fed448d8262b925dffb5bc3:588:34 start@http://localhost:3000/packages/iron_router.js?c564289eeaa191561eba900052037432ebfcbe4a:1769:43 http://localhost:3000/packages/iron_router.js?c564289eeaa191561eba900052037432ebfcbe4a:972:21 withValue@http://localhost:3000/packages/meteor.js?9730f4ff059088b3f7f14c0672d155218a1802d4:971:21 http://localhost:3000/packages/meteor.js?9730f4ff059088b3f7f14c0672d155218a1802d4:428:54 http://localhost:3000/packages/meteor.js?9730f4ff059088b3f7f14c0672d155218a1802d4:999:27 onGlobalMessage@http://localhost:3000/packages/meteor.js?9730f4ff059088b3f7f14c0672d155218a1802d4:365:23 ```
2016/02/20
['https://Stackoverflow.com/questions/35522805', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2498182/']
Here is some [helpful documentation](https://meteorhacks.com/subscription-manager-for-iron-router/) on managing subscriptions for Iron Router. I'm pretty sure your `findOne()` is returning `undefined` at this point, which means your findOne().title is going to throw an exception. You'll want to use `waitOn()` to get your subscriptions ready before querying data.
Thanks to Stephen Woods I found that my initial code printed both the exception and the title just because of reactivity. And everything I had to do is wait for subscriptions from iron:router. ``` Router.route('/news/:_id', function() { this.render('l_basic'); console.log (newsCollection.findOne().title); }, { waitOn: function () { return Meteor.subscribe('news'); }); ```
12,410,727
I have a list of `<li>` items being generated from a CMS/DB. Each `<li>` has a `<div>` in it which contains a link to a lightbox (a hidden `<div>`). The link targets the id of the hidden `<div>` (#inline-content-print) so the javascript plugin triggers and pulls up the lightbox. The problem I'm running into is that all of the `<li>`s on the page generate with the same hidden `div` id (I can change this to classes). So no matter which `<li>` href is clicked, it always pulls up the lightbox for the first `<li>` on the page (the first instance of the id). I need a way for the href to say "open #inline-content-print" from THIS `div` (the one the link being clicked lives in)". ``` <li> <div class="store-buttons-bg hide-print-buttons-{tag_Hide-Print-Buttons}"> <a href="#inline-content-print" class="various store-button">PRINT</a> <div style="display: none;" id="inline-content-print"> CONTENT OF LIGHTBOX </div> <!-- end inline-content-print --> </div> </li> ``` Any advice would be greatly appreciated.
2012/09/13
['https://Stackoverflow.com/questions/12410727', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1669207/']
**If I'm not wrong, when a `before` callback returns `false`, the transaction gets rolled back.** That's probably what's happening. ``` def check_new_record self.is_new = self.new_record? end ``` When `self.new_record?` returns `false`, it assigns `false` to `self.is_new` and then the method returns `self.is_new`, which is `false` too. Try this instead: ``` def check_new_record self.is_new = self.new_record? true end ```
For one thing, you can get rid of the hack you have to detect if the record is new in the after\_save. If the record is new, the .changed? method will return true. ``` class Video < ActiveRecord::Base after_save :index_me def index_me Resque.enqueue(IndexVideo, self.id) if self.changed? end end ```
11,460,929
This is more of a theory question than a programming question. As you know when you instantiate a table view in iOS, you have to account for dequeuing and reusing table cells, when they are scrolled in and out of view. The confusing thing to me is, all the data that populates the cells is cached anyway. When you look at a web page in safari, you are scrolling past a lot more images and text that remains after you scroll past it. I have iOS games installed that use many times more data (e.g., Asphalt 6) than a simple table. So I'm just curious why Apple goes to the trouble of dequeuing and reusing table cells. Thanks.
2012/07/12
['https://Stackoverflow.com/questions/11460929', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/591487/']
It's not about the amount of data in the model. It is more so about the amount of memory that is used in creating the Cell views. If I have a table that is going to create over 1000 `UITableViewCell` objects, why would it create them all when only about a dozen or so can appear on the screen? Don't just think about the data that is held and being displayed, think about the memory that is taken up in the objects that are displaying the data, the `UITableViewCell`s.
It's just good memory management. There's no telling how big a table could be, so better safe than sorry. You only ever need the memory for however many cells fit in a view.
1,404,832
is it possible to initialize a List with other List's in C#? Say I've got these to lists: ``` List<int> set1 = new List<int>() {1, 2, 3}; List<int> set2 = new List<int>() {4, 5, 6}; ``` What I'd like to have is a shorthand for this code: ``` List<int> fullSet = new List<int>(); fullSet.AddRange(set1); fullSet.AddRange(set2); ``` Thanks in advance!
2009/09/10
['https://Stackoverflow.com/questions/1404832', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16440/']
``` static void Main(string[] args) { List<int> set1 = new List<int>() { 1, 2, 3 }; List<int> set2 = new List<int>() { 4, 5, 6 }; List<int> set3 = new List<int>(Combine(set1, set2)); } private static IEnumerable<T> Combine<T>(IEnumerable<T> list1, IEnumerable<T> list2) { foreach (var item in list1) { yield return item; } foreach (var item in list2) { yield return item; } } ```
``` var fullSet = set1.Union(set2); // returns IEnumerable<int> ``` If you want List<int> instead of IEnumerable<int> you could do: ``` List<int> fullSet = new List<int>(set1.Union(set2)); ```
1,404,832
is it possible to initialize a List with other List's in C#? Say I've got these to lists: ``` List<int> set1 = new List<int>() {1, 2, 3}; List<int> set2 = new List<int>() {4, 5, 6}; ``` What I'd like to have is a shorthand for this code: ``` List<int> fullSet = new List<int>(); fullSet.AddRange(set1); fullSet.AddRange(set2); ``` Thanks in advance!
2009/09/10
['https://Stackoverflow.com/questions/1404832', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16440/']
To allow duplicate elements (as in your example): ``` List<int> fullSet = set1.Concat(set2).ToList(); ``` This can be generalized for more lists, i.e. `...Concat(set3).Concat(set4)`. If you want to remove duplicate elements (those items that appear in both lists): ``` List<int> fullSet = set1.Union(set2).ToList(); ```
``` var fullSet = set1.Union(set2); // returns IEnumerable<int> ``` If you want List<int> instead of IEnumerable<int> you could do: ``` List<int> fullSet = new List<int>(set1.Union(set2)); ```
1,404,832
is it possible to initialize a List with other List's in C#? Say I've got these to lists: ``` List<int> set1 = new List<int>() {1, 2, 3}; List<int> set2 = new List<int>() {4, 5, 6}; ``` What I'd like to have is a shorthand for this code: ``` List<int> fullSet = new List<int>(); fullSet.AddRange(set1); fullSet.AddRange(set2); ``` Thanks in advance!
2009/09/10
['https://Stackoverflow.com/questions/1404832', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16440/']
``` static void Main(string[] args) { List<int> set1 = new List<int>() { 1, 2, 3 }; List<int> set2 = new List<int>() { 4, 5, 6 }; List<int> set3 = new List<int>(Combine(set1, set2)); } private static IEnumerable<T> Combine<T>(IEnumerable<T> list1, IEnumerable<T> list2) { foreach (var item in list1) { yield return item; } foreach (var item in list2) { yield return item; } } ```
``` List<int> fullSet = new List<int>(set1.Union(set2)); ``` may work.
1,404,832
is it possible to initialize a List with other List's in C#? Say I've got these to lists: ``` List<int> set1 = new List<int>() {1, 2, 3}; List<int> set2 = new List<int>() {4, 5, 6}; ``` What I'd like to have is a shorthand for this code: ``` List<int> fullSet = new List<int>(); fullSet.AddRange(set1); fullSet.AddRange(set2); ``` Thanks in advance!
2009/09/10
['https://Stackoverflow.com/questions/1404832', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16440/']
To allow duplicate elements (as in your example): ``` List<int> fullSet = set1.Concat(set2).ToList(); ``` This can be generalized for more lists, i.e. `...Concat(set3).Concat(set4)`. If you want to remove duplicate elements (those items that appear in both lists): ``` List<int> fullSet = set1.Union(set2).ToList(); ```
``` List<int> fullSet = new List<int>(set1.Union(set2)); ``` may work.
1,404,832
is it possible to initialize a List with other List's in C#? Say I've got these to lists: ``` List<int> set1 = new List<int>() {1, 2, 3}; List<int> set2 = new List<int>() {4, 5, 6}; ``` What I'd like to have is a shorthand for this code: ``` List<int> fullSet = new List<int>(); fullSet.AddRange(set1); fullSet.AddRange(set2); ``` Thanks in advance!
2009/09/10
['https://Stackoverflow.com/questions/1404832', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16440/']
To allow duplicate elements (as in your example): ``` List<int> fullSet = set1.Concat(set2).ToList(); ``` This can be generalized for more lists, i.e. `...Concat(set3).Concat(set4)`. If you want to remove duplicate elements (those items that appear in both lists): ``` List<int> fullSet = set1.Union(set2).ToList(); ```
``` static void Main(string[] args) { List<int> set1 = new List<int>() { 1, 2, 3 }; List<int> set2 = new List<int>() { 4, 5, 6 }; List<int> set3 = new List<int>(Combine(set1, set2)); } private static IEnumerable<T> Combine<T>(IEnumerable<T> list1, IEnumerable<T> list2) { foreach (var item in list1) { yield return item; } foreach (var item in list2) { yield return item; } } ```
49,292,885
I need to have `TabbedPage` throughout the app. In the first page Tab's are displaying fine. When I am starting second page From Tab1, It is hiding all tabs. How can I have Tab's all over the app. [![First page with tabs](https://i.stack.imgur.com/A5yVm.png)](https://i.stack.imgur.com/A5yVm.png) [![Second page without tabs](https://i.stack.imgur.com/pCEH2.png)](https://i.stack.imgur.com/pCEH2.png) MainPage.xaml ``` <?xml version="1.0" encoding="utf-8" ?> <TabbedPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="TabbedApp.MainPage" xmlns:local="clr-namespace:TabbedApp"> <local:DairyTabs></local:DairyTabs> <ContentPage Title="Tab 2"> <StackLayout> <Label Text="Tab 2" HorizontalTextAlignment="Center" HorizontalOptions="FillAndExpand" Margin="5" /> </StackLayout> </ContentPage> </TabbedPage> ``` This is the code from starting 2nd page ``` btnDemo.Clicked +=async delegate { await Navigation.PushModalAsync(new Page2()); }; ```
2018/03/15
['https://Stackoverflow.com/questions/49292885', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8977696/']
> > I need to have TabbedPage throughout the app > > > You must add a `NavigationPage` as a child page in your TabbedPage in order to open pages inside the tab So in your Xaml, you can have a `NavigationPage` inside TabbedPage ``` <TabbedPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="TabbedApp.MainPage" xmlns:local="clr-namespace:TabbedApp"> <local:PageA/> <NavigationPage Title="Your Title"> <x:Arguments> <local:MyPage /> </x:Arguments> </NavigationPage> </TabbedPage> ``` Then you can add pages like this ``` public class MainPageCS : TabbedPage{ public MainPageCS () { var navigationPage = new NavigationPage (new MyPage ()); navigationPage.Title = "Your title"; Children.Add (new PageA ()); Children.Add (navigationPage); } } ``` So Navigation can be performed from this second page which is a instance of NavigationPage, like below ``` async void OnSomeButtonClicked (object sender, EventArgs e) { await Navigation.PushAsync (new Page2()); } ``` More info in this [here](https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/navigation/tabbed-page)
Try to use: `Navigation.PushAsync(new Page2());` Instead of: `Navigation.PushModalAsync(new Page2());`
1,628,058
Ok. this one's a challenge. I have a tableview within a navigation controller. I push it from the root, where I have an add action that allows me to add a new record. That works fine. Now what I've tried to do is add this tableview to a tab bar view (without a tab bar controller cuz that won't work) but within the same navigation controller. So what I want to do is this: Root > TabBarView (loads Tableview) > add new record. The problem lies in the managed object context, I get the whole "can't find entity error" but I have no idea how to fix it. I've managed to get the AddRecord modal view controller to show up from the tabBarView, but it presents itself without a navigationbar, whereas if I try to add a record in the solitary tableView (outside of the tabbar) its no problem. I'm now calling my methods from the TabBarView's navigationBarbuttons, routing through to the tableviews methods. I know my methods have to be called from the tabBarView instead of the actual tableview now, and they do fire, but I don't know how to manage the MOC when its in a tabView. Oh, and this is based on coredata recipes and books, so when the add record method is fired, it creates a new MOC to create it, then reintegrates back in the main MOC when you're done. Any ideas?
2009/10/27
['https://Stackoverflow.com/questions/1628058', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/188710/']
In the Intellij configuration that you use to start the server, set 'Server host' to the hostname of your machine. If it is set to 'localhost' you can't connect using the actual hostname of the machine.
You should launch Grails with debug parameters (grailsDebug) and create a Remote debug run configuration in IntelliJ IDEA's Run Configurations combobox. Enter your host name and port there and you can connect now.
1,803,867
thanks for taking the time to look at my problems. I was trying to calculate the norm of $(3, 1 + \sqrt{-17})$ and $(\sqrt{-17})$. The second one is 17 because of the norm of the element $\sqrt{-17}$, but how does this follow from $|\mathbb{Z}[\sqrt{-17}]/(\sqrt{-17})|$? I tried to calculate $|\mathbb{Z}[\sqrt{-17}]/(3, 1+\sqrt{-17})|$ and concluded that $\mathbb{Z}[\sqrt{-17}]/(3, 1+\sqrt{-17}) \cong \mathbb{Z}/3\mathbb{Z}$ such that $|\mathbb{Z}[\sqrt{-17}]/(3, 1+\sqrt{-17})| = 3$. Is this correct? Thanks in advance!
2016/05/28
['https://math.stackexchange.com/questions/1803867', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/296749/']
Your computations are correct. Since $-17\equiv3\bmod{4}$ our ring of integers is $\mathbb{Z}[\sqrt{-17}]$, so we may factor the ideal $(3)$ in $\mathbb{Z}[\sqrt{-17}]$ by factoring $$x^2 + 17 \equiv x^2 - 1 \equiv (x+1)(x+2) \bmod{3}.$$ This yields the ideal $(3,1+\sqrt{-17})$, and since 3 splits the norm of this ideal is 3. To see this more directly, we can use the ring isomorphism theorems. We have $(x^2+17) \subseteq (3,1+x) \subseteq \mathbb{Z}[x]$ from above, hence $$\mathbb{Z}[\sqrt{-17}]/(3,1+\sqrt{-17}) \cong \mathbb{Z}[x]/(3,1+x) \cong \mathbb{Z}/3$$ As for $(\sqrt{-17})$, the same argument works.
Given $a+b\sqrt{-17}$, you can subtract $b(1+\sqrt{-17})$ to get a rational integer, then subtract an appropriate multiple of 3 to get 0, 1, or 2. So the quotient ring has at most 3 elements, indeed, has number of elements a divisor of 3, so it now suffices to show it's not 1. If it's 1, then 1 is in the ideal, $1=3(a+b\sqrt{-17})+(1+\sqrt{-17})(c+d\sqrt{-17})$. Multiply everything out, and equate rational terms and equate irrational terms, to get the equations, $1=3a+c-17d$, $0=3b+c+d$. Subtraction yields $1=3(a-b-6d)$, a clear impossibility, so it's 3.
1,803,867
thanks for taking the time to look at my problems. I was trying to calculate the norm of $(3, 1 + \sqrt{-17})$ and $(\sqrt{-17})$. The second one is 17 because of the norm of the element $\sqrt{-17}$, but how does this follow from $|\mathbb{Z}[\sqrt{-17}]/(\sqrt{-17})|$? I tried to calculate $|\mathbb{Z}[\sqrt{-17}]/(3, 1+\sqrt{-17})|$ and concluded that $\mathbb{Z}[\sqrt{-17}]/(3, 1+\sqrt{-17}) \cong \mathbb{Z}/3\mathbb{Z}$ such that $|\mathbb{Z}[\sqrt{-17}]/(3, 1+\sqrt{-17})| = 3$. Is this correct? Thanks in advance!
2016/05/28
['https://math.stackexchange.com/questions/1803867', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/296749/']
Your computations are correct. Since $-17\equiv3\bmod{4}$ our ring of integers is $\mathbb{Z}[\sqrt{-17}]$, so we may factor the ideal $(3)$ in $\mathbb{Z}[\sqrt{-17}]$ by factoring $$x^2 + 17 \equiv x^2 - 1 \equiv (x+1)(x+2) \bmod{3}.$$ This yields the ideal $(3,1+\sqrt{-17})$, and since 3 splits the norm of this ideal is 3. To see this more directly, we can use the ring isomorphism theorems. We have $(x^2+17) \subseteq (3,1+x) \subseteq \mathbb{Z}[x]$ from above, hence $$\mathbb{Z}[\sqrt{-17}]/(3,1+\sqrt{-17}) \cong \mathbb{Z}[x]/(3,1+x) \cong \mathbb{Z}/3$$ As for $(\sqrt{-17})$, the same argument works.
You already seem know that the norm of a prinicipal ideal is the norm of its generator. Hence $|\mathbb Z[\sqrt{-17}]/(3)|=9$. We have $(3) \subsetneq (3,1+\sqrt{-17}) \subsetneq (1)$, hence $\mathbb Z[\sqrt{-17}]/(3,1+\sqrt{-17})$ is a non-trivial quotient of $\mathbb Z[\sqrt{-17}]/(3)$. A non-trivial quotient of a group with $9$ elements must have $3$ elements, hence we obtain $$|\mathbb Z[\sqrt{-17}]/(3,1+\sqrt{-17})|=3$$ without having calculated the quotient (Which would be of course an easy task, too, as shown in the other answers).
19,533,566
I have a LinearLayout with a white background,filled with a bunch of LinearLayouts and RelativeLayouts. I've tried to set the parent layout to have a minimum height, but it still seems to be wrapping to the content. Here's a picture of what it looks like now. The white space should have a set minimum height that is greater than it is now. ![enter image description here](https://i.stack.imgur.com/SSrnO.png) Here's what I think is a relevant section of the xml: ``` <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/contactViewScrollView" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#ABABAB" > <LinearLayout android:layout_width="match_parent" android:layout_height="300dip" android:background="#FFFFFF" android:orientation="vertical" > <RelativeLayout android:id="@+id/contactHeader" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="#EDEDED" android:paddingLeft="10dp" > <TextView android:id="@+id/fullName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginRight="175dip" android:paddingTop="5dp" android:textSize="18sp" /> <View android:layout_width="1dp" android:layout_height="90dp" android:layout_toLeftOf="@+id/image" android:background="#000000" /> <ImageView android:id="@+id/image" android:layout_width="90dp" android:layout_height="90dp" android:layout_alignParentRight="true" android:background="#D6D6D6" android:contentDescription="@string/contact_image_description" android:scaleType="centerCrop" /> </RelativeLayout> <View android:layout_width="fill_parent" android:layout_height="1dp" android:background="#000000" /> <LinearLayout android:id="@+id/mobile" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:paddingLeft="10dp" > <TextView android:id="@+id/mobilePhoneHeading" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingTop="15dp" android:text="@string/mobile_phone" android:textColor="#787878" /> <TextView android:id="@+id/mobilePhone" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingBottom="10dp" android:paddingTop="2dp" android:textSize="18sp" /> </LinearLayout> ``` ... and many other LinearLayouts, all set to 'GONE' programmatically. Can anyone suggest a fix? I can't figure out why that white section is taking up so little space.
2013/10/23
['https://Stackoverflow.com/questions/19533566', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2175846/']
``` // try this <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/contactViewScrollView" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ABABAB" > <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <LinearLayout android:layout_width="match_parent" android:layout_height="300dp" android:background="#FFFFFF" android:orientation="vertical" > <RelativeLayout android:id="@+id/contactHeader" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#EDEDED" android:paddingLeft="10dp" > <TextView android:id="@+id/fullName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginRight="175dp" android:paddingTop="5dp" android:textSize="18sp" /> <View android:layout_width="1dp" android:layout_height="90dp" android:layout_toLeftOf="@id/image" android:background="#000000" /> <ImageView android:id="@+id/image" android:layout_width="90dp" android:layout_height="90dp" android:layout_alignParentRight="true" android:background="#D6D6D6" android:contentDescription="contact_image_description" android:scaleType="centerCrop" /> </RelativeLayout> <View android:layout_width="fill_parent" android:layout_height="1dp" android:background="#000000" /> <LinearLayout android:id="@+id/mobile" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:paddingLeft="10dp" > <TextView android:id="@+id/mobilePhoneHeading" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingTop="15dp" android:text="mobile_phone" android:textColor="#787878" /> <TextView android:id="@+id/mobilePhone" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingBottom="10dp" android:paddingTop="2dp" android:textSize="18sp" /> </LinearLayout> </LinearLayout> </LinearLayout> </ScrollView> ```
set the height in second linearlayout. now it is set as wrap content.. do like ``` <LinearLayout android:id="@+id/mobile" android:layout_width="match_parent" android:layout_height="50dp" //for example android:orientation="vertical" android:paddingLeft="10dp" > <TextView android:id="@+id/mobilePhoneHeading" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingTop="15dp" android:text="@string/mobile_phone" android:textColor="#787878" /> <TextView android:id="@+id/mobilePhone" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingBottom="10dp" android:paddingTop="2dp" android:textSize="18sp" /> </LinearLayout> ```
19,533,566
I have a LinearLayout with a white background,filled with a bunch of LinearLayouts and RelativeLayouts. I've tried to set the parent layout to have a minimum height, but it still seems to be wrapping to the content. Here's a picture of what it looks like now. The white space should have a set minimum height that is greater than it is now. ![enter image description here](https://i.stack.imgur.com/SSrnO.png) Here's what I think is a relevant section of the xml: ``` <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/contactViewScrollView" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#ABABAB" > <LinearLayout android:layout_width="match_parent" android:layout_height="300dip" android:background="#FFFFFF" android:orientation="vertical" > <RelativeLayout android:id="@+id/contactHeader" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="#EDEDED" android:paddingLeft="10dp" > <TextView android:id="@+id/fullName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginRight="175dip" android:paddingTop="5dp" android:textSize="18sp" /> <View android:layout_width="1dp" android:layout_height="90dp" android:layout_toLeftOf="@+id/image" android:background="#000000" /> <ImageView android:id="@+id/image" android:layout_width="90dp" android:layout_height="90dp" android:layout_alignParentRight="true" android:background="#D6D6D6" android:contentDescription="@string/contact_image_description" android:scaleType="centerCrop" /> </RelativeLayout> <View android:layout_width="fill_parent" android:layout_height="1dp" android:background="#000000" /> <LinearLayout android:id="@+id/mobile" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:paddingLeft="10dp" > <TextView android:id="@+id/mobilePhoneHeading" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingTop="15dp" android:text="@string/mobile_phone" android:textColor="#787878" /> <TextView android:id="@+id/mobilePhone" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingBottom="10dp" android:paddingTop="2dp" android:textSize="18sp" /> </LinearLayout> ``` ... and many other LinearLayouts, all set to 'GONE' programmatically. Can anyone suggest a fix? I can't figure out why that white section is taking up so little space.
2013/10/23
['https://Stackoverflow.com/questions/19533566', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2175846/']
``` // try this <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/contactViewScrollView" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ABABAB" > <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <LinearLayout android:layout_width="match_parent" android:layout_height="300dp" android:background="#FFFFFF" android:orientation="vertical" > <RelativeLayout android:id="@+id/contactHeader" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#EDEDED" android:paddingLeft="10dp" > <TextView android:id="@+id/fullName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginRight="175dp" android:paddingTop="5dp" android:textSize="18sp" /> <View android:layout_width="1dp" android:layout_height="90dp" android:layout_toLeftOf="@id/image" android:background="#000000" /> <ImageView android:id="@+id/image" android:layout_width="90dp" android:layout_height="90dp" android:layout_alignParentRight="true" android:background="#D6D6D6" android:contentDescription="contact_image_description" android:scaleType="centerCrop" /> </RelativeLayout> <View android:layout_width="fill_parent" android:layout_height="1dp" android:background="#000000" /> <LinearLayout android:id="@+id/mobile" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:paddingLeft="10dp" > <TextView android:id="@+id/mobilePhoneHeading" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingTop="15dp" android:text="mobile_phone" android:textColor="#787878" /> <TextView android:id="@+id/mobilePhone" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingBottom="10dp" android:paddingTop="2dp" android:textSize="18sp" /> </LinearLayout> </LinearLayout> </LinearLayout> </ScrollView> ```
It can be because of the device size too. I'd definitely suggest using linear layout's weight. That should make it perfect on all the devices irrespective of tablet or phone. Let me know if you want any more guidance, or if you have any issues with weight.
18,835,104
I have a library in User Space that intercepts socket layer calls such as `socket()`, `connect()`, `accept()`, etc. I'm only dealing with TCP sockets. Down in Kernel Space I have a network kernel module, which deals with all the TCP connections. I need to be able to identify in the driver which sockets were intercepted by the User Space library. So far I've been using the `priority` field from `struct sock` (Kernel) that I can set with `setsockopt()` in User Space. But that's quite a dirty hack. Is there any kind of private field of `struct sock` I could safely use and set from User Space through `setsockopt()`? Thanks.
2013/09/16
['https://Stackoverflow.com/questions/18835104', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1181890/']
There is really no such "private field" option that can be used solely by user space and your kernel code. Using the `SO_PRIORITY` option seems a little too intrusive, as it can change how the stack processes packets, and it might lead to hard to understand results. A safer option would be to adjust the `SO_RCVBUF` or `SO_SNDBUF` values by some small delta from the usual default. Linux will double the value passed in, but you can look for the delta from the default values and know that the presence of the delta as a signal that this is your "intercepted" socket.
Getting to your original question "I need to be able to identify in the driver which sockets were intercepted by the User Space library." there are a few functions in fact. Firstly you need to know that ALL the existing connections are stored in a global hash table - "tcp\_hashinfo", and you can find the address in /proc/kallsyms. The main function is \_\_inet\_lookup\_skb(), which called \_\_inet\_lookup(), and split into \_\_inet\_lookup\_established() (looking for any matching sockets that have been established) and \_\_inet\_lookup\_listener() (looking for opened listener, but no established connections yet). The main inputs required for lookup is the source/destination ports and IP addresses information, if found the returning pointer is a "struct sock \*" to the socket. IPv6 has about the same name, and same logic too. The function (\_\_inet\_lookup\_skb()) is declared "static inline" - it cannot be found from /proc/kallsyms and neither can drivers see it, as it is compiled inline. But no problem for that as this call two other function - inet\_lookup\_listener() and inet\_lookup\_established() which are NOT compiled inline. Symbols for it are exported, so you are safe to use it from a kernel module. It is important that reading this hashinfo table is a critical operation - multiple CPUs may be reading/writing to it at the same time, and which is why locking is done at the beginning/end of functions when reading is done, to be prevent it being modified while being read. As it is difficult to access these RCU locks, even though it is global by nature, don't re-implement these functions, just reuse them.
13,086,869
I am creating a 12 month calendar using the individual calendar controls for each month. Since I am controlling the calendars (Jan - Dec) via separate next year and previous year buttons, I want to remove the previous and next calendaritem buttons from the individual calendars and disable the ability to change the display mode. Since I am new to XAML and more comfortable with doing this in code, I would prefer to change the style at runtime but willing to learn how to make it happen via XAML but I am having a very difficult time finding an example of someone doing something like this. Hope someone can help.
2012/10/26
['https://Stackoverflow.com/questions/13086869', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1777028/']
I would refer you to [this](http://msdn.microsoft.com/en-us/magazine/dd882520.aspx) article to get some basic understanding of Calendar control. In short, you need to modify CalendarItemStyle and remove PART\_PreviousButton and PART\_NextButton from its template. You can find default template for all parts of Calendar control [here](http://msdn.microsoft.com/en-us/library/ff468218.aspx). When you create a new calendar item style without those parts then set it to [CalendarItemStyle](http://msdn.microsoft.com/en-us/library/system.windows.controls.calendar.calendaritemstyle.aspx) property of your calendar in XAML.
Like Chris, I didn't want to mess with a ton a XAML. I also needed to hide/show dynamically. I imagine there is a way to do this with bindings in XAML as well, but I thought this was a pretty simple start. Just add a new class with this code, then use this derived control instead. Edit: I updated it to have a property you can set, HidePrevNextBtns. If checked/true, buttons will be hidden. This code does make a couple assumptions. One is that the template will also have prev/next buttons, and other is they will be visible by default. ``` class MyCalendar : Calendar { public Button PrevBtn; public Button NextBtn; protected bool _HidePrevNextBtns; public bool HidePrevNextBtns { get { return (_HidePrevNextBtns); } set { _HidePrevNextBtns = value; if (PrevBtn != null) { PrevBtn.Visibility = _HidePrevNextBtns ? Visibility.Hidden : Visibility.Visible; NextBtn.Visibility = _HidePrevNextBtns ? Visibility.Hidden : Visibility.Visible; } } } public override void OnApplyTemplate() { base.OnApplyTemplate(); var cal = this.Template.FindName("PART_CalendarItem", this) as CalendarItem; cal.Loaded += new RoutedEventHandler(cal_Loaded); } void cal_Loaded(object sender, RoutedEventArgs e) { var cal = sender as CalendarItem; PrevBtn = cal.Template.FindName("PART_PreviousButton", cal) as Button; NextBtn = cal.Template.FindName("PART_NextButton", cal) as Button; if (_HidePrevNextBtns) { PrevBtn.Visibility = Visibility.Hidden; NextBtn.Visibility = Visibility.Hidden; } } } ```
13,086,869
I am creating a 12 month calendar using the individual calendar controls for each month. Since I am controlling the calendars (Jan - Dec) via separate next year and previous year buttons, I want to remove the previous and next calendaritem buttons from the individual calendars and disable the ability to change the display mode. Since I am new to XAML and more comfortable with doing this in code, I would prefer to change the style at runtime but willing to learn how to make it happen via XAML but I am having a very difficult time finding an example of someone doing something like this. Hope someone can help.
2012/10/26
['https://Stackoverflow.com/questions/13086869', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1777028/']
Well, after lots of digging, many examples and Dodsky pointing me in the right direction. I figured it out and felt that sharing was the best way to repay the developer community. Since, I am new to XAML it is a small victory in project battle that I am in. Hopefully, it will help other newbies like me. I will try to explain the best way that I can to show you how to manipulate the calendar any way that you need to. In my UserControl ``` <Calendar CalendarItemStyle="{DynamicResource calItemStyle}" Name="calJan" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" HorizontalAlignment="Center" VerticalAlignment="Center" OverridesDefaultStyle="False" IsEnabled="True" /> ``` Some of the parameters are overkill, the main point is the Dynamic Resource ``` CalendarItemStyle="{DynamicResource calItemStyle}" ``` In my ResourceDictionary, I added the namespace ``` xmlns:primitives="clr-namespace:System.Windows.Controls.Primitives;assembly=PresentationFramework" ``` You will also want to add the PresentationFramework reference to your project, if it is not already there. ``` <Style x:Key="calItemStyle" TargetType="primitives:CalendarItem"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="primitives:CalendarItem"> <ControlTemplate.Resources> <DataTemplate x:Key="DayTitleTemplate"> <TextBlock Text="{Binding}" HorizontalAlignment="Center" /> </DataTemplate> </ControlTemplate.Resources> <DockPanel Name="PART_Root" LastChildFill="True"> <Button x:Name="PART_PreviousButton" DockPanel.Dock="Left" Content="&lt;" Focusable="False" Visibility="Hidden" /> <Button x:Name="PART_NextButton" DockPanel.Dock="Right" Content="&gt;" Focusable="False" Visibility="Hidden" /> <Button x:Name="PART_HeaderButton" DockPanel.Dock="Top" FontWeight="Bold" Focusable="False" /> <Grid> <Grid x:Name="PART_MonthView" Visibility="Visible"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="Auto"/> </Grid.ColumnDefinitions> </Grid> <Grid x:Name="PART_YearView" Visibility="Hidden"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="Auto"/> </Grid.ColumnDefinitions> </Grid> </Grid> <Rectangle x:Name="PART_DisabledVisual" Opacity="0" Visibility="Collapsed" Fill="#A5FFFFFF"/> </DockPanel> <ControlTemplate.Triggers> <Trigger Property="IsEnabled" Value="False"> <Setter TargetName="PART_DisabledVisual" Property="Visibility" Value="Visible" /> </Trigger> <DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType={x:Type Calendar}}, Path=DisplayMode}" Value="Year"> <Setter TargetName="PART_MonthView" Property="Visibility" Value="Hidden" /> <Setter TargetName="PART_YearView" Property="Visibility" Value="Visible" /> </DataTrigger> <DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType={x:Type Calendar}}, Path=DisplayMode}" Value="Decade"> <Setter TargetName="PART_MonthView" Property="Visibility" Value="Hidden" /> <Setter TargetName="PART_YearView" Property="Visibility" Value="Visible" /> </DataTrigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> ``` I chose to hide the Previous and Next buttons, just in case removal caused a problem with any events but otherwise, it does what I want it to and I can add or take away features as needed. Hope this helps others.
Like Chris, I didn't want to mess with a ton a XAML. I also needed to hide/show dynamically. I imagine there is a way to do this with bindings in XAML as well, but I thought this was a pretty simple start. Just add a new class with this code, then use this derived control instead. Edit: I updated it to have a property you can set, HidePrevNextBtns. If checked/true, buttons will be hidden. This code does make a couple assumptions. One is that the template will also have prev/next buttons, and other is they will be visible by default. ``` class MyCalendar : Calendar { public Button PrevBtn; public Button NextBtn; protected bool _HidePrevNextBtns; public bool HidePrevNextBtns { get { return (_HidePrevNextBtns); } set { _HidePrevNextBtns = value; if (PrevBtn != null) { PrevBtn.Visibility = _HidePrevNextBtns ? Visibility.Hidden : Visibility.Visible; NextBtn.Visibility = _HidePrevNextBtns ? Visibility.Hidden : Visibility.Visible; } } } public override void OnApplyTemplate() { base.OnApplyTemplate(); var cal = this.Template.FindName("PART_CalendarItem", this) as CalendarItem; cal.Loaded += new RoutedEventHandler(cal_Loaded); } void cal_Loaded(object sender, RoutedEventArgs e) { var cal = sender as CalendarItem; PrevBtn = cal.Template.FindName("PART_PreviousButton", cal) as Button; NextBtn = cal.Template.FindName("PART_NextButton", cal) as Button; if (_HidePrevNextBtns) { PrevBtn.Visibility = Visibility.Hidden; NextBtn.Visibility = Visibility.Hidden; } } } ```
11,287,899
Is this possible to generate a new Zabbix event from a Ruby script? I was suggested to use [zabbix\_sender](http://www.zabbix.com/documentation/1.8/manpages/zabbix_sender) script, but I couldn't find any example. Also, I couldn't find any API related to the [events](http://www.zabbix.com/documentation/1.8/api/event) creation.
2012/07/02
['https://Stackoverflow.com/questions/11287899', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/398309/']
You can use clientX or pageX, see [here](http://www.sitepen.com/blog/2011/12/07/touching-and-gesturing-on-iphone-android-and-more/)
Was having similar issue on binding event-handler using jQuery's `.on` function on `canvas` element (Don't know the reason). I resolved it by binding event-handler using `addEventListener`. The `event` object in the handler has offsetX and offsetY defined with proper values. Hope it helps...
11,287,899
Is this possible to generate a new Zabbix event from a Ruby script? I was suggested to use [zabbix\_sender](http://www.zabbix.com/documentation/1.8/manpages/zabbix_sender) script, but I couldn't find any example. Also, I couldn't find any API related to the [events](http://www.zabbix.com/documentation/1.8/api/event) creation.
2012/07/02
['https://Stackoverflow.com/questions/11287899', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/398309/']
You can use clientX or pageX, see [here](http://www.sitepen.com/blog/2011/12/07/touching-and-gesturing-on-iphone-android-and-more/)
The page - offset / client approach did not work for me. There was still an offset. I found this other solution that works perfectly: ``` let r = canvas.getBoundingClientRect(); let x = e.touches[0].pageX - r.left; let y = e.touches[0].pageY - r.top; ```
11,287,899
Is this possible to generate a new Zabbix event from a Ruby script? I was suggested to use [zabbix\_sender](http://www.zabbix.com/documentation/1.8/manpages/zabbix_sender) script, but I couldn't find any example. Also, I couldn't find any API related to the [events](http://www.zabbix.com/documentation/1.8/api/event) creation.
2012/07/02
['https://Stackoverflow.com/questions/11287899', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/398309/']
You can use clientX or pageX, see [here](http://www.sitepen.com/blog/2011/12/07/touching-and-gesturing-on-iphone-android-and-more/)
Thanks, @Kontiki - this is the solution that finally fixed things for me: ``` if("touchmove" == e.type) { let r = canvas.getBoundingClientRect(); currX = e.touches[0].clientX - r.left; currY = e.touches[0].clientY - r.top; } else { currX = e.offsetX; currY = e.offsetY; } ```
11,287,899
Is this possible to generate a new Zabbix event from a Ruby script? I was suggested to use [zabbix\_sender](http://www.zabbix.com/documentation/1.8/manpages/zabbix_sender) script, but I couldn't find any example. Also, I couldn't find any API related to the [events](http://www.zabbix.com/documentation/1.8/api/event) creation.
2012/07/02
['https://Stackoverflow.com/questions/11287899', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/398309/']
The correct answer based on the comments in the suggested answer: ``` e.offsetX = e.touches[0].pageX - e.touches[0].target.offsetLeft; e.offsetY = e.touches[0].pageY - e.touches[0].target.offsetTop; ``` This ignores any transformations such as rotations or scaling. Also be sure to check if there are any touches.
Was having similar issue on binding event-handler using jQuery's `.on` function on `canvas` element (Don't know the reason). I resolved it by binding event-handler using `addEventListener`. The `event` object in the handler has offsetX and offsetY defined with proper values. Hope it helps...
11,287,899
Is this possible to generate a new Zabbix event from a Ruby script? I was suggested to use [zabbix\_sender](http://www.zabbix.com/documentation/1.8/manpages/zabbix_sender) script, but I couldn't find any example. Also, I couldn't find any API related to the [events](http://www.zabbix.com/documentation/1.8/api/event) creation.
2012/07/02
['https://Stackoverflow.com/questions/11287899', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/398309/']
The page - offset / client approach did not work for me. There was still an offset. I found this other solution that works perfectly: ``` let r = canvas.getBoundingClientRect(); let x = e.touches[0].pageX - r.left; let y = e.touches[0].pageY - r.top; ```
Was having similar issue on binding event-handler using jQuery's `.on` function on `canvas` element (Don't know the reason). I resolved it by binding event-handler using `addEventListener`. The `event` object in the handler has offsetX and offsetY defined with proper values. Hope it helps...
11,287,899
Is this possible to generate a new Zabbix event from a Ruby script? I was suggested to use [zabbix\_sender](http://www.zabbix.com/documentation/1.8/manpages/zabbix_sender) script, but I couldn't find any example. Also, I couldn't find any API related to the [events](http://www.zabbix.com/documentation/1.8/api/event) creation.
2012/07/02
['https://Stackoverflow.com/questions/11287899', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/398309/']
Thanks, @Kontiki - this is the solution that finally fixed things for me: ``` if("touchmove" == e.type) { let r = canvas.getBoundingClientRect(); currX = e.touches[0].clientX - r.left; currY = e.touches[0].clientY - r.top; } else { currX = e.offsetX; currY = e.offsetY; } ```
Was having similar issue on binding event-handler using jQuery's `.on` function on `canvas` element (Don't know the reason). I resolved it by binding event-handler using `addEventListener`. The `event` object in the handler has offsetX and offsetY defined with proper values. Hope it helps...
11,287,899
Is this possible to generate a new Zabbix event from a Ruby script? I was suggested to use [zabbix\_sender](http://www.zabbix.com/documentation/1.8/manpages/zabbix_sender) script, but I couldn't find any example. Also, I couldn't find any API related to the [events](http://www.zabbix.com/documentation/1.8/api/event) creation.
2012/07/02
['https://Stackoverflow.com/questions/11287899', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/398309/']
The correct answer based on the comments in the suggested answer: ``` e.offsetX = e.touches[0].pageX - e.touches[0].target.offsetLeft; e.offsetY = e.touches[0].pageY - e.touches[0].target.offsetTop; ``` This ignores any transformations such as rotations or scaling. Also be sure to check if there are any touches.
The page - offset / client approach did not work for me. There was still an offset. I found this other solution that works perfectly: ``` let r = canvas.getBoundingClientRect(); let x = e.touches[0].pageX - r.left; let y = e.touches[0].pageY - r.top; ```
11,287,899
Is this possible to generate a new Zabbix event from a Ruby script? I was suggested to use [zabbix\_sender](http://www.zabbix.com/documentation/1.8/manpages/zabbix_sender) script, but I couldn't find any example. Also, I couldn't find any API related to the [events](http://www.zabbix.com/documentation/1.8/api/event) creation.
2012/07/02
['https://Stackoverflow.com/questions/11287899', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/398309/']
The correct answer based on the comments in the suggested answer: ``` e.offsetX = e.touches[0].pageX - e.touches[0].target.offsetLeft; e.offsetY = e.touches[0].pageY - e.touches[0].target.offsetTop; ``` This ignores any transformations such as rotations or scaling. Also be sure to check if there are any touches.
Thanks, @Kontiki - this is the solution that finally fixed things for me: ``` if("touchmove" == e.type) { let r = canvas.getBoundingClientRect(); currX = e.touches[0].clientX - r.left; currY = e.touches[0].clientY - r.top; } else { currX = e.offsetX; currY = e.offsetY; } ```
232,858
Are all sentences below correct? * I parked in the parking lot. * I parked on the parking lot. * I parked at the parking lot. My understanding is that I can use "to park in" if the parking lot is indoors and "to park at" with any kind of parking lot, but I'm not sure if "to park on" is usual for both indoor and outdoor parking lots.
2019/12/18
['https://ell.stackexchange.com/questions/232858', 'https://ell.stackexchange.com', 'https://ell.stackexchange.com/users/92124/']
When talking about a structure for holding cars, such as a lot, you park *in*. "I parked in the lot." "I parked in the parking garage." You can also talk about parking *on* a surface or *on* a street/road. "I parked on the concrete". "I parked on 4th Avenue." "Parking on grass is not good for your car." In this sense, saying you parked "on the lot" is also acceptable (but not as common) because the lot is a surface. You never park *on* a parking garage or other fixed structure that your goes goes inside of. You can also park *at* a location or destination. "I parked at the store." In this case, the store is your destination. This is a more colloquial way of saying "I parked in the store's parking lot." In the same sense, you could say you parked *at* a lot or a garage, since they are also locations. "I parked at the lot on 5th Street." sounds natural. The lot on 5th Street is a location that you parked at. This can get even more complicated: If you parked in a parking garage located on 6th Street, you could say "I parked on 6th Street" and then clarify with "in the parking garage." In some cases, all of these are interchangeable. If a friend asks, "where did you park?", you could say "At the lot on 5th Ave" OR "On the lot on 5th Ave" OR "In the lot on 5th Ave". Any of these works because in this situation, the lot could be considered either a location or a surface/structure for cars.
I think you use "to park in" both when it’s outdoors and indoors. I have never heard someone saying "to park at" or "to park on".
232,858
Are all sentences below correct? * I parked in the parking lot. * I parked on the parking lot. * I parked at the parking lot. My understanding is that I can use "to park in" if the parking lot is indoors and "to park at" with any kind of parking lot, but I'm not sure if "to park on" is usual for both indoor and outdoor parking lots.
2019/12/18
['https://ell.stackexchange.com/questions/232858', 'https://ell.stackexchange.com', 'https://ell.stackexchange.com/users/92124/']
> > I parked in the parking lot. > > > This is correct whether the parking lot is enclosed in some way or not (it doesn't matter). The use of "in" here generally means "within the borders of". This is also the same sense you would use when saying "I parked in a parking space" as well. > > I parked on the parking lot. > > > This is not common usage for parking lots. It's grammatically correct, but the use of "on" emphasizes the idea of "on top of", and most parking lots don't actually have a "top" (they're open-air spaces with no roofs), so it seems a bit odd to say this. However, it is common to say something like "I parked on the asphalt" or "I parked on the street", because those are flat things you can put a car on top of. > > I parked at the parking lot. > > > This is also fine. This is using "at" in the sense of a location which you went to and then you parked there. In general: * "in" is the most common way to say this, and you can use it really any time you are inside of some area with well-defined boundaries (e.g. "in the parking lot", "in the yard", etc) * "at" is also fine, and would not sound particularly strange in most situations. * "on" would sound strange to most people.
I think you use "to park in" both when it’s outdoors and indoors. I have never heard someone saying "to park at" or "to park on".
232,858
Are all sentences below correct? * I parked in the parking lot. * I parked on the parking lot. * I parked at the parking lot. My understanding is that I can use "to park in" if the parking lot is indoors and "to park at" with any kind of parking lot, but I'm not sure if "to park on" is usual for both indoor and outdoor parking lots.
2019/12/18
['https://ell.stackexchange.com/questions/232858', 'https://ell.stackexchange.com', 'https://ell.stackexchange.com/users/92124/']
When talking about a structure for holding cars, such as a lot, you park *in*. "I parked in the lot." "I parked in the parking garage." You can also talk about parking *on* a surface or *on* a street/road. "I parked on the concrete". "I parked on 4th Avenue." "Parking on grass is not good for your car." In this sense, saying you parked "on the lot" is also acceptable (but not as common) because the lot is a surface. You never park *on* a parking garage or other fixed structure that your goes goes inside of. You can also park *at* a location or destination. "I parked at the store." In this case, the store is your destination. This is a more colloquial way of saying "I parked in the store's parking lot." In the same sense, you could say you parked *at* a lot or a garage, since they are also locations. "I parked at the lot on 5th Street." sounds natural. The lot on 5th Street is a location that you parked at. This can get even more complicated: If you parked in a parking garage located on 6th Street, you could say "I parked on 6th Street" and then clarify with "in the parking garage." In some cases, all of these are interchangeable. If a friend asks, "where did you park?", you could say "At the lot on 5th Ave" OR "On the lot on 5th Ave" OR "In the lot on 5th Ave". Any of these works because in this situation, the lot could be considered either a location or a surface/structure for cars.
> > I parked in the parking lot. > > > This is correct whether the parking lot is enclosed in some way or not (it doesn't matter). The use of "in" here generally means "within the borders of". This is also the same sense you would use when saying "I parked in a parking space" as well. > > I parked on the parking lot. > > > This is not common usage for parking lots. It's grammatically correct, but the use of "on" emphasizes the idea of "on top of", and most parking lots don't actually have a "top" (they're open-air spaces with no roofs), so it seems a bit odd to say this. However, it is common to say something like "I parked on the asphalt" or "I parked on the street", because those are flat things you can put a car on top of. > > I parked at the parking lot. > > > This is also fine. This is using "at" in the sense of a location which you went to and then you parked there. In general: * "in" is the most common way to say this, and you can use it really any time you are inside of some area with well-defined boundaries (e.g. "in the parking lot", "in the yard", etc) * "at" is also fine, and would not sound particularly strange in most situations. * "on" would sound strange to most people.
64,173,564
I'm trying to upgrade my Spring Boot 2.3.4 app to use Flyway 7.0.0 (the latest version). Previously it was using Flyway 6.5.6. The relevant entries in `build.gradle` are shown below. ``` buildscript { ext { flywayVersion = "7.0.0" // changed from 6.5.6 } } plugins { id "org.flywaydb.flyway" version "${flywayVersion}" } dependencies { implementation "org.flywaydb:flyway-core:${flywayVersion}" } flyway { url = "jdbc:postgresql://0.0.0.0:5432/postgres" user = "postgres" password = "secret" } ``` The following error occurs when I start the app e.g. with `./gradlew bootRun` > > > > --- > > > APPLICATION FAILED TO START > > > > > --- > > > Description: > > > An attempt was made to call a method that does not exist. The attempt > was made from the following location: > > > > ``` > org.springframework.boot.autoconfigure.flyway.FlywayMigrationInitializer.afterPropertiesSet(FlywayMigrationInitializer.java:65) > > ``` > > The following method did not exist: > > > > ``` > 'int org.flywaydb.core.Flyway.migrate()' > > ``` > > The method's class, org.flywaydb.core.Flyway, is available from the > following locations: > > > > ``` > jar:file:/Users/antonio/.gradle/caches/modules-2/files-2.1/org.flywaydb/flyway-core/7.0.0/623494c303c62080ca1bc5886098ee65d1a5528a/flyway-core-7.0.0.jar!/org/flywaydb/core/Flyway.class > > ``` > > The class hierarchy was loaded from the following locations: > > > > ``` > org.flywaydb.core.Flyway: file:/Users/antonio/.gradle/caches/modules-2/files-2.1/org.flywaydb/flyway-core/7.0.0/623494c303c62080ca1bc5886098ee65d1a5528a/flyway-core-7.0.0.jar > > ``` > > Action: > > > Correct the classpath of your application so that it contains a > single, compatible version of org.flywaydb.core.Flyway > > >
2020/10/02
['https://Stackoverflow.com/questions/64173564', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4786956/']
Basically, see Philip's comment on your question. Flyway 7.x.x is not currently compatible with Spring Boot 2.3.4 Temporary solution is to just downgrade to Flyway 6.5.7 (the last 6.x.x version) until Spring Boot 2.3.5 is released. Read more and follow the issue here: <https://github.com/spring-projects/spring-boot/issues/23514> Support for Flyway's new configuration options: <https://github.com/spring-projects/spring-boot/issues/23579>
downgrade to Flyway 6.5.7 works.
64,173,564
I'm trying to upgrade my Spring Boot 2.3.4 app to use Flyway 7.0.0 (the latest version). Previously it was using Flyway 6.5.6. The relevant entries in `build.gradle` are shown below. ``` buildscript { ext { flywayVersion = "7.0.0" // changed from 6.5.6 } } plugins { id "org.flywaydb.flyway" version "${flywayVersion}" } dependencies { implementation "org.flywaydb:flyway-core:${flywayVersion}" } flyway { url = "jdbc:postgresql://0.0.0.0:5432/postgres" user = "postgres" password = "secret" } ``` The following error occurs when I start the app e.g. with `./gradlew bootRun` > > > > --- > > > APPLICATION FAILED TO START > > > > > --- > > > Description: > > > An attempt was made to call a method that does not exist. The attempt > was made from the following location: > > > > ``` > org.springframework.boot.autoconfigure.flyway.FlywayMigrationInitializer.afterPropertiesSet(FlywayMigrationInitializer.java:65) > > ``` > > The following method did not exist: > > > > ``` > 'int org.flywaydb.core.Flyway.migrate()' > > ``` > > The method's class, org.flywaydb.core.Flyway, is available from the > following locations: > > > > ``` > jar:file:/Users/antonio/.gradle/caches/modules-2/files-2.1/org.flywaydb/flyway-core/7.0.0/623494c303c62080ca1bc5886098ee65d1a5528a/flyway-core-7.0.0.jar!/org/flywaydb/core/Flyway.class > > ``` > > The class hierarchy was loaded from the following locations: > > > > ``` > org.flywaydb.core.Flyway: file:/Users/antonio/.gradle/caches/modules-2/files-2.1/org.flywaydb/flyway-core/7.0.0/623494c303c62080ca1bc5886098ee65d1a5528a/flyway-core-7.0.0.jar > > ``` > > Action: > > > Correct the classpath of your application so that it contains a > single, compatible version of org.flywaydb.core.Flyway > > >
2020/10/02
['https://Stackoverflow.com/questions/64173564', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4786956/']
Basically, see Philip's comment on your question. Flyway 7.x.x is not currently compatible with Spring Boot 2.3.4 Temporary solution is to just downgrade to Flyway 6.5.7 (the last 6.x.x version) until Spring Boot 2.3.5 is released. Read more and follow the issue here: <https://github.com/spring-projects/spring-boot/issues/23514> Support for Flyway's new configuration options: <https://github.com/spring-projects/spring-boot/issues/23579>
In Flyway 7 the signature of `migrate` changed. To get Flyway 7.x.x working with Spring Boot 2.3.x you can provide a custom FlywayMigrationStrategy implementation, which calls the the right `migrate` method. ``` import org.flywaydb.core.Flyway; import org.springframework.boot.autoconfigure.flyway.FlywayMigrationStrategy; import org.springframework.stereotype.Component; @Component public class FlywayMigrationStrategyImpl implements FlywayMigrationStrategy { @Override public void migrate(Flyway flyway) { flyway.migrate(); } } ```
64,173,564
I'm trying to upgrade my Spring Boot 2.3.4 app to use Flyway 7.0.0 (the latest version). Previously it was using Flyway 6.5.6. The relevant entries in `build.gradle` are shown below. ``` buildscript { ext { flywayVersion = "7.0.0" // changed from 6.5.6 } } plugins { id "org.flywaydb.flyway" version "${flywayVersion}" } dependencies { implementation "org.flywaydb:flyway-core:${flywayVersion}" } flyway { url = "jdbc:postgresql://0.0.0.0:5432/postgres" user = "postgres" password = "secret" } ``` The following error occurs when I start the app e.g. with `./gradlew bootRun` > > > > --- > > > APPLICATION FAILED TO START > > > > > --- > > > Description: > > > An attempt was made to call a method that does not exist. The attempt > was made from the following location: > > > > ``` > org.springframework.boot.autoconfigure.flyway.FlywayMigrationInitializer.afterPropertiesSet(FlywayMigrationInitializer.java:65) > > ``` > > The following method did not exist: > > > > ``` > 'int org.flywaydb.core.Flyway.migrate()' > > ``` > > The method's class, org.flywaydb.core.Flyway, is available from the > following locations: > > > > ``` > jar:file:/Users/antonio/.gradle/caches/modules-2/files-2.1/org.flywaydb/flyway-core/7.0.0/623494c303c62080ca1bc5886098ee65d1a5528a/flyway-core-7.0.0.jar!/org/flywaydb/core/Flyway.class > > ``` > > The class hierarchy was loaded from the following locations: > > > > ``` > org.flywaydb.core.Flyway: file:/Users/antonio/.gradle/caches/modules-2/files-2.1/org.flywaydb/flyway-core/7.0.0/623494c303c62080ca1bc5886098ee65d1a5528a/flyway-core-7.0.0.jar > > ``` > > Action: > > > Correct the classpath of your application so that it contains a > single, compatible version of org.flywaydb.core.Flyway > > >
2020/10/02
['https://Stackoverflow.com/questions/64173564', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4786956/']
In Flyway 7 the signature of `migrate` changed. To get Flyway 7.x.x working with Spring Boot 2.3.x you can provide a custom FlywayMigrationStrategy implementation, which calls the the right `migrate` method. ``` import org.flywaydb.core.Flyway; import org.springframework.boot.autoconfigure.flyway.FlywayMigrationStrategy; import org.springframework.stereotype.Component; @Component public class FlywayMigrationStrategyImpl implements FlywayMigrationStrategy { @Override public void migrate(Flyway flyway) { flyway.migrate(); } } ```
downgrade to Flyway 6.5.7 works.
502,374
I have this spec file that will install numerous rpm packages such as apache, mysql, etc. I'm new to building rpms and I did looked at the Fedora documentation but I did not find the answer to my question. How do I add commands in my spec file so that if I do a: ``` rpm -e yum erase ``` it will stop services that wasn't stopped during yum erase/rpm-e? Thanks.
2013/04/24
['https://serverfault.com/questions/502374', 'https://serverfault.com', 'https://serverfault.com/users/163460/']
It may not be relevant to this case, but remember that if you will upgrade your RPM, rpm will install the new version and then remove the old one, so after upgrade the services will be down. To be on the safe side, do: ``` %preun if [[ $1 -eq 0 ]] then service https stop # or what ever you want fi ```
There is a section in spec file preun which runs before package is uninstalled: ``` %preun service https stop # or what ever you want ```
14,755,569
I have some floated divs where I can't use display: inline-block because some of those divs are jqxSwitchButtons and using that inline-block would mess everything around those buttons. [Here](http://jsfiddle.net/Luigino/Ps3zE/) is a JSFiddle example where I commented some lines that are jqxSwitchButtons and I'd like to center in the middle those divs. Code from JSFiddle: ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> </head> <body> <center> <table style="padding:1px;margin:1px;color:#00417B;font-size:12px;border:2px solid #525252;border-collapse: collapse;background-color:white;width: 100%;" border=1> <tr><td> <div style="display: block; align:center; width: 100%; margin-left: auto; margin-right: auto; padding-right: auto; padding-left: auto; text-align: center;"> <div style="float: left; margin-top: 5px; font-weight: bold; ">Element 1</div> <div><div style="float: left; margin-left: 5px; margin-right: 5px; margin-top: 2px; margin-bottom: 2px; border: 0.1em solid green; width: 10px; height: 21px;"><div id="element_1" style="float: left;"></div></div></div> <!-- jqxSwitchButton --> <div style="float: left; margin-top: 5px; font-weight: bold; ">Element 2</div> <div><div style="float: left; margin-left: 5px; margin-right: 5px; margin-top: 2px; margin-bottom: 2px; border: 0.1em solid green; width: 10px; height: 21px;"><div id="element_2" style="float: left;"></div></div></div> <!-- jqxSwitchButton --> <div style="float: left; margin-top: 5px; font-weight: bold; ">Element 3</div> <div><div style="float: left; margin-left: 5px; margin-right: 5px; margin-top: 2px; margin-bottom: 2px; border: 0.1em solid green; width: 10px; height: 21px;"><div id="element_3" style="float: left;"></div></div></div> <!-- jqxSwitchButton --> <div style="float: left; margin-left: 1px">|</div> <div style="float: left; margin-left: 2px"><input type="button" id="btnCompute" value="Compute" onClick="Compute()" style="margin-top: 4px"></div> <div style="float: left; margin-left: 1px">|</div> <div style="float: left; margin-top: 5px; margin-left: 2px; font-weight: bold; ">Auto-compute</div> <div><div style="float: left; margin-left: 5px; margin-right: 5px; margin-top: 2px; margin-bottom: 2px; border: 0.1em solid green; width: 10px; height: 21px;"><div id="recompute" style="float: left;"></div></div></div> <!-- jqxSwitchButton --> <div style="float: left; margin-top: 5px; margin-left: 2px; font-weight: bold; "><input type="checkbox" name="chkAutoRecompute" id="chkAutoRecompute" value="0" style="display: none" ></div> </div> </td></tr> </table> </center> </body> </html> ``` Any suggestions?
2013/02/07
['https://Stackoverflow.com/questions/14755569', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1487979/']
You can use a meteorite package. accounts-anonymous <https://github.com/tmeasday/meteor-accounts-anonymous> So you use ``` Meteor.loginAnonymously(); ``` if the user visits your page for the first time, and use .allow to check what you need
Use a session or localStorage key. When the visitor submits the form check if the key has been set, and if it has, reject the insert.
14,755,569
I have some floated divs where I can't use display: inline-block because some of those divs are jqxSwitchButtons and using that inline-block would mess everything around those buttons. [Here](http://jsfiddle.net/Luigino/Ps3zE/) is a JSFiddle example where I commented some lines that are jqxSwitchButtons and I'd like to center in the middle those divs. Code from JSFiddle: ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> </head> <body> <center> <table style="padding:1px;margin:1px;color:#00417B;font-size:12px;border:2px solid #525252;border-collapse: collapse;background-color:white;width: 100%;" border=1> <tr><td> <div style="display: block; align:center; width: 100%; margin-left: auto; margin-right: auto; padding-right: auto; padding-left: auto; text-align: center;"> <div style="float: left; margin-top: 5px; font-weight: bold; ">Element 1</div> <div><div style="float: left; margin-left: 5px; margin-right: 5px; margin-top: 2px; margin-bottom: 2px; border: 0.1em solid green; width: 10px; height: 21px;"><div id="element_1" style="float: left;"></div></div></div> <!-- jqxSwitchButton --> <div style="float: left; margin-top: 5px; font-weight: bold; ">Element 2</div> <div><div style="float: left; margin-left: 5px; margin-right: 5px; margin-top: 2px; margin-bottom: 2px; border: 0.1em solid green; width: 10px; height: 21px;"><div id="element_2" style="float: left;"></div></div></div> <!-- jqxSwitchButton --> <div style="float: left; margin-top: 5px; font-weight: bold; ">Element 3</div> <div><div style="float: left; margin-left: 5px; margin-right: 5px; margin-top: 2px; margin-bottom: 2px; border: 0.1em solid green; width: 10px; height: 21px;"><div id="element_3" style="float: left;"></div></div></div> <!-- jqxSwitchButton --> <div style="float: left; margin-left: 1px">|</div> <div style="float: left; margin-left: 2px"><input type="button" id="btnCompute" value="Compute" onClick="Compute()" style="margin-top: 4px"></div> <div style="float: left; margin-left: 1px">|</div> <div style="float: left; margin-top: 5px; margin-left: 2px; font-weight: bold; ">Auto-compute</div> <div><div style="float: left; margin-left: 5px; margin-right: 5px; margin-top: 2px; margin-bottom: 2px; border: 0.1em solid green; width: 10px; height: 21px;"><div id="recompute" style="float: left;"></div></div></div> <!-- jqxSwitchButton --> <div style="float: left; margin-top: 5px; margin-left: 2px; font-weight: bold; "><input type="checkbox" name="chkAutoRecompute" id="chkAutoRecompute" value="0" style="display: none" ></div> </div> </td></tr> </table> </center> </body> </html> ``` Any suggestions?
2013/02/07
['https://Stackoverflow.com/questions/14755569', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1487979/']
To get the ip address, the observatory (<https://github.com/jhoxray/observatory>) project uses this: in coffee: ``` Meteor.userIP = (uid)-> ret = {} if uid? s = ss for k, ss of Meteor.default_server.sessions when ss.userId is uid if s ret.forwardedFor = s.socket?.headers?['x-forwarded-for'] ret.remoteAddress = s.socket?.remoteAddress ret ``` Which returns an object like `{ forwardedFor: '192.168.5.4', remoteAddress: '192.168.5.4' }`
Use a session or localStorage key. When the visitor submits the form check if the key has been set, and if it has, reject the insert.
14,755,569
I have some floated divs where I can't use display: inline-block because some of those divs are jqxSwitchButtons and using that inline-block would mess everything around those buttons. [Here](http://jsfiddle.net/Luigino/Ps3zE/) is a JSFiddle example where I commented some lines that are jqxSwitchButtons and I'd like to center in the middle those divs. Code from JSFiddle: ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> </head> <body> <center> <table style="padding:1px;margin:1px;color:#00417B;font-size:12px;border:2px solid #525252;border-collapse: collapse;background-color:white;width: 100%;" border=1> <tr><td> <div style="display: block; align:center; width: 100%; margin-left: auto; margin-right: auto; padding-right: auto; padding-left: auto; text-align: center;"> <div style="float: left; margin-top: 5px; font-weight: bold; ">Element 1</div> <div><div style="float: left; margin-left: 5px; margin-right: 5px; margin-top: 2px; margin-bottom: 2px; border: 0.1em solid green; width: 10px; height: 21px;"><div id="element_1" style="float: left;"></div></div></div> <!-- jqxSwitchButton --> <div style="float: left; margin-top: 5px; font-weight: bold; ">Element 2</div> <div><div style="float: left; margin-left: 5px; margin-right: 5px; margin-top: 2px; margin-bottom: 2px; border: 0.1em solid green; width: 10px; height: 21px;"><div id="element_2" style="float: left;"></div></div></div> <!-- jqxSwitchButton --> <div style="float: left; margin-top: 5px; font-weight: bold; ">Element 3</div> <div><div style="float: left; margin-left: 5px; margin-right: 5px; margin-top: 2px; margin-bottom: 2px; border: 0.1em solid green; width: 10px; height: 21px;"><div id="element_3" style="float: left;"></div></div></div> <!-- jqxSwitchButton --> <div style="float: left; margin-left: 1px">|</div> <div style="float: left; margin-left: 2px"><input type="button" id="btnCompute" value="Compute" onClick="Compute()" style="margin-top: 4px"></div> <div style="float: left; margin-left: 1px">|</div> <div style="float: left; margin-top: 5px; margin-left: 2px; font-weight: bold; ">Auto-compute</div> <div><div style="float: left; margin-left: 5px; margin-right: 5px; margin-top: 2px; margin-bottom: 2px; border: 0.1em solid green; width: 10px; height: 21px;"><div id="recompute" style="float: left;"></div></div></div> <!-- jqxSwitchButton --> <div style="float: left; margin-top: 5px; margin-left: 2px; font-weight: bold; "><input type="checkbox" name="chkAutoRecompute" id="chkAutoRecompute" value="0" style="display: none" ></div> </div> </td></tr> </table> </center> </body> </html> ``` Any suggestions?
2013/02/07
['https://Stackoverflow.com/questions/14755569', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1487979/']
You can use a meteorite package. accounts-anonymous <https://github.com/tmeasday/meteor-accounts-anonymous> So you use ``` Meteor.loginAnonymously(); ``` if the user visits your page for the first time, and use .allow to check what you need
You can do something like this: ``` if (Meteor.isClient) { Meteor.startup(function () { Session.set('currentuser', 'something randomly generated by another function'); } } ``` and check if the 'currentuser' already has inserted in your database.
14,755,569
I have some floated divs where I can't use display: inline-block because some of those divs are jqxSwitchButtons and using that inline-block would mess everything around those buttons. [Here](http://jsfiddle.net/Luigino/Ps3zE/) is a JSFiddle example where I commented some lines that are jqxSwitchButtons and I'd like to center in the middle those divs. Code from JSFiddle: ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> </head> <body> <center> <table style="padding:1px;margin:1px;color:#00417B;font-size:12px;border:2px solid #525252;border-collapse: collapse;background-color:white;width: 100%;" border=1> <tr><td> <div style="display: block; align:center; width: 100%; margin-left: auto; margin-right: auto; padding-right: auto; padding-left: auto; text-align: center;"> <div style="float: left; margin-top: 5px; font-weight: bold; ">Element 1</div> <div><div style="float: left; margin-left: 5px; margin-right: 5px; margin-top: 2px; margin-bottom: 2px; border: 0.1em solid green; width: 10px; height: 21px;"><div id="element_1" style="float: left;"></div></div></div> <!-- jqxSwitchButton --> <div style="float: left; margin-top: 5px; font-weight: bold; ">Element 2</div> <div><div style="float: left; margin-left: 5px; margin-right: 5px; margin-top: 2px; margin-bottom: 2px; border: 0.1em solid green; width: 10px; height: 21px;"><div id="element_2" style="float: left;"></div></div></div> <!-- jqxSwitchButton --> <div style="float: left; margin-top: 5px; font-weight: bold; ">Element 3</div> <div><div style="float: left; margin-left: 5px; margin-right: 5px; margin-top: 2px; margin-bottom: 2px; border: 0.1em solid green; width: 10px; height: 21px;"><div id="element_3" style="float: left;"></div></div></div> <!-- jqxSwitchButton --> <div style="float: left; margin-left: 1px">|</div> <div style="float: left; margin-left: 2px"><input type="button" id="btnCompute" value="Compute" onClick="Compute()" style="margin-top: 4px"></div> <div style="float: left; margin-left: 1px">|</div> <div style="float: left; margin-top: 5px; margin-left: 2px; font-weight: bold; ">Auto-compute</div> <div><div style="float: left; margin-left: 5px; margin-right: 5px; margin-top: 2px; margin-bottom: 2px; border: 0.1em solid green; width: 10px; height: 21px;"><div id="recompute" style="float: left;"></div></div></div> <!-- jqxSwitchButton --> <div style="float: left; margin-top: 5px; margin-left: 2px; font-weight: bold; "><input type="checkbox" name="chkAutoRecompute" id="chkAutoRecompute" value="0" style="display: none" ></div> </div> </td></tr> </table> </center> </body> </html> ``` Any suggestions?
2013/02/07
['https://Stackoverflow.com/questions/14755569', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1487979/']
To get the ip address, the observatory (<https://github.com/jhoxray/observatory>) project uses this: in coffee: ``` Meteor.userIP = (uid)-> ret = {} if uid? s = ss for k, ss of Meteor.default_server.sessions when ss.userId is uid if s ret.forwardedFor = s.socket?.headers?['x-forwarded-for'] ret.remoteAddress = s.socket?.remoteAddress ret ``` Which returns an object like `{ forwardedFor: '192.168.5.4', remoteAddress: '192.168.5.4' }`
You can do something like this: ``` if (Meteor.isClient) { Meteor.startup(function () { Session.set('currentuser', 'something randomly generated by another function'); } } ``` and check if the 'currentuser' already has inserted in your database.
14,755,569
I have some floated divs where I can't use display: inline-block because some of those divs are jqxSwitchButtons and using that inline-block would mess everything around those buttons. [Here](http://jsfiddle.net/Luigino/Ps3zE/) is a JSFiddle example where I commented some lines that are jqxSwitchButtons and I'd like to center in the middle those divs. Code from JSFiddle: ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> </head> <body> <center> <table style="padding:1px;margin:1px;color:#00417B;font-size:12px;border:2px solid #525252;border-collapse: collapse;background-color:white;width: 100%;" border=1> <tr><td> <div style="display: block; align:center; width: 100%; margin-left: auto; margin-right: auto; padding-right: auto; padding-left: auto; text-align: center;"> <div style="float: left; margin-top: 5px; font-weight: bold; ">Element 1</div> <div><div style="float: left; margin-left: 5px; margin-right: 5px; margin-top: 2px; margin-bottom: 2px; border: 0.1em solid green; width: 10px; height: 21px;"><div id="element_1" style="float: left;"></div></div></div> <!-- jqxSwitchButton --> <div style="float: left; margin-top: 5px; font-weight: bold; ">Element 2</div> <div><div style="float: left; margin-left: 5px; margin-right: 5px; margin-top: 2px; margin-bottom: 2px; border: 0.1em solid green; width: 10px; height: 21px;"><div id="element_2" style="float: left;"></div></div></div> <!-- jqxSwitchButton --> <div style="float: left; margin-top: 5px; font-weight: bold; ">Element 3</div> <div><div style="float: left; margin-left: 5px; margin-right: 5px; margin-top: 2px; margin-bottom: 2px; border: 0.1em solid green; width: 10px; height: 21px;"><div id="element_3" style="float: left;"></div></div></div> <!-- jqxSwitchButton --> <div style="float: left; margin-left: 1px">|</div> <div style="float: left; margin-left: 2px"><input type="button" id="btnCompute" value="Compute" onClick="Compute()" style="margin-top: 4px"></div> <div style="float: left; margin-left: 1px">|</div> <div style="float: left; margin-top: 5px; margin-left: 2px; font-weight: bold; ">Auto-compute</div> <div><div style="float: left; margin-left: 5px; margin-right: 5px; margin-top: 2px; margin-bottom: 2px; border: 0.1em solid green; width: 10px; height: 21px;"><div id="recompute" style="float: left;"></div></div></div> <!-- jqxSwitchButton --> <div style="float: left; margin-top: 5px; margin-left: 2px; font-weight: bold; "><input type="checkbox" name="chkAutoRecompute" id="chkAutoRecompute" value="0" style="display: none" ></div> </div> </td></tr> </table> </center> </body> </html> ``` Any suggestions?
2013/02/07
['https://Stackoverflow.com/questions/14755569', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1487979/']
You can use a meteorite package. accounts-anonymous <https://github.com/tmeasday/meteor-accounts-anonymous> So you use ``` Meteor.loginAnonymously(); ``` if the user visits your page for the first time, and use .allow to check what you need
To get the ip address, the observatory (<https://github.com/jhoxray/observatory>) project uses this: in coffee: ``` Meteor.userIP = (uid)-> ret = {} if uid? s = ss for k, ss of Meteor.default_server.sessions when ss.userId is uid if s ret.forwardedFor = s.socket?.headers?['x-forwarded-for'] ret.remoteAddress = s.socket?.remoteAddress ret ``` Which returns an object like `{ forwardedFor: '192.168.5.4', remoteAddress: '192.168.5.4' }`
76,593
in my header and other sections I would like to use ``` <script src="/incs/js/script.js"></script> ``` While maintaining the default theme folder structure in server as below ``` /wp-content/themes/theme-name/incs/js/script.js ``` file need to be accessed via browser/html source if need be so that it hides **/wp-content/themes/theme-name** ``` http://website.com/incs/js/script.js ``` This is also applicable to images I may have under /incs/images/imagname.jpg I've seen solutions where defining the directory located outside of theme folder... but need a solution that does this within. Is this possible? Thanks
2012/12/19
['https://wordpress.stackexchange.com/questions/76593', 'https://wordpress.stackexchange.com', 'https://wordpress.stackexchange.com/users/16419/']
The easiest way to move your theme folder is only via constant; include the wp-content folder. You can set a constant for the plugin folder and wp-content folder. Then is your plugins and themes in separete url, also in the include in the source of the frontend. like this example for my dev installs: ``` define( 'WP_CONTENT_DIR', dirname( __FILE__ ) . '/wp-content' ); define( 'WP_CONTENT_URL', 'http://' . $_SERVER['HTTP_HOST'] . '/wp-content' ); // Custom plugin directory define( 'WP_PLUGIN_DIR', dirname( __FILE__ ) . '/wp-plugins' ); define( 'WP_PLUGIN_URL', 'http://' . $_SERVER['HTTP_HOST'] . '/wp-plugins' ); // Custom mu plugin directory define( 'WPMU_PLUGIN_DIR', dirname( __FILE__ ) . '/wpmu-plugins' ); define( 'WPMU_PLUGIN_URL', 'http://' . $_SERVER['HTTP_HOST'] . '/wpmu-plugins' ); ```
Why dont you use bloginfo(); default wordpress functions ``` <?php bloginfo( $show ); ?> <script src="<?php bloginfo('template_directory'); ?>/incs/js/script.js"></script> ``` more info <http://codex.wordpress.org/Function_Reference/bloginfo>
76,593
in my header and other sections I would like to use ``` <script src="/incs/js/script.js"></script> ``` While maintaining the default theme folder structure in server as below ``` /wp-content/themes/theme-name/incs/js/script.js ``` file need to be accessed via browser/html source if need be so that it hides **/wp-content/themes/theme-name** ``` http://website.com/incs/js/script.js ``` This is also applicable to images I may have under /incs/images/imagname.jpg I've seen solutions where defining the directory located outside of theme folder... but need a solution that does this within. Is this possible? Thanks
2012/12/19
['https://wordpress.stackexchange.com/questions/76593', 'https://wordpress.stackexchange.com', 'https://wordpress.stackexchange.com/users/16419/']
The easiest way to move your theme folder is only via constant; include the wp-content folder. You can set a constant for the plugin folder and wp-content folder. Then is your plugins and themes in separete url, also in the include in the source of the frontend. like this example for my dev installs: ``` define( 'WP_CONTENT_DIR', dirname( __FILE__ ) . '/wp-content' ); define( 'WP_CONTENT_URL', 'http://' . $_SERVER['HTTP_HOST'] . '/wp-content' ); // Custom plugin directory define( 'WP_PLUGIN_DIR', dirname( __FILE__ ) . '/wp-plugins' ); define( 'WP_PLUGIN_URL', 'http://' . $_SERVER['HTTP_HOST'] . '/wp-plugins' ); // Custom mu plugin directory define( 'WPMU_PLUGIN_DIR', dirname( __FILE__ ) . '/wpmu-plugins' ); define( 'WPMU_PLUGIN_URL', 'http://' . $_SERVER['HTTP_HOST'] . '/wpmu-plugins' ); ```
Nowadays I use the technique I describe in this Q: [Steps to Take to Hide the Fact a Site is Using WordPress?](https://wordpress.stackexchange.com/q/1507/12615). Before that, I used the [Roots Theme method](http://benword.com/how-to-hide-that-youre-using-wordpress/), which is what I think you are looking for: > > This post contains information on how to clean up WordPress code output. The methods described below do not prevent actual fingerprinting and shouldn’t be looked at as any sort of security measure. > > > Note that it doesn't work in Multisite or Child Themes. --- I'll reproduce here the documentation I did for using the Roots method: Modifying `.htaccess` Rewrite Rules ----------------------------------- Large chunk of code directly from the Roots theme: <https://gist.github.com/4336843> [PasteBin mirror](http://pastebin.com/8C2gAb6C). The array `$roots_new_non_wp_rules` has to be adapted accordingly. Refresh permalinks ------------------ Go to `/wp-admin/options-permalink.php` and click `Save Changes`. Load scripts from CDN and not from `/wp-includes/` -------------------------------------------------- ``` add_action( 'wp_enqueue_scripts', 'wpse_76593_scripts_custom' ); function wpse_76593_scripts_custom() { wp_deregister_script('jquery'); wp_register_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js', false, '1.7.1', true); wp_enqueue_script( 'jquery' ); } ``` Search the theme for all style and script registers and enqueues. style.css --------- 1. create a new file inside the folder "/css" named "style.css" 2. open the theme's `style.css` 3. select all declarations bellow the [theme file header](http://codex.wordpress.org/File_Header#Theme_File_Header_Example) 4. cut and paste in the file `/css/style.css` 5. save both in short: `/your-theme/styles.css` will contain only the header information, and `/your-theme/css/styles.css` will contain all the styles * change all occurrences of `url('fonts/` with `url('../fonts/` * change all occurrences of `images/` with `../images/` header.php ---------- Change the stylesheet link from ``` <link rel="stylesheet" type="text/css" media="all" href="<?php bloginfo( 'stylesheet_url' ); ?>" /> ``` to ``` <link rel="stylesheet" type="text/css" media="all" href="<?php echo get_template_directory_uri(); ?>/css/style.css" /> ``` All theme files --------------- Search for: * `get_bloginfo('template_url')` * `get_bloginfo('template_directory')` and replace with: * `get_template_directory_uri()` Testing ------- Not sure about other browsers, but [Safari Activity Window](https://www.google.com/search?q=safari%20activity%20window&hl=es&safe=off&tbo=d&source=lnms&tbm=isch) is perfect to check all loaded files and its URLs. Depending on the theme complexity, extra steps have to be taken.
76,593
in my header and other sections I would like to use ``` <script src="/incs/js/script.js"></script> ``` While maintaining the default theme folder structure in server as below ``` /wp-content/themes/theme-name/incs/js/script.js ``` file need to be accessed via browser/html source if need be so that it hides **/wp-content/themes/theme-name** ``` http://website.com/incs/js/script.js ``` This is also applicable to images I may have under /incs/images/imagname.jpg I've seen solutions where defining the directory located outside of theme folder... but need a solution that does this within. Is this possible? Thanks
2012/12/19
['https://wordpress.stackexchange.com/questions/76593', 'https://wordpress.stackexchange.com', 'https://wordpress.stackexchange.com/users/16419/']
The easiest way to move your theme folder is only via constant; include the wp-content folder. You can set a constant for the plugin folder and wp-content folder. Then is your plugins and themes in separete url, also in the include in the source of the frontend. like this example for my dev installs: ``` define( 'WP_CONTENT_DIR', dirname( __FILE__ ) . '/wp-content' ); define( 'WP_CONTENT_URL', 'http://' . $_SERVER['HTTP_HOST'] . '/wp-content' ); // Custom plugin directory define( 'WP_PLUGIN_DIR', dirname( __FILE__ ) . '/wp-plugins' ); define( 'WP_PLUGIN_URL', 'http://' . $_SERVER['HTTP_HOST'] . '/wp-plugins' ); // Custom mu plugin directory define( 'WPMU_PLUGIN_DIR', dirname( __FILE__ ) . '/wpmu-plugins' ); define( 'WPMU_PLUGIN_URL', 'http://' . $_SERVER['HTTP_HOST'] . '/wpmu-plugins' ); ```
I created the [Roots Plug](http://wordpress.org/extend/plugins/roots-plug/) which has the same `.htaccess` rewrites as the Roots Theme. But completely agree with what @brasofolio [said](https://wordpress.stackexchange.com/a/76605/9605)
76,593
in my header and other sections I would like to use ``` <script src="/incs/js/script.js"></script> ``` While maintaining the default theme folder structure in server as below ``` /wp-content/themes/theme-name/incs/js/script.js ``` file need to be accessed via browser/html source if need be so that it hides **/wp-content/themes/theme-name** ``` http://website.com/incs/js/script.js ``` This is also applicable to images I may have under /incs/images/imagname.jpg I've seen solutions where defining the directory located outside of theme folder... but need a solution that does this within. Is this possible? Thanks
2012/12/19
['https://wordpress.stackexchange.com/questions/76593', 'https://wordpress.stackexchange.com', 'https://wordpress.stackexchange.com/users/16419/']
The easiest way to move your theme folder is only via constant; include the wp-content folder. You can set a constant for the plugin folder and wp-content folder. Then is your plugins and themes in separete url, also in the include in the source of the frontend. like this example for my dev installs: ``` define( 'WP_CONTENT_DIR', dirname( __FILE__ ) . '/wp-content' ); define( 'WP_CONTENT_URL', 'http://' . $_SERVER['HTTP_HOST'] . '/wp-content' ); // Custom plugin directory define( 'WP_PLUGIN_DIR', dirname( __FILE__ ) . '/wp-plugins' ); define( 'WP_PLUGIN_URL', 'http://' . $_SERVER['HTTP_HOST'] . '/wp-plugins' ); // Custom mu plugin directory define( 'WPMU_PLUGIN_DIR', dirname( __FILE__ ) . '/wpmu-plugins' ); define( 'WPMU_PLUGIN_URL', 'http://' . $_SERVER['HTTP_HOST'] . '/wpmu-plugins' ); ```
This can be easily achieved by using '[hide my wp](http://bit.ly/1cyQW91)' plugin. Please change it's permalinks and url settings as shown below: ![Change theme path under Permalinks & urls to /incs](https://i.stack.imgur.com/tHGVs.jpg) Change theme path under Permalinks & urls to `/incs`. Once you have changed these settings, you will notice, `bloginfo('template_url')` will render `http://website.com/incs/` and hence ``` http://website.com/incs/js/script.js ``` Reference: <http://howtomakewebsite.ws/wordpress-plugins/how-to-hide-wordpress/731/>
76,593
in my header and other sections I would like to use ``` <script src="/incs/js/script.js"></script> ``` While maintaining the default theme folder structure in server as below ``` /wp-content/themes/theme-name/incs/js/script.js ``` file need to be accessed via browser/html source if need be so that it hides **/wp-content/themes/theme-name** ``` http://website.com/incs/js/script.js ``` This is also applicable to images I may have under /incs/images/imagname.jpg I've seen solutions where defining the directory located outside of theme folder... but need a solution that does this within. Is this possible? Thanks
2012/12/19
['https://wordpress.stackexchange.com/questions/76593', 'https://wordpress.stackexchange.com', 'https://wordpress.stackexchange.com/users/16419/']
Nowadays I use the technique I describe in this Q: [Steps to Take to Hide the Fact a Site is Using WordPress?](https://wordpress.stackexchange.com/q/1507/12615). Before that, I used the [Roots Theme method](http://benword.com/how-to-hide-that-youre-using-wordpress/), which is what I think you are looking for: > > This post contains information on how to clean up WordPress code output. The methods described below do not prevent actual fingerprinting and shouldn’t be looked at as any sort of security measure. > > > Note that it doesn't work in Multisite or Child Themes. --- I'll reproduce here the documentation I did for using the Roots method: Modifying `.htaccess` Rewrite Rules ----------------------------------- Large chunk of code directly from the Roots theme: <https://gist.github.com/4336843> [PasteBin mirror](http://pastebin.com/8C2gAb6C). The array `$roots_new_non_wp_rules` has to be adapted accordingly. Refresh permalinks ------------------ Go to `/wp-admin/options-permalink.php` and click `Save Changes`. Load scripts from CDN and not from `/wp-includes/` -------------------------------------------------- ``` add_action( 'wp_enqueue_scripts', 'wpse_76593_scripts_custom' ); function wpse_76593_scripts_custom() { wp_deregister_script('jquery'); wp_register_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js', false, '1.7.1', true); wp_enqueue_script( 'jquery' ); } ``` Search the theme for all style and script registers and enqueues. style.css --------- 1. create a new file inside the folder "/css" named "style.css" 2. open the theme's `style.css` 3. select all declarations bellow the [theme file header](http://codex.wordpress.org/File_Header#Theme_File_Header_Example) 4. cut and paste in the file `/css/style.css` 5. save both in short: `/your-theme/styles.css` will contain only the header information, and `/your-theme/css/styles.css` will contain all the styles * change all occurrences of `url('fonts/` with `url('../fonts/` * change all occurrences of `images/` with `../images/` header.php ---------- Change the stylesheet link from ``` <link rel="stylesheet" type="text/css" media="all" href="<?php bloginfo( 'stylesheet_url' ); ?>" /> ``` to ``` <link rel="stylesheet" type="text/css" media="all" href="<?php echo get_template_directory_uri(); ?>/css/style.css" /> ``` All theme files --------------- Search for: * `get_bloginfo('template_url')` * `get_bloginfo('template_directory')` and replace with: * `get_template_directory_uri()` Testing ------- Not sure about other browsers, but [Safari Activity Window](https://www.google.com/search?q=safari%20activity%20window&hl=es&safe=off&tbo=d&source=lnms&tbm=isch) is perfect to check all loaded files and its URLs. Depending on the theme complexity, extra steps have to be taken.
Why dont you use bloginfo(); default wordpress functions ``` <?php bloginfo( $show ); ?> <script src="<?php bloginfo('template_directory'); ?>/incs/js/script.js"></script> ``` more info <http://codex.wordpress.org/Function_Reference/bloginfo>
76,593
in my header and other sections I would like to use ``` <script src="/incs/js/script.js"></script> ``` While maintaining the default theme folder structure in server as below ``` /wp-content/themes/theme-name/incs/js/script.js ``` file need to be accessed via browser/html source if need be so that it hides **/wp-content/themes/theme-name** ``` http://website.com/incs/js/script.js ``` This is also applicable to images I may have under /incs/images/imagname.jpg I've seen solutions where defining the directory located outside of theme folder... but need a solution that does this within. Is this possible? Thanks
2012/12/19
['https://wordpress.stackexchange.com/questions/76593', 'https://wordpress.stackexchange.com', 'https://wordpress.stackexchange.com/users/16419/']
I created the [Roots Plug](http://wordpress.org/extend/plugins/roots-plug/) which has the same `.htaccess` rewrites as the Roots Theme. But completely agree with what @brasofolio [said](https://wordpress.stackexchange.com/a/76605/9605)
Why dont you use bloginfo(); default wordpress functions ``` <?php bloginfo( $show ); ?> <script src="<?php bloginfo('template_directory'); ?>/incs/js/script.js"></script> ``` more info <http://codex.wordpress.org/Function_Reference/bloginfo>
76,593
in my header and other sections I would like to use ``` <script src="/incs/js/script.js"></script> ``` While maintaining the default theme folder structure in server as below ``` /wp-content/themes/theme-name/incs/js/script.js ``` file need to be accessed via browser/html source if need be so that it hides **/wp-content/themes/theme-name** ``` http://website.com/incs/js/script.js ``` This is also applicable to images I may have under /incs/images/imagname.jpg I've seen solutions where defining the directory located outside of theme folder... but need a solution that does this within. Is this possible? Thanks
2012/12/19
['https://wordpress.stackexchange.com/questions/76593', 'https://wordpress.stackexchange.com', 'https://wordpress.stackexchange.com/users/16419/']
This can be easily achieved by using '[hide my wp](http://bit.ly/1cyQW91)' plugin. Please change it's permalinks and url settings as shown below: ![Change theme path under Permalinks & urls to /incs](https://i.stack.imgur.com/tHGVs.jpg) Change theme path under Permalinks & urls to `/incs`. Once you have changed these settings, you will notice, `bloginfo('template_url')` will render `http://website.com/incs/` and hence ``` http://website.com/incs/js/script.js ``` Reference: <http://howtomakewebsite.ws/wordpress-plugins/how-to-hide-wordpress/731/>
Why dont you use bloginfo(); default wordpress functions ``` <?php bloginfo( $show ); ?> <script src="<?php bloginfo('template_directory'); ?>/incs/js/script.js"></script> ``` more info <http://codex.wordpress.org/Function_Reference/bloginfo>
76,593
in my header and other sections I would like to use ``` <script src="/incs/js/script.js"></script> ``` While maintaining the default theme folder structure in server as below ``` /wp-content/themes/theme-name/incs/js/script.js ``` file need to be accessed via browser/html source if need be so that it hides **/wp-content/themes/theme-name** ``` http://website.com/incs/js/script.js ``` This is also applicable to images I may have under /incs/images/imagname.jpg I've seen solutions where defining the directory located outside of theme folder... but need a solution that does this within. Is this possible? Thanks
2012/12/19
['https://wordpress.stackexchange.com/questions/76593', 'https://wordpress.stackexchange.com', 'https://wordpress.stackexchange.com/users/16419/']
Nowadays I use the technique I describe in this Q: [Steps to Take to Hide the Fact a Site is Using WordPress?](https://wordpress.stackexchange.com/q/1507/12615). Before that, I used the [Roots Theme method](http://benword.com/how-to-hide-that-youre-using-wordpress/), which is what I think you are looking for: > > This post contains information on how to clean up WordPress code output. The methods described below do not prevent actual fingerprinting and shouldn’t be looked at as any sort of security measure. > > > Note that it doesn't work in Multisite or Child Themes. --- I'll reproduce here the documentation I did for using the Roots method: Modifying `.htaccess` Rewrite Rules ----------------------------------- Large chunk of code directly from the Roots theme: <https://gist.github.com/4336843> [PasteBin mirror](http://pastebin.com/8C2gAb6C). The array `$roots_new_non_wp_rules` has to be adapted accordingly. Refresh permalinks ------------------ Go to `/wp-admin/options-permalink.php` and click `Save Changes`. Load scripts from CDN and not from `/wp-includes/` -------------------------------------------------- ``` add_action( 'wp_enqueue_scripts', 'wpse_76593_scripts_custom' ); function wpse_76593_scripts_custom() { wp_deregister_script('jquery'); wp_register_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js', false, '1.7.1', true); wp_enqueue_script( 'jquery' ); } ``` Search the theme for all style and script registers and enqueues. style.css --------- 1. create a new file inside the folder "/css" named "style.css" 2. open the theme's `style.css` 3. select all declarations bellow the [theme file header](http://codex.wordpress.org/File_Header#Theme_File_Header_Example) 4. cut and paste in the file `/css/style.css` 5. save both in short: `/your-theme/styles.css` will contain only the header information, and `/your-theme/css/styles.css` will contain all the styles * change all occurrences of `url('fonts/` with `url('../fonts/` * change all occurrences of `images/` with `../images/` header.php ---------- Change the stylesheet link from ``` <link rel="stylesheet" type="text/css" media="all" href="<?php bloginfo( 'stylesheet_url' ); ?>" /> ``` to ``` <link rel="stylesheet" type="text/css" media="all" href="<?php echo get_template_directory_uri(); ?>/css/style.css" /> ``` All theme files --------------- Search for: * `get_bloginfo('template_url')` * `get_bloginfo('template_directory')` and replace with: * `get_template_directory_uri()` Testing ------- Not sure about other browsers, but [Safari Activity Window](https://www.google.com/search?q=safari%20activity%20window&hl=es&safe=off&tbo=d&source=lnms&tbm=isch) is perfect to check all loaded files and its URLs. Depending on the theme complexity, extra steps have to be taken.
This can be easily achieved by using '[hide my wp](http://bit.ly/1cyQW91)' plugin. Please change it's permalinks and url settings as shown below: ![Change theme path under Permalinks & urls to /incs](https://i.stack.imgur.com/tHGVs.jpg) Change theme path under Permalinks & urls to `/incs`. Once you have changed these settings, you will notice, `bloginfo('template_url')` will render `http://website.com/incs/` and hence ``` http://website.com/incs/js/script.js ``` Reference: <http://howtomakewebsite.ws/wordpress-plugins/how-to-hide-wordpress/731/>
76,593
in my header and other sections I would like to use ``` <script src="/incs/js/script.js"></script> ``` While maintaining the default theme folder structure in server as below ``` /wp-content/themes/theme-name/incs/js/script.js ``` file need to be accessed via browser/html source if need be so that it hides **/wp-content/themes/theme-name** ``` http://website.com/incs/js/script.js ``` This is also applicable to images I may have under /incs/images/imagname.jpg I've seen solutions where defining the directory located outside of theme folder... but need a solution that does this within. Is this possible? Thanks
2012/12/19
['https://wordpress.stackexchange.com/questions/76593', 'https://wordpress.stackexchange.com', 'https://wordpress.stackexchange.com/users/16419/']
I created the [Roots Plug](http://wordpress.org/extend/plugins/roots-plug/) which has the same `.htaccess` rewrites as the Roots Theme. But completely agree with what @brasofolio [said](https://wordpress.stackexchange.com/a/76605/9605)
This can be easily achieved by using '[hide my wp](http://bit.ly/1cyQW91)' plugin. Please change it's permalinks and url settings as shown below: ![Change theme path under Permalinks & urls to /incs](https://i.stack.imgur.com/tHGVs.jpg) Change theme path under Permalinks & urls to `/incs`. Once you have changed these settings, you will notice, `bloginfo('template_url')` will render `http://website.com/incs/` and hence ``` http://website.com/incs/js/script.js ``` Reference: <http://howtomakewebsite.ws/wordpress-plugins/how-to-hide-wordpress/731/>
36,248,147
I have a regexp: ``` import re regexp = re.compile(r'^(?P<parts>(?:[\w-]+/?)+)/$') ``` It matches a string like `foo/bar/baz/` and put the `foo/bar/baz` in a group named `parts` (the `/?` combined with the `/$` support this). This works perfectly fine, **until you match a string that doesn't end in a slash**. Then, it gets slower at a seemingly-exponential rate with each new char you add to the string you're matching. ### Example ``` # This is instant (trailing slash) regexp.match('this-will-take-no-time-at-all/') # This is slow regexp.match('this-takes-about-5-seconds') # This will not finish regexp.match('this-probably-will-not-finish-until-the-day-star-turns-black') ``` I'm trying to understand why this specific recursion issue only happens when the `/$` (trailing slash) isn't in the string (i.e., a non-match). Could you help me understand the control flow of the underlying algorithm in both the trailing slash and the non trailing slash cases? ### Note I'm not looking for a solution for my desired pattern. I'm trying to understand the specific regexp.
2016/03/27
['https://Stackoverflow.com/questions/36248147', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/128463/']
It is getting slow due to [catastrophic backtracking](http://www.regular-expressions.info/catastrophic.html) in your regex: You can fix catastrophic backtracking by using this regex: ``` ^(?P<parts>(?:[\w-]+/)*[\w-]+)/$ ``` As per the link above: > > The **solution to avoid *catastrophic backtracking*** is simple. When nesting repetition operators, make absolutely sure that there is only one way to match the same match. > > >
Wiktor Stribizew is correct. The issue is the question mark after the slash inside the repeating pattern. So, the pattern you gave: ``` '^(?P<parts>(?:[\w-]+/?)+)/$' ``` Says, look for one or more groups of one or more word characters or dashes possibly followed by a slash, then there should be a slash at the very end. So, for a string like `arm/`, the inner grouping could be any of: ``` (arm)/ (ar)(m)/ (a)(rm)/ (a)(r)(m)/ ``` As the string gets longer, if the regex fails to match on its first try, it will check more and more combinations to try to match. To avoid this the same match could be achieved with: ``` '^(?P<parts>(?:[\w-]+/)*[\w-]+)/$' ``` because this version can only match your target strings one way.
25,530,172
1) Here's my schema: ``` { "_id" : ObjectId("53f4db1d968166157c2d57ce"), "init" : "SJ", "name" : "Steve Jobs", "companies" : [ { "_id" : ObjectId("53f4db1d968166157c2d57cf"), "ticker" : "AAPL", "compname" : "Apple" }, { "_id" : ObjectId("53f4db1d968166157c2d57d0"), "ticker" : "MSFT", "compname" : "Microsoft" }, { "_id" : ObjectId("53f4db1d968166157c2d57d1"), "ticker" : "ABC", "compname" : "iTunes" }, { "_id" : ObjectId("53f4db1d968166157c2d57d2"), "ticker" : "DEF", "compname" : "iPad Mini" } ] } ``` I'm trying to get a list of compnames, using Powershell & MongoDB. Here's what I have so far: ``` $databaseName = "CompanyInfo" $collectionName = "comps" $client = New-Object -TypeName MongoDB.Driver.MongoClient -ArgumentList "mongodb://localhost:27017" $server = $client.GetServer() $database = $server.GetDatabase($databaseName) $collection = $database.GetCollection($collectionName) $query['init'] = "SJ" $results = $collection.FindOne($query) foreach ($result in $results) { write-host $result["companies.ticker"] /// Doesn't show me any records } ``` This doesn't show me any records. How can I display companies.ticker info where init = "SJ"? 2) Btw, I get the following error after ``` $query['init'] = "SJ" ``` error ``` Cannot index into a null array. At line:9 char:1 + $query['init'] = "SJ" + ~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : NullArray ``` Any ideas as to why? I only have the MongoDB's standard index, which is on "\_id", nothing else. My powershell script still works but I'm curious as to why I get that error. **[UPDATE Part 2]** Thanks to @arco444, I no longer get error in part 2. Here's my revised code: ``` $query = @{'init' = "SJ"} $collection.FindOne([MongoDB.Driver.QueryDocument]$query) ``` But I actually need help with part 1 - which is to display only the company tickers for a particular init. Any ideas on that one? **[ANSWER Part 1]** Thanks again to @arco444 for directing me to the right path. After some tinkering around, I figured out what I missed. Here's my updated code: ``` $databaseName = "CompanyInfo" $collectionName = "comps" $client = New-Object -TypeName MongoDB.Driver.MongoClient -ArgumentList "mongodb://localhost:27017" $server = $client.GetServer() $database = $server.GetDatabase($databaseName) $collection = $database.GetCollection($collectionName) $query = new-object MongoDB.Driver.QueryDocument("init","SJ") /// Updated $results = $collection.FindOne($query) foreach ($result in $results["companies"]) { /// Updated write-host $result["ticker"] /// Updated } ```
2014/08/27
['https://Stackoverflow.com/questions/25530172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/979127/']
From reading the MongoDB [documentation](http://docs.mongodb.org/ecosystem/tutorial/use-csharp-driver/#findone-and-findoneas-methods), it looks like you need to initialise the query object properly first. Try this: ``` $query = new-object MongoDB.Driver.QueryDocument("init","SJ") $results = $collection.FindOne($query) ```
So when I use your query procedure with ``` $mongoDbDriverPath = 'D:\mongo\driver\' $mongoServer = 'myserver:27000' Add-Type -Path "$($mongoDbDriverPath)MongoDB.Bson.dll" Add-Type -Path "$($mongoDbDriverPath)MongoDB.Driver.dll" $databaseName = 'Tickets' $collectionName = 'MongoUserTicket' $client = New-Object -TypeName MongoDB.Driver.MongoClient -ArgumentList "mongodb://$mongoServer" $server = $client.GetServer() $database = $server.GetDatabase($databaseName) $collection = $database.GetCollection($collectionName) $query = new-object Mongodb.driver.querydocument('Id','5') $query2 = New-object Mongodb.driver.querydocument('Type','User') $results = @() foreach($item in $collection.Find($query)) { $results += $item } ``` I get unexpected results for the query: When piping to Get member for results I get this: ``` TypeName: MongoDB.Bson.BsonElement Name MemberType Definition ---- ---------- ---------- Clone Method MongoDB.Bson.BsonElement Clone() CompareTo Method int CompareTo(MongoDB.Bson.BsonElement other), int IComparable[BsonElement].CompareTo(MongoDB.Bson.BsonElement other) DeepClone Method MongoDB.Bson.BsonElement DeepClone() Equals Method bool Equals(MongoDB.Bson.BsonElement rhs), bool Equals(System.Object obj), bool IEquatable[BsonElement].Equals(MongoDB.Bson.BsonElement other) GetHashCode Method int GetHashCode() GetType Method type GetType() ToString Method string ToString() Name Property string Name {get;} Value Property MongoDB.Bson.BsonValue Value {get;set;} ``` When entering $results on the shell prompt I get the data I expect: ``` $results Name Value ---- ----- Id 5 AccessToken CreatedOn 2013-09-27T22:05:52.246Z TokenExpiration 2013-09-27T22:20:52.246Z RefreshTokenExpiration 2013-09-28T22:05:52.246Z ProfileToken BsonNull Type User Id 5 AccessToken CreatedOn 2013-09-27T23:42:28.492Z TokenExpiration 2013-09-27T23:57:28.492Z RefreshTokenExpiration 2013-09-28T22:06:04.071Z ProfileToken BsonNull Type User ```
25,530,172
1) Here's my schema: ``` { "_id" : ObjectId("53f4db1d968166157c2d57ce"), "init" : "SJ", "name" : "Steve Jobs", "companies" : [ { "_id" : ObjectId("53f4db1d968166157c2d57cf"), "ticker" : "AAPL", "compname" : "Apple" }, { "_id" : ObjectId("53f4db1d968166157c2d57d0"), "ticker" : "MSFT", "compname" : "Microsoft" }, { "_id" : ObjectId("53f4db1d968166157c2d57d1"), "ticker" : "ABC", "compname" : "iTunes" }, { "_id" : ObjectId("53f4db1d968166157c2d57d2"), "ticker" : "DEF", "compname" : "iPad Mini" } ] } ``` I'm trying to get a list of compnames, using Powershell & MongoDB. Here's what I have so far: ``` $databaseName = "CompanyInfo" $collectionName = "comps" $client = New-Object -TypeName MongoDB.Driver.MongoClient -ArgumentList "mongodb://localhost:27017" $server = $client.GetServer() $database = $server.GetDatabase($databaseName) $collection = $database.GetCollection($collectionName) $query['init'] = "SJ" $results = $collection.FindOne($query) foreach ($result in $results) { write-host $result["companies.ticker"] /// Doesn't show me any records } ``` This doesn't show me any records. How can I display companies.ticker info where init = "SJ"? 2) Btw, I get the following error after ``` $query['init'] = "SJ" ``` error ``` Cannot index into a null array. At line:9 char:1 + $query['init'] = "SJ" + ~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : NullArray ``` Any ideas as to why? I only have the MongoDB's standard index, which is on "\_id", nothing else. My powershell script still works but I'm curious as to why I get that error. **[UPDATE Part 2]** Thanks to @arco444, I no longer get error in part 2. Here's my revised code: ``` $query = @{'init' = "SJ"} $collection.FindOne([MongoDB.Driver.QueryDocument]$query) ``` But I actually need help with part 1 - which is to display only the company tickers for a particular init. Any ideas on that one? **[ANSWER Part 1]** Thanks again to @arco444 for directing me to the right path. After some tinkering around, I figured out what I missed. Here's my updated code: ``` $databaseName = "CompanyInfo" $collectionName = "comps" $client = New-Object -TypeName MongoDB.Driver.MongoClient -ArgumentList "mongodb://localhost:27017" $server = $client.GetServer() $database = $server.GetDatabase($databaseName) $collection = $database.GetCollection($collectionName) $query = new-object MongoDB.Driver.QueryDocument("init","SJ") /// Updated $results = $collection.FindOne($query) foreach ($result in $results["companies"]) { /// Updated write-host $result["ticker"] /// Updated } ```
2014/08/27
['https://Stackoverflow.com/questions/25530172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/979127/']
From reading the MongoDB [documentation](http://docs.mongodb.org/ecosystem/tutorial/use-csharp-driver/#findone-and-findoneas-methods), it looks like you need to initialise the query object properly first. Try this: ``` $query = new-object MongoDB.Driver.QueryDocument("init","SJ") $results = $collection.FindOne($query) ```
here is what allowed me to get an object that i could operate on: ``` $results = @() foreach($item in $collection.Find($query)) { $props = @{} $item | foreach { $props[ $_.name ] = $_.value } $pso = [pscustomobject]$props $results += $pso } ``` full code: ``` $mongoDbDriverPath = 'D:\mongo\driver\' $mongoServer = 'myserver:27000' Add-Type -Path "$($mongoDbDriverPath)MongoDB.Bson.dll" Add-Type -Path "$($mongoDbDriverPath)MongoDB.Driver.dll" $databaseName = 'Tickets' $collectionName = 'MongoUserTicket' $client = New-Object -TypeName MongoDB.Driver.MongoClient -ArgumentList "mongodb://$mongoServer" $server = $client.GetServer() $database = $server.GetDatabase($databaseName) $collection = $database.GetCollection($collectionName) $query = new-object Mongodb.driver.querydocument('Id','5') $query2 = New-object Mongodb.driver.querydocument('Type','User') $results = @() foreach($item in $collection.Find($query)) { $props = @{} $item | foreach { $props[ $_.name ] = $_.value } $pso = [pscustomobject]$props $results += $pso } $results ```
25,530,172
1) Here's my schema: ``` { "_id" : ObjectId("53f4db1d968166157c2d57ce"), "init" : "SJ", "name" : "Steve Jobs", "companies" : [ { "_id" : ObjectId("53f4db1d968166157c2d57cf"), "ticker" : "AAPL", "compname" : "Apple" }, { "_id" : ObjectId("53f4db1d968166157c2d57d0"), "ticker" : "MSFT", "compname" : "Microsoft" }, { "_id" : ObjectId("53f4db1d968166157c2d57d1"), "ticker" : "ABC", "compname" : "iTunes" }, { "_id" : ObjectId("53f4db1d968166157c2d57d2"), "ticker" : "DEF", "compname" : "iPad Mini" } ] } ``` I'm trying to get a list of compnames, using Powershell & MongoDB. Here's what I have so far: ``` $databaseName = "CompanyInfo" $collectionName = "comps" $client = New-Object -TypeName MongoDB.Driver.MongoClient -ArgumentList "mongodb://localhost:27017" $server = $client.GetServer() $database = $server.GetDatabase($databaseName) $collection = $database.GetCollection($collectionName) $query['init'] = "SJ" $results = $collection.FindOne($query) foreach ($result in $results) { write-host $result["companies.ticker"] /// Doesn't show me any records } ``` This doesn't show me any records. How can I display companies.ticker info where init = "SJ"? 2) Btw, I get the following error after ``` $query['init'] = "SJ" ``` error ``` Cannot index into a null array. At line:9 char:1 + $query['init'] = "SJ" + ~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : NullArray ``` Any ideas as to why? I only have the MongoDB's standard index, which is on "\_id", nothing else. My powershell script still works but I'm curious as to why I get that error. **[UPDATE Part 2]** Thanks to @arco444, I no longer get error in part 2. Here's my revised code: ``` $query = @{'init' = "SJ"} $collection.FindOne([MongoDB.Driver.QueryDocument]$query) ``` But I actually need help with part 1 - which is to display only the company tickers for a particular init. Any ideas on that one? **[ANSWER Part 1]** Thanks again to @arco444 for directing me to the right path. After some tinkering around, I figured out what I missed. Here's my updated code: ``` $databaseName = "CompanyInfo" $collectionName = "comps" $client = New-Object -TypeName MongoDB.Driver.MongoClient -ArgumentList "mongodb://localhost:27017" $server = $client.GetServer() $database = $server.GetDatabase($databaseName) $collection = $database.GetCollection($collectionName) $query = new-object MongoDB.Driver.QueryDocument("init","SJ") /// Updated $results = $collection.FindOne($query) foreach ($result in $results["companies"]) { /// Updated write-host $result["ticker"] /// Updated } ```
2014/08/27
['https://Stackoverflow.com/questions/25530172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/979127/']
Here's my updated code: ``` $databaseName = "CompanyInfo" $collectionName = "comps" $client = New-Object -TypeName MongoDB.Driver.MongoClient -ArgumentList "mongodb://localhost:27017" $server = $client.GetServer() $database = $server.GetDatabase($databaseName) $collection = $database.GetCollection($collectionName) $query = new-object MongoDB.Driver.QueryDocument("init","SJ") /// Updated $results = $collection.FindOne($query) foreach ($result in $results["companies"]) { /// Updated write-host $result["ticker"] /// Updated } ```
So when I use your query procedure with ``` $mongoDbDriverPath = 'D:\mongo\driver\' $mongoServer = 'myserver:27000' Add-Type -Path "$($mongoDbDriverPath)MongoDB.Bson.dll" Add-Type -Path "$($mongoDbDriverPath)MongoDB.Driver.dll" $databaseName = 'Tickets' $collectionName = 'MongoUserTicket' $client = New-Object -TypeName MongoDB.Driver.MongoClient -ArgumentList "mongodb://$mongoServer" $server = $client.GetServer() $database = $server.GetDatabase($databaseName) $collection = $database.GetCollection($collectionName) $query = new-object Mongodb.driver.querydocument('Id','5') $query2 = New-object Mongodb.driver.querydocument('Type','User') $results = @() foreach($item in $collection.Find($query)) { $results += $item } ``` I get unexpected results for the query: When piping to Get member for results I get this: ``` TypeName: MongoDB.Bson.BsonElement Name MemberType Definition ---- ---------- ---------- Clone Method MongoDB.Bson.BsonElement Clone() CompareTo Method int CompareTo(MongoDB.Bson.BsonElement other), int IComparable[BsonElement].CompareTo(MongoDB.Bson.BsonElement other) DeepClone Method MongoDB.Bson.BsonElement DeepClone() Equals Method bool Equals(MongoDB.Bson.BsonElement rhs), bool Equals(System.Object obj), bool IEquatable[BsonElement].Equals(MongoDB.Bson.BsonElement other) GetHashCode Method int GetHashCode() GetType Method type GetType() ToString Method string ToString() Name Property string Name {get;} Value Property MongoDB.Bson.BsonValue Value {get;set;} ``` When entering $results on the shell prompt I get the data I expect: ``` $results Name Value ---- ----- Id 5 AccessToken CreatedOn 2013-09-27T22:05:52.246Z TokenExpiration 2013-09-27T22:20:52.246Z RefreshTokenExpiration 2013-09-28T22:05:52.246Z ProfileToken BsonNull Type User Id 5 AccessToken CreatedOn 2013-09-27T23:42:28.492Z TokenExpiration 2013-09-27T23:57:28.492Z RefreshTokenExpiration 2013-09-28T22:06:04.071Z ProfileToken BsonNull Type User ```
25,530,172
1) Here's my schema: ``` { "_id" : ObjectId("53f4db1d968166157c2d57ce"), "init" : "SJ", "name" : "Steve Jobs", "companies" : [ { "_id" : ObjectId("53f4db1d968166157c2d57cf"), "ticker" : "AAPL", "compname" : "Apple" }, { "_id" : ObjectId("53f4db1d968166157c2d57d0"), "ticker" : "MSFT", "compname" : "Microsoft" }, { "_id" : ObjectId("53f4db1d968166157c2d57d1"), "ticker" : "ABC", "compname" : "iTunes" }, { "_id" : ObjectId("53f4db1d968166157c2d57d2"), "ticker" : "DEF", "compname" : "iPad Mini" } ] } ``` I'm trying to get a list of compnames, using Powershell & MongoDB. Here's what I have so far: ``` $databaseName = "CompanyInfo" $collectionName = "comps" $client = New-Object -TypeName MongoDB.Driver.MongoClient -ArgumentList "mongodb://localhost:27017" $server = $client.GetServer() $database = $server.GetDatabase($databaseName) $collection = $database.GetCollection($collectionName) $query['init'] = "SJ" $results = $collection.FindOne($query) foreach ($result in $results) { write-host $result["companies.ticker"] /// Doesn't show me any records } ``` This doesn't show me any records. How can I display companies.ticker info where init = "SJ"? 2) Btw, I get the following error after ``` $query['init'] = "SJ" ``` error ``` Cannot index into a null array. At line:9 char:1 + $query['init'] = "SJ" + ~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : NullArray ``` Any ideas as to why? I only have the MongoDB's standard index, which is on "\_id", nothing else. My powershell script still works but I'm curious as to why I get that error. **[UPDATE Part 2]** Thanks to @arco444, I no longer get error in part 2. Here's my revised code: ``` $query = @{'init' = "SJ"} $collection.FindOne([MongoDB.Driver.QueryDocument]$query) ``` But I actually need help with part 1 - which is to display only the company tickers for a particular init. Any ideas on that one? **[ANSWER Part 1]** Thanks again to @arco444 for directing me to the right path. After some tinkering around, I figured out what I missed. Here's my updated code: ``` $databaseName = "CompanyInfo" $collectionName = "comps" $client = New-Object -TypeName MongoDB.Driver.MongoClient -ArgumentList "mongodb://localhost:27017" $server = $client.GetServer() $database = $server.GetDatabase($databaseName) $collection = $database.GetCollection($collectionName) $query = new-object MongoDB.Driver.QueryDocument("init","SJ") /// Updated $results = $collection.FindOne($query) foreach ($result in $results["companies"]) { /// Updated write-host $result["ticker"] /// Updated } ```
2014/08/27
['https://Stackoverflow.com/questions/25530172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/979127/']
Here's my updated code: ``` $databaseName = "CompanyInfo" $collectionName = "comps" $client = New-Object -TypeName MongoDB.Driver.MongoClient -ArgumentList "mongodb://localhost:27017" $server = $client.GetServer() $database = $server.GetDatabase($databaseName) $collection = $database.GetCollection($collectionName) $query = new-object MongoDB.Driver.QueryDocument("init","SJ") /// Updated $results = $collection.FindOne($query) foreach ($result in $results["companies"]) { /// Updated write-host $result["ticker"] /// Updated } ```
here is what allowed me to get an object that i could operate on: ``` $results = @() foreach($item in $collection.Find($query)) { $props = @{} $item | foreach { $props[ $_.name ] = $_.value } $pso = [pscustomobject]$props $results += $pso } ``` full code: ``` $mongoDbDriverPath = 'D:\mongo\driver\' $mongoServer = 'myserver:27000' Add-Type -Path "$($mongoDbDriverPath)MongoDB.Bson.dll" Add-Type -Path "$($mongoDbDriverPath)MongoDB.Driver.dll" $databaseName = 'Tickets' $collectionName = 'MongoUserTicket' $client = New-Object -TypeName MongoDB.Driver.MongoClient -ArgumentList "mongodb://$mongoServer" $server = $client.GetServer() $database = $server.GetDatabase($databaseName) $collection = $database.GetCollection($collectionName) $query = new-object Mongodb.driver.querydocument('Id','5') $query2 = New-object Mongodb.driver.querydocument('Type','User') $results = @() foreach($item in $collection.Find($query)) { $props = @{} $item | foreach { $props[ $_.name ] = $_.value } $pso = [pscustomobject]$props $results += $pso } $results ```
1,748,356
I have some application, which has ability to update itself. Its downloads the jar file from the net, and then tries to replace used jar to run this application by downloaded one. But I cannot to do that, because the file is locked by windows, because application is still running. Does anybody know some workaround of that?
2009/11/17
['https://Stackoverflow.com/questions/1748356', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/212822/']
One of the popular solutions for this is to run your updater as a separate program. Have you ever noticed that Firefox has to restart when it is updated? Well that is because a separate process (updater.exe) is updating the files, then starting Firefox again. You can try this approach. The only obstacle I see in the way is trying to automate the MAIN program to close itself. The only portable way to do this (in my head) is for the main application to wait for a kill signal via a local socket, and the updater can send the command through local networking. One more thing you have to consider is that the updater has to run in a separate java process. If your main program just creates a new Updater object, the Updater will co-exist with the main program's JVM, which brings you back to square one.
I think the correct thing to do here is to **restart** the application. Event if you could update the jar at *runtime*, all sort of errors might occur after because of class versions, different classes, different implementations, etc.
1,748,356
I have some application, which has ability to update itself. Its downloads the jar file from the net, and then tries to replace used jar to run this application by downloaded one. But I cannot to do that, because the file is locked by windows, because application is still running. Does anybody know some workaround of that?
2009/11/17
['https://Stackoverflow.com/questions/1748356', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/212822/']
I think the correct thing to do here is to **restart** the application. Event if you could update the jar at *runtime*, all sort of errors might occur after because of class versions, different classes, different implementations, etc.
Typical way to do this is to write a separate updater which will be invoked by your main program when it sees an update. At this time your main program can start the updater in a new process and exit. You updater can wait for main program to exit, download and copy the updated files and restart your main program
1,748,356
I have some application, which has ability to update itself. Its downloads the jar file from the net, and then tries to replace used jar to run this application by downloaded one. But I cannot to do that, because the file is locked by windows, because application is still running. Does anybody know some workaround of that?
2009/11/17
['https://Stackoverflow.com/questions/1748356', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/212822/']
One of the popular solutions for this is to run your updater as a separate program. Have you ever noticed that Firefox has to restart when it is updated? Well that is because a separate process (updater.exe) is updating the files, then starting Firefox again. You can try this approach. The only obstacle I see in the way is trying to automate the MAIN program to close itself. The only portable way to do this (in my head) is for the main application to wait for a kill signal via a local socket, and the updater can send the command through local networking. One more thing you have to consider is that the updater has to run in a separate java process. If your main program just creates a new Updater object, the Updater will co-exist with the main program's JVM, which brings you back to square one.
Typical way to do this is to write a separate updater which will be invoked by your main program when it sees an update. At this time your main program can start the updater in a new process and exit. You updater can wait for main program to exit, download and copy the updated files and restart your main program
1,748,356
I have some application, which has ability to update itself. Its downloads the jar file from the net, and then tries to replace used jar to run this application by downloaded one. But I cannot to do that, because the file is locked by windows, because application is still running. Does anybody know some workaround of that?
2009/11/17
['https://Stackoverflow.com/questions/1748356', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/212822/']
One of the popular solutions for this is to run your updater as a separate program. Have you ever noticed that Firefox has to restart when it is updated? Well that is because a separate process (updater.exe) is updating the files, then starting Firefox again. You can try this approach. The only obstacle I see in the way is trying to automate the MAIN program to close itself. The only portable way to do this (in my head) is for the main application to wait for a kill signal via a local socket, and the updater can send the command through local networking. One more thing you have to consider is that the updater has to run in a separate java process. If your main program just creates a new Updater object, the Updater will co-exist with the main program's JVM, which brings you back to square one.
That's a problem **already solved** by OSGi. The real problem is not to load a new jar version. This could be done with your own classloader that releases the file lock. The real problem is how to [handle instances of different versions of the same class](http://en.wikipedia.org/wiki/Classloader#JAR_hell). Restart does omit these problem. If you really need different jar versions in one application use OSGi.
1,748,356
I have some application, which has ability to update itself. Its downloads the jar file from the net, and then tries to replace used jar to run this application by downloaded one. But I cannot to do that, because the file is locked by windows, because application is still running. Does anybody know some workaround of that?
2009/11/17
['https://Stackoverflow.com/questions/1748356', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/212822/']
That's a problem **already solved** by OSGi. The real problem is not to load a new jar version. This could be done with your own classloader that releases the file lock. The real problem is how to [handle instances of different versions of the same class](http://en.wikipedia.org/wiki/Classloader#JAR_hell). Restart does omit these problem. If you really need different jar versions in one application use OSGi.
Typical way to do this is to write a separate updater which will be invoked by your main program when it sees an update. At this time your main program can start the updater in a new process and exit. You updater can wait for main program to exit, download and copy the updated files and restart your main program
12,302,290
I have a log file on server called `writelog` which is about `2GB`. I want to delete first `100,000` lines from the file. I could open the file and delete those lines but because of the file size it takes me forever to download it. So, is it possible to do this from Linux terminal? If yes how?
2012/09/06
['https://Stackoverflow.com/questions/12302290', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1143828/']
If you want to clear out the *whole file* a quick way is `cat /dev/null > writelog` See also [this thread on unix.com](http://www.unix.com/unix-dummies-questions-answers/150082-create-empty-file-overwrite-file-differences-between-cat-echo-etc.html).
If you are running a Linux server, you can use `ssh`: ``` ssh [email protected] sed -i '1,100000d' /path/to/logfile ```
12,302,290
I have a log file on server called `writelog` which is about `2GB`. I want to delete first `100,000` lines from the file. I could open the file and delete those lines but because of the file size it takes me forever to download it. So, is it possible to do this from Linux terminal? If yes how?
2012/09/06
['https://Stackoverflow.com/questions/12302290', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1143828/']
If you want to clear out the *whole file* a quick way is `cat /dev/null > writelog` See also [this thread on unix.com](http://www.unix.com/unix-dummies-questions-answers/150082-create-empty-file-overwrite-file-differences-between-cat-echo-etc.html).
It might be better to keep the last 1000 lines: ``` mv writelog writelog.bak tail -1000 writelog.bak > writelog ``` And you should enable `logrotate` ([manual](http://linux.die.net/man/8/logrotate)) for the file. The system will then make sure the file doesn't grow out of proportions.
9,293,124
``` Qt :: WindowFlags flags = 0; // Makes the Pomodoro stay on the top of all windows. flags |= Qt :: WindowStaysOnTopHint; // Removes minimize, maximize, and close buttons. flags |= Qt :: WindowTitleHint | Qt :: CustomizeWindowHint; window->setWindowFlags (flags); window->setWindowTitle ("Failing to plan is planning to fail"); ``` This removes minimize, maximize, and close buttons. The default menu on the left is still there. How to get rid of that? I want the title bar to be there, but just want the menu to be removed. Default menu contains: Minimize, Maximize, Move etc options. EDIT 1: ------- timer.cpp ``` #include <QApplication> #include <QMainWindow> #include "timer.h" #include <QPushButton> #include <QListWidget> #include <QtGui> #include <QTreeWidget> int main(int argc, char *argv[]) { QApplication app (argc, argv); // The window on which we will place the timer. QMainWindow *window = new QMainWindow(); QWidget *centralWidget = new QWidget (window); /* Button widget */ // Displays a button on the main window. QPushButton *startButton = new QPushButton("Start", window); // Setting the size of the button widget. startButton->setFixedSize (245, 25); /* Text box */ // Displays a time interval list on the main window. QListWidget *timeIntervalList = new QListWidget (window); timeIntervalList->setFixedSize (30, 145); QStringList timeIntervals; timeIntervals << "1" << "20" << "30" << "40"; timeIntervalList->addItems (timeIntervals); /* LCD widget */ // Start Counting down from 25 minutes lcdDisplay *objLcdDisplay = new lcdDisplay (centralWidget); // Setting the size of the LCD widget. objLcdDisplay->setFixedSize (245, 140); // The clicked time interval should be returned from the list to the timer. QObject :: connect (timeIntervalList, SIGNAL (itemClicked (QListWidgetItem *)), objLcdDisplay, SLOT (receiveTimeInterval (QListWidgetItem *))); // The timer should start and emit signals when the start button is clicked. QObject :: connect (startButton, SIGNAL (clicked ()), objLcdDisplay, SLOT (setTimerConnect ())); ************************************************************************* Qt :: WindowFlags flags = 0; // Makes the Pomodoro stay on the top of all windows. flags |= Qt :: Window | Qt :: WindowStaysOnTopHint; // Removes minimize, maximize, and close buttons. flags |= Qt :: WindowTitleHint | Qt :: CustomizeWindowHint; window->setWindowFlags (flags); ************************************************************************* window->setWindowTitle ("Failing to plan is planning to fail"); QGridLayout *layout = new QGridLayout(); centralWidget->setLayout(layout); //Add Items to QGridLayout Here //Row and Column counts are set Automatically layout->addWidget (objLcdDisplay, 0, 1); layout->addWidget (startButton, 1, 1); layout->addWidget (timeIntervalList, 0, 0); window->setCentralWidget (centralWidget); window->show(); return app.exec(); } ``` Timer.h ``` #ifndef LCDNUMBER_H #define LCDNUMBER_H #include <QLCDNumber> #include <QTimer> #include <QTime> #include <QListWidget> #include <QMessageBox> #include <iostream> class lcdDisplay : public QLCDNumber { Q_OBJECT public: // The QTimer class provides repetitive and single-shot timers. QTimer* objTimer; // The QTime class provides clock time functions. QTime* objTime; public: lcdDisplay (QWidget *parentWidget) { objTimer = new QTimer (); // Setting our own time with the specified hours, minutes, and seconds. objTime = new QTime (0, 0, 0); setParent (parentWidget); }; ~ lcdDisplay () {}; public slots: // This slot is called after the timer timeouts (1 second). void setDisplay () { // TODO objTime->setHMS (0, objTime->addSecs (-1).minute (), objTime->addSecs (-1).second ()); display (objTime->toString ()); if ((objTime->minute () == 0) && (objTime->second () == 0)) { objTimer->stop (); QMessageBox msgBox; msgBox.setWindowTitle ("Pomodoro"); msgBox.setText ("Time's up."); msgBox.setWindowModality(Qt::ApplicationModal); msgBox.exec(); } }; void receiveTimeInterval (QListWidgetItem *item) { QString h = item->text(); objTime->setHMS (0, h.toUInt(), 0); } void setTimerConnect () { // connect (objectA, signalAFromObjectA, objectB, slotAFromObjectB) // timeout (): This signal is emitted when the timer times out. The time out period can be specified with `start (int milliseconds)` function. QObject :: connect (objTimer, SIGNAL (timeout ()), this, SLOT (setDisplay ())); // 1 second has 1000 milliseconds. // start (int milliseconds): Starts the timer with a timeout interval of specified milliseconds. this means that after 1 second the timer will emit a signal. TODO placement objTimer->start (1000); } }; #endif ```
2012/02/15
['https://Stackoverflow.com/questions/9293124', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/462608/']
This is working for me: ``` Qt::Window | Qt::WindowTitleHint | Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint ``` ![Screen shot](https://i.stack.imgur.com/zCRxF.png) Sometimes you have to specify these in the constructor of the window for them to take effect. If you assign them later (`setWindowFlags`), some of the settings may not apply.
I'm currently at work without an Qt environment, so I could not test it. Would you please try this? ``` Qt::WindowFlags flags = 0; // Makes the Pomodoro stay on the top of all windows. flags |= Qt :: WindowStaysOnTopHint; // Removes minimize, maximize, and close buttons. flags |= Qt :: WindowTitleHint | Qt :: CustomizeWindowHint; window->setWindowFlags (flags & ~Qt::WindowSystemMenuHint); window->setWindowTitle ("Failing to plan is planning to fail"); ```
9,293,124
``` Qt :: WindowFlags flags = 0; // Makes the Pomodoro stay on the top of all windows. flags |= Qt :: WindowStaysOnTopHint; // Removes minimize, maximize, and close buttons. flags |= Qt :: WindowTitleHint | Qt :: CustomizeWindowHint; window->setWindowFlags (flags); window->setWindowTitle ("Failing to plan is planning to fail"); ``` This removes minimize, maximize, and close buttons. The default menu on the left is still there. How to get rid of that? I want the title bar to be there, but just want the menu to be removed. Default menu contains: Minimize, Maximize, Move etc options. EDIT 1: ------- timer.cpp ``` #include <QApplication> #include <QMainWindow> #include "timer.h" #include <QPushButton> #include <QListWidget> #include <QtGui> #include <QTreeWidget> int main(int argc, char *argv[]) { QApplication app (argc, argv); // The window on which we will place the timer. QMainWindow *window = new QMainWindow(); QWidget *centralWidget = new QWidget (window); /* Button widget */ // Displays a button on the main window. QPushButton *startButton = new QPushButton("Start", window); // Setting the size of the button widget. startButton->setFixedSize (245, 25); /* Text box */ // Displays a time interval list on the main window. QListWidget *timeIntervalList = new QListWidget (window); timeIntervalList->setFixedSize (30, 145); QStringList timeIntervals; timeIntervals << "1" << "20" << "30" << "40"; timeIntervalList->addItems (timeIntervals); /* LCD widget */ // Start Counting down from 25 minutes lcdDisplay *objLcdDisplay = new lcdDisplay (centralWidget); // Setting the size of the LCD widget. objLcdDisplay->setFixedSize (245, 140); // The clicked time interval should be returned from the list to the timer. QObject :: connect (timeIntervalList, SIGNAL (itemClicked (QListWidgetItem *)), objLcdDisplay, SLOT (receiveTimeInterval (QListWidgetItem *))); // The timer should start and emit signals when the start button is clicked. QObject :: connect (startButton, SIGNAL (clicked ()), objLcdDisplay, SLOT (setTimerConnect ())); ************************************************************************* Qt :: WindowFlags flags = 0; // Makes the Pomodoro stay on the top of all windows. flags |= Qt :: Window | Qt :: WindowStaysOnTopHint; // Removes minimize, maximize, and close buttons. flags |= Qt :: WindowTitleHint | Qt :: CustomizeWindowHint; window->setWindowFlags (flags); ************************************************************************* window->setWindowTitle ("Failing to plan is planning to fail"); QGridLayout *layout = new QGridLayout(); centralWidget->setLayout(layout); //Add Items to QGridLayout Here //Row and Column counts are set Automatically layout->addWidget (objLcdDisplay, 0, 1); layout->addWidget (startButton, 1, 1); layout->addWidget (timeIntervalList, 0, 0); window->setCentralWidget (centralWidget); window->show(); return app.exec(); } ``` Timer.h ``` #ifndef LCDNUMBER_H #define LCDNUMBER_H #include <QLCDNumber> #include <QTimer> #include <QTime> #include <QListWidget> #include <QMessageBox> #include <iostream> class lcdDisplay : public QLCDNumber { Q_OBJECT public: // The QTimer class provides repetitive and single-shot timers. QTimer* objTimer; // The QTime class provides clock time functions. QTime* objTime; public: lcdDisplay (QWidget *parentWidget) { objTimer = new QTimer (); // Setting our own time with the specified hours, minutes, and seconds. objTime = new QTime (0, 0, 0); setParent (parentWidget); }; ~ lcdDisplay () {}; public slots: // This slot is called after the timer timeouts (1 second). void setDisplay () { // TODO objTime->setHMS (0, objTime->addSecs (-1).minute (), objTime->addSecs (-1).second ()); display (objTime->toString ()); if ((objTime->minute () == 0) && (objTime->second () == 0)) { objTimer->stop (); QMessageBox msgBox; msgBox.setWindowTitle ("Pomodoro"); msgBox.setText ("Time's up."); msgBox.setWindowModality(Qt::ApplicationModal); msgBox.exec(); } }; void receiveTimeInterval (QListWidgetItem *item) { QString h = item->text(); objTime->setHMS (0, h.toUInt(), 0); } void setTimerConnect () { // connect (objectA, signalAFromObjectA, objectB, slotAFromObjectB) // timeout (): This signal is emitted when the timer times out. The time out period can be specified with `start (int milliseconds)` function. QObject :: connect (objTimer, SIGNAL (timeout ()), this, SLOT (setDisplay ())); // 1 second has 1000 milliseconds. // start (int milliseconds): Starts the timer with a timeout interval of specified milliseconds. this means that after 1 second the timer will emit a signal. TODO placement objTimer->start (1000); } }; #endif ```
2012/02/15
['https://Stackoverflow.com/questions/9293124', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/462608/']
This is working for me: ``` Qt::Window | Qt::WindowTitleHint | Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint ``` ![Screen shot](https://i.stack.imgur.com/zCRxF.png) Sometimes you have to specify these in the constructor of the window for them to take effect. If you assign them later (`setWindowFlags`), some of the settings may not apply.
Try to start by setting Qt::Dialog ``` setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::WindowStaysOnTopHint); ```
10,581,112
What would be the best way to create a C# Web Application that allows the user to browse for an image and then display it? An equivalent of Picturebox in windows applications, sort of Ideally the user should be able to click on Browse, choose the picture and see it in the browser itself Thanks
2012/05/14
['https://Stackoverflow.com/questions/10581112', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1211929/']
There are all ready some image-browser for asp.net including source code. Some of them <http://www.codeproject.com/Articles/17605/Thumbnail-Image-Viewer-Control-for-ASP-NET-2-0> <http://www.codeproject.com/Articles/29846/A-simple-ASP-NET-AJAX-image-browser>
For this, the user needs to choose an image which will be uploaded to the server, and then rendered in the HTML or recovered using AJAX. The problem is that you can't get rid of the send/receive, and it can get slow. You can use a `FileUpload` or any other component that allows to upload files directly or via AJAX (look at [AjaxFileUpload](http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/AjaxFileUpload/AjaxFileUpload.aspx) AjaxControlToolkit for this). Then you need to add an `<img>` to your page, through a full postback or using any other means (like jQuery.Ajax).
30,796,314
Am new to Angularjs, any one can help me about this infact my array is like this ``` array = [{"loc_name":"pronto network office","address":"3rd floor, kalyani motors","ap":[]}], ``` but when i use at dynamically its converted like this ``` [" {\"loc_name\":\"pronto="" network="" office\",\"address\":\"3rd="" floor,="" kalyani="" motors\",\"ap\":[]}"] ``` finally i want like this ``` <ul ng-repeat="loc in [" {\"loc_name\":\"pronto=" " network=" " office\",\"address\":\"3rd=" " floor,=" " kalyani=" " motors\",\"ap\":[]} "]"=""> <li class="clearfix"> <div class="list-icon"> <i class="fa fa-user"></i> </div> <div class="location-info"> <h4 class="location-name">{{ loc.loc_name }}</h4> <p class="location-address">{{ loc.address }}</p> </div> </li> <li ng-if="loc.aps != '' "> <ul ng-repeat="ap in loc.aps"> <li class="clearfix"> <div class="list-icon"> <i class="fa fa-user"></i> </div> <div class="location-info"> <h4 class="location-name">{{ ap.mac_id }}</h4> <p class="location-address"></p> </div> </li> </ul> </li> </ul> ```
2015/06/12
['https://Stackoverflow.com/questions/30796314', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/748447/']
Your response should not contain `"` at starting of object inside array right after `[` and just before `]` need to remove `"` like it should be like `[{\"loc_name\":\"pronto="" network="" office\",\"address\":\"3rd="" floor,="" kalyani="" motors\",\"ap\":[]}]` Then place it in your scope variable `$scope.locations = [{\"loc_name\":\"pronto="" network="" office\",\"address\":\"3rd="" floor,="" kalyani="" motors\",\"ap\":[]}]` & refer that scope variable on html then you need to worry about to convert it to double quote`"` to '`' single quote. ``` <ul ng-repeat="loc in locations"> ... <ul> ```
You can just use single quotes instead of `"`: ``` <ul ng-repeat="loc in [{loc_name: 'pronto network office', address: '3rd floor, kalyani motors', ap: []}]"> <!-- ... --> </ul> ``` You can also omit quotes around keys: string inside `ngRepeat` doesn't have to comply string JSON notation with quoted keys. Of course you can still use `'` for keys as well.
30,796,314
Am new to Angularjs, any one can help me about this infact my array is like this ``` array = [{"loc_name":"pronto network office","address":"3rd floor, kalyani motors","ap":[]}], ``` but when i use at dynamically its converted like this ``` [" {\"loc_name\":\"pronto="" network="" office\",\"address\":\"3rd="" floor,="" kalyani="" motors\",\"ap\":[]}"] ``` finally i want like this ``` <ul ng-repeat="loc in [" {\"loc_name\":\"pronto=" " network=" " office\",\"address\":\"3rd=" " floor,=" " kalyani=" " motors\",\"ap\":[]} "]"=""> <li class="clearfix"> <div class="list-icon"> <i class="fa fa-user"></i> </div> <div class="location-info"> <h4 class="location-name">{{ loc.loc_name }}</h4> <p class="location-address">{{ loc.address }}</p> </div> </li> <li ng-if="loc.aps != '' "> <ul ng-repeat="ap in loc.aps"> <li class="clearfix"> <div class="list-icon"> <i class="fa fa-user"></i> </div> <div class="location-info"> <h4 class="location-name">{{ ap.mac_id }}</h4> <p class="location-address"></p> </div> </li> </ul> </li> </ul> ```
2015/06/12
['https://Stackoverflow.com/questions/30796314', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/748447/']
Your response should not contain `"` at starting of object inside array right after `[` and just before `]` need to remove `"` like it should be like `[{\"loc_name\":\"pronto="" network="" office\",\"address\":\"3rd="" floor,="" kalyani="" motors\",\"ap\":[]}]` Then place it in your scope variable `$scope.locations = [{\"loc_name\":\"pronto="" network="" office\",\"address\":\"3rd="" floor,="" kalyani="" motors\",\"ap\":[]}]` & refer that scope variable on html then you need to worry about to convert it to double quote`"` to '`' single quote. ``` <ul ng-repeat="loc in locations"> ... <ul> ```
Do you really want your array inside your html? Otherwise to make it simple and recommended way of doing is to move it to your controller in the JS. I have created a sample in <http://jsbin.com/tayege/2/edit?html,js,output> for you
55,740,242
Are there any compiler independent flags that can be set? I'd like to be able to set single variable to e.g. `OPTIMIZE_MOST` and get `-O3` on gcc and `/O2` in MS C++ compiler. Is there something I can use or should flags be set for each compiler separately?
2019/04/18
['https://Stackoverflow.com/questions/55740242', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3826362/']
Simply spoken: No, there is no flag to directly set the optimization level independently for every compiler. However, CMake provides so called [build types](https://cmake.org/cmake/help/latest/variable/CMAKE_BUILD_TYPE.html). Those are independent of the compiler in use and each comes with a predefined selection of flags, one of which is the optimization flag. Available build types are * `Debug` * `Release` * `RelWithDebInfo` * `MinSizeRel` For a comprehensive explanation, I refer to [this answer](https://stackoverflow.com/a/24767451/579698). It also provides some code that helps to identify the flags in question when included into the `CMakeLists.txt` file: ``` message("CMAKE_C_FLAGS_DEBUG is ${CMAKE_C_FLAGS_DEBUG}") message("CMAKE_C_FLAGS_RELEASE is ${CMAKE_C_FLAGS_RELEASE}") message("CMAKE_C_FLAGS_RELWITHDEBINFO is ${CMAKE_C_FLAGS_RELWITHDEBINFO}") message("CMAKE_C_FLAGS_MINSIZEREL is ${CMAKE_C_FLAGS_MINSIZEREL}") message("CMAKE_CXX_FLAGS_DEBUG is ${CMAKE_CXX_FLAGS_DEBUG}") message("CMAKE_CXX_FLAGS_RELEASE is ${CMAKE_CXX_FLAGS_RELEASE}") message("CMAKE_CXX_FLAGS_RELWITHDEBINFO is ${CMAKE_CXX_FLAGS_RELWITHDEBINFO}") message("CMAKE_CXX_FLAGS_MINSIZEREL is ${CMAKE_CXX_FLAGS_MINSIZEREL}") ```
To a degree. For some concepts, CMake has support for specifying them in a compiler-agnostic manner, usually by setting properties on the target in question. Unfortunately, there is no one location where all such possibilities would be listed. I went through the current [list of target properties](https://cmake.org/cmake/help/latest/manual/cmake-properties.7.html#properties-on-targets) and identified the following properties as "absrtacting away build-tool option syntax": * `COMPILE_PDB_NAME` * `INCLUDE_DIRECTORIES` * `INSTALL_RPATH` * `INTERPROCEDURAL_OPTIMIZATION` * `LINK_DIRECTORIES` * `LINK_LIBRARIES` * `PDB_NAME` * `PDB_OUTPUT_DIRECTORY` * (plus the properties for setting output name, path, etc.) There is apparently nothing for handling optimisation flags other than IPO. To the best of my knowledge, there is also no generic process for adding these — they are added to CMake as someone finds the need for them (and the time to implement them).
20,693,377
I have a sortable list of items (each with a draggable handle) and I'm trying to align some elements within each item: a title, link, and some descriptive text. The items are adjacent to a left-floated div (the "handle" you see on the left). Unfortunately, there is a large gap between the title and the link: ![There's a gap between the title and the link](https://i.stack.imgur.com/IzgND.png) (<http://www.bootply.com/101604>) Here's a mock-up I made in an image editing program that illustrates what I'm trying to achieve (no large gap between the title and the link): ![Here's the ideal layout--without the gap](https://i.stack.imgur.com/gmmKJ.png) I know it has something to do with the `.handle` div which is floated left and has a specified width and height, but I can't quite figure it out. When I remove the `.handle`, everything lines up fine without the awkward gap. I'm sure it's a simple fix, but I'm struggling to find an answer. Any suggestions would be helpful. Thanks!
2013/12/19
['https://Stackoverflow.com/questions/20693377', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/557928/']
Try adding these properties to your existing classes: ``` .itemSubContainer { overflow:hidden; } .handle { margin-right:10px; } ``` To help clear your floated elemets, because your itemSubContainer class doesn't know about the containing elements because they are floated and taken out of the flow.
Try the [`Media Object`](http://getbootstrap.com/components/#media) implementation given in Bootstrap. It includes a left-floated element with multiple text elements on its right. ``` <div class="media"> <a class="pull-left" href="#"> <img class="media-object" src="..." alt="..."> </a> <div class="media-body"> <h4 class="media-heading">Media heading</h4> ... </div> </div> ```
20,693,377
I have a sortable list of items (each with a draggable handle) and I'm trying to align some elements within each item: a title, link, and some descriptive text. The items are adjacent to a left-floated div (the "handle" you see on the left). Unfortunately, there is a large gap between the title and the link: ![There's a gap between the title and the link](https://i.stack.imgur.com/IzgND.png) (<http://www.bootply.com/101604>) Here's a mock-up I made in an image editing program that illustrates what I'm trying to achieve (no large gap between the title and the link): ![Here's the ideal layout--without the gap](https://i.stack.imgur.com/gmmKJ.png) I know it has something to do with the `.handle` div which is floated left and has a specified width and height, but I can't quite figure it out. When I remove the `.handle`, everything lines up fine without the awkward gap. I'm sure it's a simple fix, but I'm struggling to find an answer. Any suggestions would be helpful. Thanks!
2013/12/19
['https://Stackoverflow.com/questions/20693377', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/557928/']
Try adding these properties to your existing classes: ``` .itemSubContainer { overflow:hidden; } .handle { margin-right:10px; } ``` To help clear your floated elemets, because your itemSubContainer class doesn't know about the containing elements because they are floated and taken out of the flow.
The problem is that `.row` itself is also floating left and each `.row` clears the float. Instead of floating `.handle`, use `position: absolute` so the handle doesn't interfere with the rest of the content. Note that there's also a 10px margin on `h4` that you may wish to adjust. ![enter image description here](https://i.stack.imgur.com/e3FKw.png)
60,996,959
I have this command : ``` $ anbox session-manager --single-window --window-size=400,650 ``` and i need to run it **frequently**, is there any way to avoid **rewriting** it every time I need it ?
2020/04/02
['https://Stackoverflow.com/questions/60996959', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10863605/']
You can set an alias like this, ``` alias sessmgr = "anbox session-manager --single-window --window-size=400,650" ``` Later, you can directly use `sessmgr`.
There are several ways you can do this, the most common is probably [using an alias](https://www.tecmint.com/create-alias-in-linux/) A common alias is using 'll' for 'ls -al', one way you could do that is with the following command: `alias ll='ls-al'`
60,996,959
I have this command : ``` $ anbox session-manager --single-window --window-size=400,650 ``` and i need to run it **frequently**, is there any way to avoid **rewriting** it every time I need it ?
2020/04/02
['https://Stackoverflow.com/questions/60996959', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10863605/']
For permanently use 1. run this ``` echo 'alias customcommand="anbox session-manager --single-window --window-size=400,650"' >> /home/$(USER)/.bashrc ``` 2. open new terminal 3. now you can run `customcommand` and get that response
There are several ways you can do this, the most common is probably [using an alias](https://www.tecmint.com/create-alias-in-linux/) A common alias is using 'll' for 'ls -al', one way you could do that is with the following command: `alias ll='ls-al'`
60,996,959
I have this command : ``` $ anbox session-manager --single-window --window-size=400,650 ``` and i need to run it **frequently**, is there any way to avoid **rewriting** it every time I need it ?
2020/04/02
['https://Stackoverflow.com/questions/60996959', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10863605/']
You can use the alias command, and if you want to make the change permanent you can append the alias command in your .bashrc file, so every time you launch a terminal you will have by default the defined alias that you set before in your .bashrc file. e.g. `alias <name_of_the_alias>="<command>".` You can find more info regarding alias [here](https://en.wikipedia.org/wiki/Alias_(command))
There are several ways you can do this, the most common is probably [using an alias](https://www.tecmint.com/create-alias-in-linux/) A common alias is using 'll' for 'ls -al', one way you could do that is with the following command: `alias ll='ls-al'`
60,996,959
I have this command : ``` $ anbox session-manager --single-window --window-size=400,650 ``` and i need to run it **frequently**, is there any way to avoid **rewriting** it every time I need it ?
2020/04/02
['https://Stackoverflow.com/questions/60996959', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10863605/']
For permanently use 1. run this ``` echo 'alias customcommand="anbox session-manager --single-window --window-size=400,650"' >> /home/$(USER)/.bashrc ``` 2. open new terminal 3. now you can run `customcommand` and get that response
You can set an alias like this, ``` alias sessmgr = "anbox session-manager --single-window --window-size=400,650" ``` Later, you can directly use `sessmgr`.
60,996,959
I have this command : ``` $ anbox session-manager --single-window --window-size=400,650 ``` and i need to run it **frequently**, is there any way to avoid **rewriting** it every time I need it ?
2020/04/02
['https://Stackoverflow.com/questions/60996959', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10863605/']
For permanently use 1. run this ``` echo 'alias customcommand="anbox session-manager --single-window --window-size=400,650"' >> /home/$(USER)/.bashrc ``` 2. open new terminal 3. now you can run `customcommand` and get that response
You can use the alias command, and if you want to make the change permanent you can append the alias command in your .bashrc file, so every time you launch a terminal you will have by default the defined alias that you set before in your .bashrc file. e.g. `alias <name_of_the_alias>="<command>".` You can find more info regarding alias [here](https://en.wikipedia.org/wiki/Alias_(command))
58,505,500
My code looks like this: ``` cIndex = (int)rand.Next(App.viewablePhrases.Count); phrase = App.viewablePhrases[cIndex]; ``` Infrequently it's giving me an error: ``` Application Specific Information: *** Terminating app due to uncaught exception 'SIGABRT', reason: 'Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index' Xamarin Exception Stack: System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index at System.Collections.Generic.List`1[T].get_Item (System.Int32 ) <0x10047bfc0 + 0x0007b> in <939d99b14d934342858948926287beba#d346c1f46aec0f7ce096300b9d7adc79>:0 at CardsTabViewModel.Random () <0x10138a5d0 + 0x0013b> in <1a94c4e2e6ff49bab0334b2d6333fc29#d346c1f46aec0f7ce096300b9d7adc79>:0 ``` Is there a way I could catch this exception to show more details?
2019/10/22
['https://Stackoverflow.com/questions/58505500', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1422604/']
> > Is there a way I could catch this exception to show more details? > > > Just put your code in try / catch block like this: ``` try { cIndex = (int)rand.Next(App.viewablePhrases.Count); phrase = App.viewablePhrases[cIndex]; } catch(System.ArgumentOutOfRangeException e) { Console.WriteLine("Exception information: {0}", e); } catch(Exception e) { Console.WriteLine("Exception information: {0}", e); } ``` Set a break point in catch block to see more information.
Index can be from 0 to Count-1.
38,710,913
I'm learning Angular on Plural Sight and the first lesson gives an example of how to use the ng-app directive. Here's a link to the Plunker editor <http://plnkr.co/edit/HIDCS8A9CR1jnAIDR0Zb?p=preview> ``` <!DOCTYPE html> <html> <head> <script data-require="angular.js@*" data-semver="2.0.0" src="https://code.angularjs.org/2.0.0-snapshot/angular2.js"></script> <link rel="stylesheet" href="style.css" /> <script src="script.js"></script> </head> <body ng-app> <h1>Hello Plunker!</h1> {{ 843 /42 }} </body> </html> ``` The example that was given uses the expression {{ 843 / 42 }} to demonstrate how angular would render the quotient on a webpage. I've copied the lesson script several times over and can't figure out what I'm doing wrong and why its rendering as text. This is my first post on stackoverflow, and I'm happy to join the community! Thanks Again. Shamus
2016/08/02
['https://Stackoverflow.com/questions/38710913', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6665622/']
The method you are looking for is this **[`org.bouncycastle.util.encoders.Base64.encode(byte[] data)`](https://people.eecs.berkeley.edu/~jonah/bc/org/bouncycastle/util/encoders/Base64.html#encode(byte[]))** I'm not sure where you got the reference to `Base64.toBase64String`, but a quick search shows that is very close to a similar C# method.
I guess you will have to use the methoad as below and check if it compiles ``` Base64.getEncoder().encodeToString(cipher.doFinal(initiatorpassword.getBytes())) ```
19,447,314
There in C# available any methods like serialize and unserialize in php? I need it for best way to transfer an array through network.
2013/10/18
['https://Stackoverflow.com/questions/19447314', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1146533/']
``` var countries = ["FR", "IT", "DE", "AU", "RU"]; $('div').hide(); $('select').change(function () { if ($.inArray(this.value, countries) >= 0) { $('div').show(); } else { $('div').hide(); } }); ``` [**FIDDLE**](http://jsfiddle.net/qYnKK/1/)
Try this, ``` var countries = ["FR", "IT", "DE", "AU", "RU"]; $('#myitems').hide(); $('#country').on('change', function () { if ($.inArray($(this).val(), countries)!=-1) { $('#myitems').show(); } else { $('#myitems').hide(); } }); ``` [Demo](http://jsfiddle.net/rohankumar1524/sVXJF/)
19,447,314
There in C# available any methods like serialize and unserialize in php? I need it for best way to transfer an array through network.
2013/10/18
['https://Stackoverflow.com/questions/19447314', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1146533/']
``` var countries = ["FR", "IT", "DE", "AU", "RU"]; $('div').hide(); $('select').change(function () { if ($.inArray(this.value, countries) >= 0) { $('div').show(); } else { $('div').hide(); } }); ``` [**FIDDLE**](http://jsfiddle.net/qYnKK/1/)
[JSFIDDLE](http://jsfiddle.net/zDuq5/) ``` var countries=["FR","IT","DE", "AU", "RU"]; $("#country").change(function(){ var selectedVal = $(this).val(); if(countries.indexOf(selectedVal) != -1){ $("#divToShow").show(); } else { $("#divToShow").hide(); } }); ```
19,447,314
There in C# available any methods like serialize and unserialize in php? I need it for best way to transfer an array through network.
2013/10/18
['https://Stackoverflow.com/questions/19447314', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1146533/']
``` var countries = ["FR", "IT", "DE", "AU", "RU"]; $('div').hide(); $('select').change(function () { if ($.inArray(this.value, countries) >= 0) { $('div').show(); } else { $('div').hide(); } }); ``` [**FIDDLE**](http://jsfiddle.net/qYnKK/1/)
**[Live Demo](http://jsfiddle.net/FfzgR/1/)** you can use `$.inArray("Your data", array)` using `Jquery` function for ex: **HTML:** ``` <select name="country" id="country"> <option value="0">Your country</option> <option value="IT">Afghanistan</option> <option value="AX">&#197;land Islands</option> <option value="RU">Albania</option> </select> ``` **JQuery:** ``` $(function() { $('select').on('change', function() { var countries=["FR","IT","DE", "AU", "RU"]; var data1 = $(this).val();http://jsfiddle.net/FfzgR/#update if ($.inArray(data1, countries) !== -1) { alert('yes'); } else{ alert('no'); } }); }); ```
54,126,434
Right now I'm calling an external bash script via open, because said script might run for seconds or it might run for minutes. The only things that are certain are: 1. It will output text which has to be displayed to the user. Not after the script is done, but while it is still running. 2. It will set a return code with different meanings Reading and using the text outputted by the shell script does work. But I don't have a clue on how to read the return code. The (simplified) TCL script looks like this: ``` #!/usr/bin/tclsh proc run_script {} { set script "./testing.sh" set process [open "|${script}" "r"] chan configure $process -blocking 0 -translation {"lf" "lf"} -encoding "iso8859-1" while {[eof $process] == 0} { if {[gets $process zeile] != -1} { puts $zeile } update } close $process return "???" } set rc [run_script] puts "RC = ${rc}" ``` The (simplified) shell script does look like this: ``` #!/bin/bash echo Here sleep 1 echo be sleep 2 echo dragons sleep 4 echo .... sleep 8 exit 20 ``` So how do I read the return code of the shell script via tcl?
2019/01/10
['https://Stackoverflow.com/questions/54126434', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6009051/']
You need to switch the file descriptor back to blocking before you close it to get the exit code. For example: You can use `try ... trap`, which was implemented with tcl 8.6: ``` chan configure $process -blocking 1 try { close $process # No error return 0 } trap CHILDSTATUS {result options} { return [lindex [dict get $options -errorcode] 2] } ``` An other option would be to use `catch`: ``` chan configure $process -blocking 1 if {[catch {close $process} result options]} { if {[lindex [dict get $options -errorcode] 0] eq "CHILDSTATUS"} { return [lindex [dict get $options -errorcode] 2] } else { # Rethrow other errors return -options [dict incr options -level] $result } } return 0 ```
To get the status in 8.5, use this: ``` fconfigure $process -blocking 1 if {[catch {close $process} result options] == 1} { set code [dict get $options -errorcode] if {[lindex $code 0] eq "CHILDSTATUS"} { return [lindex $code 2] } # handle other types of failure here... } ``` To get the status in 8.4, use this: ``` fconfigure $process -blocking 1 if {[catch {close $process}] == 1} { set code $::errorCode if {[lindex $code 0] eq "CHILDSTATUS"} { return [lindex $code 2] } # handle other types of failure here... } ```
34,811,616
As a complete beginner to VBA Excel, I would like to be able to do the following: I want to find the first value larger than 0 in a row, and then sum over the following 4 cells in the same row. So ``` Animal1 0 0 1 2 3 0 1 Animal2 3 3 0 1 4 2 0 Animal3 0 0 0 0 0 1 0 ``` Results in ``` Animal1 7 Animal2 11 Animal3 1 ``` Is this possible?
2016/01/15
['https://Stackoverflow.com/questions/34811616', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4729787/']
(Your problem description didn't match your examples. I interpreted the problem as one of summing the 4 elements in a row which begin with the first number which is greater than 0. If my interpretation is wrong -- the following code would need to be tweaked.) You could do it with a user-defined function (i.e. a UDF -- a VBA function designed to be used as a spreadsheet function): ``` Function SumAfter(R As Range, n As Long) As Variant 'Sums the (at most) n elements beginning with the first occurence of 'a strictly positive number in the range R, 'which is assumed to be 1-dimensional. 'If all numbers are zero or negative -- returns a #VALUE! error Dim i As Long, j As Long, m As Long Dim total As Variant m = R.Cells.Count For i = 1 To m If R.Cells(i).Value > 0 Then For j = i To Application.Min(m, i + n - 1) total = total + R.Cells(j) Next j SumAfter = total Exit Function End If Next i 'error condition if you reach here SumAfter = CVErr(xlErrValue) End Function ``` If your sample data is in `A1:H3` then putting the formula `=SumAfter(B1:H1,4)` in `I1` and copying down will work as intended. Note that the code is slightly more general than your problem description. If you are going to use VBA, you might as well make your subs/functions as flexible as possible. Also note that if you are writing a UDF, it is a good idea to think of what type of error you want to return if the input violates expectations. See [this](http://www.cpearson.com/Excel/ReturningErrors.aspx) for an excellent discussion (from Chip Pearson's site - which is an excellent resource for Excel VBA programmers). ON EDIT: If you want the first cell greater than 0 added to the next 4 (for a total of 5 cells in the sum) then the function I gave works as is, but using `=SumAfter(B1:H1,5)` instead of `=SumAfter(B1:H1,4)`.
Here is what I would use, I dont know any of the cell placement you have used so you will need to change that yourself. Future reference this isnt a code writing site for you, if you are new to VBA i suggest doing simple stuff first, make a message box appear, use code to move to different cells, try a few if statments and/or loops. When your comftable with that start using varibles(Booleans, string , intergers and such) and you will see how far you can go. As i like to say , "if you can do it in excel, code can do it better" If the code doesnt work or doesnt suit your needs then change it so it does, it worked for me when i used it but im not you nor do i have your spread sheet paste it into your vba and use F8 to go through it step by step see how it works and if you want to use it. ``` Sub test() [A1].Select ' assuming it starts in column A1 'loops till it reachs the end of the cells or till it hits a blank cell Do Until ActiveCell.Value = "" ActiveCell.Offset(0, 1).Select 'adds up the value of the cells going right and removes the previous cell to clean up Do Until ActiveCell.Value = "" x = x + ActiveCell.Value ActiveCell.Offset(0, 1).Select ActiveCell.Offset(0, -1).ClearContents Loop 'goes back to the begining and ends tallyed up value Selection.End(xlToLeft).Select ActiveCell.Offset(0, 1).Value = x 'moves down one to next row ActiveCell.Offset(1, 0).Select Loop End Sub ```
34,811,616
As a complete beginner to VBA Excel, I would like to be able to do the following: I want to find the first value larger than 0 in a row, and then sum over the following 4 cells in the same row. So ``` Animal1 0 0 1 2 3 0 1 Animal2 3 3 0 1 4 2 0 Animal3 0 0 0 0 0 1 0 ``` Results in ``` Animal1 7 Animal2 11 Animal3 1 ``` Is this possible?
2016/01/15
['https://Stackoverflow.com/questions/34811616', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4729787/']
This is the one of the variants of how you can achieve required result: ``` Sub test() Dim cl As Range, cl2 As Range, k, Dic As Object, i%: i = 1 Set Dic = CreateObject("Scripting.Dictionary") For Each cl In ActiveSheet.UsedRange.Columns(1).Cells For Each cl2 In Range(Cells(cl.Row, 2), Cells(cl.Row, 8)) If cl2.Value2 > 0 Then Dic.Add i, cl.Value2 & "|" & Application.Sum(Range(cl2, cl2.Offset(, 4))) i = i + 1 Exit For End If Next cl2, cl Workbooks.Add: i = 1 For Each k In Dic Cells(i, "A").Value2 = Split(Dic(k), "|")(0) Cells(i, "b").Value2 = CDec(Split(Dic(k), "|")(1)) i = i + 1 Next k End Sub ``` [![enter image description here](https://i.stack.imgur.com/rviN2.png)](https://i.stack.imgur.com/rviN2.png)
Here is what I would use, I dont know any of the cell placement you have used so you will need to change that yourself. Future reference this isnt a code writing site for you, if you are new to VBA i suggest doing simple stuff first, make a message box appear, use code to move to different cells, try a few if statments and/or loops. When your comftable with that start using varibles(Booleans, string , intergers and such) and you will see how far you can go. As i like to say , "if you can do it in excel, code can do it better" If the code doesnt work or doesnt suit your needs then change it so it does, it worked for me when i used it but im not you nor do i have your spread sheet paste it into your vba and use F8 to go through it step by step see how it works and if you want to use it. ``` Sub test() [A1].Select ' assuming it starts in column A1 'loops till it reachs the end of the cells or till it hits a blank cell Do Until ActiveCell.Value = "" ActiveCell.Offset(0, 1).Select 'adds up the value of the cells going right and removes the previous cell to clean up Do Until ActiveCell.Value = "" x = x + ActiveCell.Value ActiveCell.Offset(0, 1).Select ActiveCell.Offset(0, -1).ClearContents Loop 'goes back to the begining and ends tallyed up value Selection.End(xlToLeft).Select ActiveCell.Offset(0, 1).Value = x 'moves down one to next row ActiveCell.Offset(1, 0).Select Loop End Sub ```
34,811,616
As a complete beginner to VBA Excel, I would like to be able to do the following: I want to find the first value larger than 0 in a row, and then sum over the following 4 cells in the same row. So ``` Animal1 0 0 1 2 3 0 1 Animal2 3 3 0 1 4 2 0 Animal3 0 0 0 0 0 1 0 ``` Results in ``` Animal1 7 Animal2 11 Animal3 1 ``` Is this possible?
2016/01/15
['https://Stackoverflow.com/questions/34811616', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4729787/']
(Your problem description didn't match your examples. I interpreted the problem as one of summing the 4 elements in a row which begin with the first number which is greater than 0. If my interpretation is wrong -- the following code would need to be tweaked.) You could do it with a user-defined function (i.e. a UDF -- a VBA function designed to be used as a spreadsheet function): ``` Function SumAfter(R As Range, n As Long) As Variant 'Sums the (at most) n elements beginning with the first occurence of 'a strictly positive number in the range R, 'which is assumed to be 1-dimensional. 'If all numbers are zero or negative -- returns a #VALUE! error Dim i As Long, j As Long, m As Long Dim total As Variant m = R.Cells.Count For i = 1 To m If R.Cells(i).Value > 0 Then For j = i To Application.Min(m, i + n - 1) total = total + R.Cells(j) Next j SumAfter = total Exit Function End If Next i 'error condition if you reach here SumAfter = CVErr(xlErrValue) End Function ``` If your sample data is in `A1:H3` then putting the formula `=SumAfter(B1:H1,4)` in `I1` and copying down will work as intended. Note that the code is slightly more general than your problem description. If you are going to use VBA, you might as well make your subs/functions as flexible as possible. Also note that if you are writing a UDF, it is a good idea to think of what type of error you want to return if the input violates expectations. See [this](http://www.cpearson.com/Excel/ReturningErrors.aspx) for an excellent discussion (from Chip Pearson's site - which is an excellent resource for Excel VBA programmers). ON EDIT: If you want the first cell greater than 0 added to the next 4 (for a total of 5 cells in the sum) then the function I gave works as is, but using `=SumAfter(B1:H1,5)` instead of `=SumAfter(B1:H1,4)`.
This is the one of the variants of how you can achieve required result: ``` Sub test() Dim cl As Range, cl2 As Range, k, Dic As Object, i%: i = 1 Set Dic = CreateObject("Scripting.Dictionary") For Each cl In ActiveSheet.UsedRange.Columns(1).Cells For Each cl2 In Range(Cells(cl.Row, 2), Cells(cl.Row, 8)) If cl2.Value2 > 0 Then Dic.Add i, cl.Value2 & "|" & Application.Sum(Range(cl2, cl2.Offset(, 4))) i = i + 1 Exit For End If Next cl2, cl Workbooks.Add: i = 1 For Each k In Dic Cells(i, "A").Value2 = Split(Dic(k), "|")(0) Cells(i, "b").Value2 = CDec(Split(Dic(k), "|")(1)) i = i + 1 Next k End Sub ``` [![enter image description here](https://i.stack.imgur.com/rviN2.png)](https://i.stack.imgur.com/rviN2.png)