qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
36,865,742
On my project i have wordpress custom field data from mysql : ``` --------------------------------------------------- id | post_id | meta_key | meta_value --------------------------------------------------- 1 | 200 | age_min | 5 2 | 200 | age_max | 8 3 | 399 | ... | ... ``` My table structure ``` id => aut_increment meta_key => varchar(255) meta_value => longtext ``` From my sql script i have to find childs between 'age\_min and age\_max' and childs number : ``` SELECT DISTINCT p.ID , a.meta_value as nbrmin, b.meta_value as nbr_enfants_min , c.meta_value as age_min, d.meta_value as age_max FROM `6288gjvs_posts` as p LEFT JOIN 6288gjvs_postmeta as a ON a.post_id = p.ID LEFT JOIN 6288gjvs_postmeta as b ON b.post_id = p.ID LEFT JOIN 6288gjvs_postmeta as c ON c.post_id = p.ID LEFT JOIN 6288gjvs_postmeta as d ON d.post_id = p.ID WHERE p.post_type = 'product' AND post_status = 'publish' AND a.meta_key = 'childs_min_number' AND a.meta_value <= 2 AND b.meta_key = 'childs_max_number' AND b.meta_value >= 2 AND c.meta_key = 'age_min' AND c.meta_value = 1 AND d.meta_key = 'age_max' AND d.meta_value >= 10 ``` When i launch this query, this not working properly, because meta\_value type is a longtext and my php variables ( $this->age\_min, $this->age\_max ) are integers, so i cannot compare those 2 different type ? I tried to convert like this with no luck : ``` ... CONVERT(a.meta_value, DECIMAL) ... ``` as mentioned from this site : [Mysql conversion functions](http://www.geeksengine.com/database/single-row-functions/conversion-functions.php#p1-5) Anyone can help me please ? Thank you.
2016/04/26
[ "https://Stackoverflow.com/questions/36865742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Using ajax you can call a controller action and return it's response to a particular `div`. Empty `div`: ``` <div class="row" id="div3"> </div> ``` Ajax to display html in empty `div`: ``` function performSearch(searchCriteria) { //get information to pass to controller var searchInformation = JSON.stringify(**your search information**); $.ajax({ url: '@Url.Action("Search", "ControllerName")',//controller name and action type: 'POST', data: { 'svm': searchInformation } //information for search }) .success(function (result) { $('#div3').html(result); //write returned partial view to empty div }) .error(function (xhr, status) { alert(status); }) } ```
jQuery will help you with it! Try to handle submit button onclick event like this: ``` $("#yourButtonId").click(function() { $.ajax({ type: "POST", url: "/yourUrl", //in asp.net mvc using ActionResult data: data, dataType: 'html', success: function (result) { //Your result is here $("#yourContainerId").html(result); } }); }); ```
36,865,742
On my project i have wordpress custom field data from mysql : ``` --------------------------------------------------- id | post_id | meta_key | meta_value --------------------------------------------------- 1 | 200 | age_min | 5 2 | 200 | age_max | 8 3 | 399 | ... | ... ``` My table structure ``` id => aut_increment meta_key => varchar(255) meta_value => longtext ``` From my sql script i have to find childs between 'age\_min and age\_max' and childs number : ``` SELECT DISTINCT p.ID , a.meta_value as nbrmin, b.meta_value as nbr_enfants_min , c.meta_value as age_min, d.meta_value as age_max FROM `6288gjvs_posts` as p LEFT JOIN 6288gjvs_postmeta as a ON a.post_id = p.ID LEFT JOIN 6288gjvs_postmeta as b ON b.post_id = p.ID LEFT JOIN 6288gjvs_postmeta as c ON c.post_id = p.ID LEFT JOIN 6288gjvs_postmeta as d ON d.post_id = p.ID WHERE p.post_type = 'product' AND post_status = 'publish' AND a.meta_key = 'childs_min_number' AND a.meta_value <= 2 AND b.meta_key = 'childs_max_number' AND b.meta_value >= 2 AND c.meta_key = 'age_min' AND c.meta_value = 1 AND d.meta_key = 'age_max' AND d.meta_value >= 10 ``` When i launch this query, this not working properly, because meta\_value type is a longtext and my php variables ( $this->age\_min, $this->age\_max ) are integers, so i cannot compare those 2 different type ? I tried to convert like this with no luck : ``` ... CONVERT(a.meta_value, DECIMAL) ... ``` as mentioned from this site : [Mysql conversion functions](http://www.geeksengine.com/database/single-row-functions/conversion-functions.php#p1-5) Anyone can help me please ? Thank you.
2016/04/26
[ "https://Stackoverflow.com/questions/36865742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Using ajax you can call a controller action and return it's response to a particular `div`. Empty `div`: ``` <div class="row" id="div3"> </div> ``` Ajax to display html in empty `div`: ``` function performSearch(searchCriteria) { //get information to pass to controller var searchInformation = JSON.stringify(**your search information**); $.ajax({ url: '@Url.Action("Search", "ControllerName")',//controller name and action type: 'POST', data: { 'svm': searchInformation } //information for search }) .success(function (result) { $('#div3').html(result); //write returned partial view to empty div }) .error(function (xhr, status) { alert(status); }) } ```
You can do it with ajax. First, change your html.beginform to ajax.beginform in your view and add div id into **UpdateTargetId** that you want to change contents. After updating first partial with ajax.beginform, you can update other partialviews with ajax.beginform's **"OnSuccess"** function. You have to add update function like that: ``` @using (Ajax.BeginForm("YourAction", "YourController", new { /*your objects*/ }, new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "ChangeThisPart", OnSuccess = "OnSuccessMethod" })) { /*your code*/ } <script> function OnSuccessMethod() { $("#YouWantToChangeSecondDivID").load('/YourController/YourAction2'); $("#YouWantToChangeThirdDivID").load('/YourController/YourAction3'); }; </script> ``` Then in your controller, return a partial view to refresh your view part that you entered it's ID in UpdateTargetId value: ``` public ActionResult YourControllerName(YourModelType model) { ...//your code return PartialView("_YourPartialViewName", YourViewModel); } ``` **Note:** Don't forget to add reference to "jquery.unobtrusive-ajax.min.js" in your view while using ajax.
45,087
This is based on [xkcd #153](http://xkcd.com/153/). Make a program or named function which takes 2 parameters, each of which is a string or a list or array of bytes or characters. The second parameter will only contain characters drawn from `lrfu` (or the equivalent ASCII bytes). It should be interpreted as a series of instructions to be performed on a bit sequence represented by the first parameter. The processing performed must be equivalent to the following: 1. Convert the first parameter into a single bitstring formed by concatenating the bits of each character (interpreted as one of 7-bit ASCII, an 8-bit extended ASCII, or a standard Unicode encoding). E.g. if the first parameter is `"AB"` then this would be one of `10000011000010` (7-bit), `0100000101000010` (8-bit or UTF-8), `00000000010000010000000001000010`, or `01000001000000000100001000000000` (UTF-16 in the two endiannesses), etc. 2. For each character in the second parameter, in order, execute the corresponding instruction: * `l` rotates the bitstring left one. E.g. `10000011000010` becomes `00000110000101`. * `r` rotates the bitstring right one. E.g. `10000011000010` becomes `01000001100001`. * `f` flips (or inverts) each bit in the bitstring. E.g. `10000011000010` becomes `01111100111101`. * `u` reverses the bitstring. E.g. `10000011000010` becomes `01000011000001`. 3. Convert the bitstring into an ASCII string which uses one character per bit. E.g. `10000011000010` becomes `"10000011000010"`. This is because not all sets of 7/8 bits have a character assigned to them. Example (in Python): ``` >>> f("b", "rfu") 01110011 ``` It turns `"b"` into its 8-bit ASCII binary representation `01100010`, rotates it right (`00110001`), flips each bit (`11001110`), and reverses it (`01110011`). ### Flexibility Other characters may be used instead of the characters `l`, `r`, `f`, and `u`, but they must be clearly documented. ### Scoreboard Thanks to [@Optimizer](http://meta.codegolf.stackexchange.com/users/31414/optimizer) for creating the following code snippet. To use, click "Show code snippet", scroll to the bottom and click "► Run code snippet". ```js var QUESTION_ID = 45087; var answers = [], page = 1;var SCORE_REG = /\d+(?=[^\d&]*(?:&lt;(?:s&gt;[^&]*&lt;\/s&gt;|[^&]+&gt;)[^\d&]*)*$)/;function url(index) {return "http://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=votes&site=codegolf&filter=!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";}function getAnswers() {$.ajax({url: url(page++),method: "get",dataType: "jsonp",crossDomain: true,success: function (data) {answers.push.apply(answers, data.items);if (data.has_more) getAnswers();else process()}});}getAnswers();function shouldHaveHeading(a) {var pass = false;try {pass |= /^(#|&lt;h).*/.test(a.body_markdown);pass |= ["-", "="].indexOf(a.body_markdown.split("\n")[1][0]) > -1;} catch (ex) {}return pass;}function shouldHaveScore(a) {var pass = false;try {pass |= SCORE_REG.test(a.body_markdown.split("\n")[0]);} catch (ex) {}return pass;}function getRelDate(previous) {var current = Date.now();var msPerMinute = 60 * 1000;var msPerHour = msPerMinute * 60;var msPerDay = msPerHour * 24;var msPerMonth = msPerDay * 30;var msPerYear = msPerDay * 365;var elapsed = current - previous;if (elapsed < msPerMinute) {return Math.round(elapsed/1000) + ' seconds ago';}if (elapsed < msPerHour) {return Math.round(elapsed/msPerMinute) + ' minutes ago';}if (elapsed < msPerDay ) {return Math.round(elapsed/msPerHour ) + ' hours ago';}if (elapsed < msPerMonth) {return 'approx. ' + Math.round(elapsed/msPerDay) + ' days ago';}if (elapsed < msPerYear) {return 'approx. ' + Math.round(elapsed/msPerMonth) + ' months ago';}return 'approx. ' + Math.round(elapsed/msPerYear ) + ' years ago';}function process() {answers = answers.filter(shouldHaveHeading);answers = answers.filter(shouldHaveScore);answers.sort(function (a, b) {var aB = +(a.body_markdown.split("\n")[0].match(SCORE_REG) || [Infinity])[0],bB = +(b.body_markdown.split("\n")[0].match(SCORE_REG) || [Infinity])[0];return aB - bB});answers.forEach(function (a) {var answer = $("#answer-template").html();answer = answer.replace("{{BODY}}", a.body).replace("{{NAME}}", a.owner.display_name).replace("{{REP}}", a.owner.reputation).replace("{{VOTES}}", a.score).replace("{{DATE}}", new Date(a.creation_date*1e3).toUTCString()).replace("{{REL_TIME}}", getRelDate(a.creation_date*1e3)).replace("{{POST_LINK}}", a.share_link).replace(/{{USER_LINK}}/g, a.owner.link).replace('{{img}}=""', "src=\"" + a.owner.profile_image + '"');answer = $(answer);if (a.is_accepted) {answer.find(".vote-accepted-on").removeAttr("style");}$("#answers").append(answer);});} ``` ```css body { text-align: left !important} ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id="answers"></div><div id="answer-template" style="display: none"><div class="answer" ><table><tbody><tr><td class="votecell"><div class="vote"><span style="cursor: pointer;" title="Total Votes" itemprop="upvoteCount" class="vote-count-post ">{{VOTES}}</span><span style="display: none" class="vote-accepted-on load-accepted-answer-date" title="The question owner accepted this as the best answer">accepted</span></div></td><td class="answercell"><div class="post-text" itemprop="text">{{BODY}}</div><table class="fw"><tbody><tr><td class="vt"><div class="post-menu"><a href="{{POST_LINK}}" title="short permalink to this answer" class="short-link">share</a></div></td><td class="post-signature" align="right"><div class="user-info "><div class="user-action-time">answered <span title="{{DATE}}" class="relativetime">{{REL_TIME}}</span></div><div class="user-gravatar32"></div><div class="user-details"><br></div></div></td><td class="post-signature" align="right"><div class="user-info user-hover"><div class="user-action-time"></div><div class="user-gravatar32"><a href="{{USER_LINK}}"><div class="gravatar-wrapper-32"><img {{img}} alt="" height="32" width="32"></div></a></div><div class="user-details"><a href="{{USER_LINK}}">{{NAME}}</a><br><span class="reputation-score" title="reputation score " dir="ltr">{{REP}}</span></div></div></td></tr></tbody></table></td></tr></tbody></table></div></div> ```
2015/01/27
[ "https://codegolf.stackexchange.com/questions/45087", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/-1/" ]
CJam, ~~34~~ 32 bytes ===================== ``` 1l+256b2b1>l{~"11W:mm%!<>">4%~}/ ``` It uses the following characters for instructions: ``` 0: left rotation 1: right rotation 2: reverse 3: flip ``` The input is taking from STDIN with the word on the first line and the instruction string on the second line. [Test it here.](http://cjam.aditsu.net/) Explanation ----------- Getting the bit string is really just a matter of interpreting the character codes as the digits of a base-256 number (and getting its base-2 representation). The tricky thing is that the latter base conversion won't pad the result with 0s on the left. Therefore, I add a leading 1 to the initial input, and then split off that 1 again in the binary representation. As an example, if the input is `ab`, I turn that into an array `[1 'a 'b]`, interpret that as base-256 (characters are automatically converted to character codes), which is `90466` and the to base-2, which is `[1 0 1 1 0 0 0 0 1 0 1 1 0 0 0 1 0]`. Now if I just remove that leading `1` I've got the bitstream I'm looking for. That's what this part of the code does: ``` 1l+256b2b1> ``` Now I read the list of instructions and execute a block for each character in the instruction string: ``` l{...}/ ``` The first thing to do is to evaluate the character and actual integers`0`, `1`, `2` or `3`. Now the real golfy magic... depending on the instruction I want to run a short piece of code that implements the operation: ``` Integer: Code Operation 0 1m< "Left rotation"; 1 1m> "Right rotation"; 2 W% "Reverse"; 3 :! "Flip each bit"; ``` I could store these in an array of blocks and choose the right block to run, but encoding them in a string is actually shorter: ``` "11W:mm%!<>">4%~ ``` First, I use the integer associate with the instruction to slice off the beginning of the string. So for left rotation, the string is unchanged, for right rotation the first character is discarded and so on. Then I select every fourth character from the string, starting from the first, with `4%`. Notice how the four code snippets are distributed throughout the string. Finally I just evaluate the string as code with `~`. The bit string is printed automatically at the end of the program.
JavaScript (E6), 163 ~~167~~ ============================ Fully using the input flexibility, a named function with 2 array parameters. * First parameter, array of bytes corresponding to 7 bit character codes * Second parameter, array of bytes corresponding to ascii characters 'F','L','R','U' --> 70, 76, 82, 85 The function returns a character string composed of '1' and '0' ```js F=(a,s,r='')=> a.map(c=>r+=(128|c).toString(2).slice(-7))- s.map(c=>a=c<71?a.map(c=>1-c):c<77?a.concat(a.shift):c<83?[a.pop(),...a]:a.reverse(),a=[...r]) ||a.join('') ``` **Example** `f("b", "rfu")` translate to `F([98],[82,70,85])`, result is `0111001` **Note** using character strings is so much longer in javascript! Byte count **186** ```js F=(a,s,r='')=> [for(c of a)r+=(128|c.charCodeAt()).toString(2).slice(-7)]- [for(c of(a=[...r],s))a=c<'G'?a.map(c=>1-c):c<'M'?a.concat(a.shift):c<'S'?[a.pop(),...a]:a.reverse()] ||a.join('') ``` **Example** `F("b", "RFU")`, result is `0111001` again
45,087
This is based on [xkcd #153](http://xkcd.com/153/). Make a program or named function which takes 2 parameters, each of which is a string or a list or array of bytes or characters. The second parameter will only contain characters drawn from `lrfu` (or the equivalent ASCII bytes). It should be interpreted as a series of instructions to be performed on a bit sequence represented by the first parameter. The processing performed must be equivalent to the following: 1. Convert the first parameter into a single bitstring formed by concatenating the bits of each character (interpreted as one of 7-bit ASCII, an 8-bit extended ASCII, or a standard Unicode encoding). E.g. if the first parameter is `"AB"` then this would be one of `10000011000010` (7-bit), `0100000101000010` (8-bit or UTF-8), `00000000010000010000000001000010`, or `01000001000000000100001000000000` (UTF-16 in the two endiannesses), etc. 2. For each character in the second parameter, in order, execute the corresponding instruction: * `l` rotates the bitstring left one. E.g. `10000011000010` becomes `00000110000101`. * `r` rotates the bitstring right one. E.g. `10000011000010` becomes `01000001100001`. * `f` flips (or inverts) each bit in the bitstring. E.g. `10000011000010` becomes `01111100111101`. * `u` reverses the bitstring. E.g. `10000011000010` becomes `01000011000001`. 3. Convert the bitstring into an ASCII string which uses one character per bit. E.g. `10000011000010` becomes `"10000011000010"`. This is because not all sets of 7/8 bits have a character assigned to them. Example (in Python): ``` >>> f("b", "rfu") 01110011 ``` It turns `"b"` into its 8-bit ASCII binary representation `01100010`, rotates it right (`00110001`), flips each bit (`11001110`), and reverses it (`01110011`). ### Flexibility Other characters may be used instead of the characters `l`, `r`, `f`, and `u`, but they must be clearly documented. ### Scoreboard Thanks to [@Optimizer](http://meta.codegolf.stackexchange.com/users/31414/optimizer) for creating the following code snippet. To use, click "Show code snippet", scroll to the bottom and click "► Run code snippet". ```js var QUESTION_ID = 45087; var answers = [], page = 1;var SCORE_REG = /\d+(?=[^\d&]*(?:&lt;(?:s&gt;[^&]*&lt;\/s&gt;|[^&]+&gt;)[^\d&]*)*$)/;function url(index) {return "http://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=votes&site=codegolf&filter=!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";}function getAnswers() {$.ajax({url: url(page++),method: "get",dataType: "jsonp",crossDomain: true,success: function (data) {answers.push.apply(answers, data.items);if (data.has_more) getAnswers();else process()}});}getAnswers();function shouldHaveHeading(a) {var pass = false;try {pass |= /^(#|&lt;h).*/.test(a.body_markdown);pass |= ["-", "="].indexOf(a.body_markdown.split("\n")[1][0]) > -1;} catch (ex) {}return pass;}function shouldHaveScore(a) {var pass = false;try {pass |= SCORE_REG.test(a.body_markdown.split("\n")[0]);} catch (ex) {}return pass;}function getRelDate(previous) {var current = Date.now();var msPerMinute = 60 * 1000;var msPerHour = msPerMinute * 60;var msPerDay = msPerHour * 24;var msPerMonth = msPerDay * 30;var msPerYear = msPerDay * 365;var elapsed = current - previous;if (elapsed < msPerMinute) {return Math.round(elapsed/1000) + ' seconds ago';}if (elapsed < msPerHour) {return Math.round(elapsed/msPerMinute) + ' minutes ago';}if (elapsed < msPerDay ) {return Math.round(elapsed/msPerHour ) + ' hours ago';}if (elapsed < msPerMonth) {return 'approx. ' + Math.round(elapsed/msPerDay) + ' days ago';}if (elapsed < msPerYear) {return 'approx. ' + Math.round(elapsed/msPerMonth) + ' months ago';}return 'approx. ' + Math.round(elapsed/msPerYear ) + ' years ago';}function process() {answers = answers.filter(shouldHaveHeading);answers = answers.filter(shouldHaveScore);answers.sort(function (a, b) {var aB = +(a.body_markdown.split("\n")[0].match(SCORE_REG) || [Infinity])[0],bB = +(b.body_markdown.split("\n")[0].match(SCORE_REG) || [Infinity])[0];return aB - bB});answers.forEach(function (a) {var answer = $("#answer-template").html();answer = answer.replace("{{BODY}}", a.body).replace("{{NAME}}", a.owner.display_name).replace("{{REP}}", a.owner.reputation).replace("{{VOTES}}", a.score).replace("{{DATE}}", new Date(a.creation_date*1e3).toUTCString()).replace("{{REL_TIME}}", getRelDate(a.creation_date*1e3)).replace("{{POST_LINK}}", a.share_link).replace(/{{USER_LINK}}/g, a.owner.link).replace('{{img}}=""', "src=\"" + a.owner.profile_image + '"');answer = $(answer);if (a.is_accepted) {answer.find(".vote-accepted-on").removeAttr("style");}$("#answers").append(answer);});} ``` ```css body { text-align: left !important} ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id="answers"></div><div id="answer-template" style="display: none"><div class="answer" ><table><tbody><tr><td class="votecell"><div class="vote"><span style="cursor: pointer;" title="Total Votes" itemprop="upvoteCount" class="vote-count-post ">{{VOTES}}</span><span style="display: none" class="vote-accepted-on load-accepted-answer-date" title="The question owner accepted this as the best answer">accepted</span></div></td><td class="answercell"><div class="post-text" itemprop="text">{{BODY}}</div><table class="fw"><tbody><tr><td class="vt"><div class="post-menu"><a href="{{POST_LINK}}" title="short permalink to this answer" class="short-link">share</a></div></td><td class="post-signature" align="right"><div class="user-info "><div class="user-action-time">answered <span title="{{DATE}}" class="relativetime">{{REL_TIME}}</span></div><div class="user-gravatar32"></div><div class="user-details"><br></div></div></td><td class="post-signature" align="right"><div class="user-info user-hover"><div class="user-action-time"></div><div class="user-gravatar32"><a href="{{USER_LINK}}"><div class="gravatar-wrapper-32"><img {{img}} alt="" height="32" width="32"></div></a></div><div class="user-details"><a href="{{USER_LINK}}">{{NAME}}</a><br><span class="reputation-score" title="reputation score " dir="ltr">{{REP}}</span></div></div></td></tr></tbody></table></td></tr></tbody></table></div></div> ```
2015/01/27
[ "https://codegolf.stackexchange.com/questions/45087", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/-1/" ]
CJam, ~~34~~ 32 bytes ===================== ``` 1l+256b2b1>l{~"11W:mm%!<>">4%~}/ ``` It uses the following characters for instructions: ``` 0: left rotation 1: right rotation 2: reverse 3: flip ``` The input is taking from STDIN with the word on the first line and the instruction string on the second line. [Test it here.](http://cjam.aditsu.net/) Explanation ----------- Getting the bit string is really just a matter of interpreting the character codes as the digits of a base-256 number (and getting its base-2 representation). The tricky thing is that the latter base conversion won't pad the result with 0s on the left. Therefore, I add a leading 1 to the initial input, and then split off that 1 again in the binary representation. As an example, if the input is `ab`, I turn that into an array `[1 'a 'b]`, interpret that as base-256 (characters are automatically converted to character codes), which is `90466` and the to base-2, which is `[1 0 1 1 0 0 0 0 1 0 1 1 0 0 0 1 0]`. Now if I just remove that leading `1` I've got the bitstream I'm looking for. That's what this part of the code does: ``` 1l+256b2b1> ``` Now I read the list of instructions and execute a block for each character in the instruction string: ``` l{...}/ ``` The first thing to do is to evaluate the character and actual integers`0`, `1`, `2` or `3`. Now the real golfy magic... depending on the instruction I want to run a short piece of code that implements the operation: ``` Integer: Code Operation 0 1m< "Left rotation"; 1 1m> "Right rotation"; 2 W% "Reverse"; 3 :! "Flip each bit"; ``` I could store these in an array of blocks and choose the right block to run, but encoding them in a string is actually shorter: ``` "11W:mm%!<>">4%~ ``` First, I use the integer associate with the instruction to slice off the beginning of the string. So for left rotation, the string is unchanged, for right rotation the first character is discarded and so on. Then I select every fourth character from the string, starting from the first, with `4%`. Notice how the four code snippets are distributed throughout the string. Finally I just evaluate the string as code with `~`. The bit string is printed automatically at the end of the program.
Matlab (166 bytes) ================== This uses letters `abcd` instead of `lrfu` respectively. ``` function D=f(B,C) D=dec2bin(B,8)'; D=D(:); g=@circshift; for c=C switch c-97 case 0 D=g(D,-1); case 1 D=g(D,1); case 2 D=char(97-D); case 3 D=flipud(D); end end D=D'; ``` Some tricks used here to save space: * Using `abcd` letters lets me subtract `97` once, and then the letters become `0`, `1`, `2`, `3`. This saves space in the `switch`-`case` clauses. * Defining `circshift` as a one-letter anonymous function also saves space, as it's used twice. * Since `D` consists of `'0'` and `'1'` characters (ASCII codes `48` and `49`), the statement `D=char(97-D)` corresponds to inversion between `'0'` and `'1'` values. Note that this `97` has nothing to do with that referred to above. * Complex-conjugate transpose `'` is used instead of transpose `.'`.
45,087
This is based on [xkcd #153](http://xkcd.com/153/). Make a program or named function which takes 2 parameters, each of which is a string or a list or array of bytes or characters. The second parameter will only contain characters drawn from `lrfu` (or the equivalent ASCII bytes). It should be interpreted as a series of instructions to be performed on a bit sequence represented by the first parameter. The processing performed must be equivalent to the following: 1. Convert the first parameter into a single bitstring formed by concatenating the bits of each character (interpreted as one of 7-bit ASCII, an 8-bit extended ASCII, or a standard Unicode encoding). E.g. if the first parameter is `"AB"` then this would be one of `10000011000010` (7-bit), `0100000101000010` (8-bit or UTF-8), `00000000010000010000000001000010`, or `01000001000000000100001000000000` (UTF-16 in the two endiannesses), etc. 2. For each character in the second parameter, in order, execute the corresponding instruction: * `l` rotates the bitstring left one. E.g. `10000011000010` becomes `00000110000101`. * `r` rotates the bitstring right one. E.g. `10000011000010` becomes `01000001100001`. * `f` flips (or inverts) each bit in the bitstring. E.g. `10000011000010` becomes `01111100111101`. * `u` reverses the bitstring. E.g. `10000011000010` becomes `01000011000001`. 3. Convert the bitstring into an ASCII string which uses one character per bit. E.g. `10000011000010` becomes `"10000011000010"`. This is because not all sets of 7/8 bits have a character assigned to them. Example (in Python): ``` >>> f("b", "rfu") 01110011 ``` It turns `"b"` into its 8-bit ASCII binary representation `01100010`, rotates it right (`00110001`), flips each bit (`11001110`), and reverses it (`01110011`). ### Flexibility Other characters may be used instead of the characters `l`, `r`, `f`, and `u`, but they must be clearly documented. ### Scoreboard Thanks to [@Optimizer](http://meta.codegolf.stackexchange.com/users/31414/optimizer) for creating the following code snippet. To use, click "Show code snippet", scroll to the bottom and click "► Run code snippet". ```js var QUESTION_ID = 45087; var answers = [], page = 1;var SCORE_REG = /\d+(?=[^\d&]*(?:&lt;(?:s&gt;[^&]*&lt;\/s&gt;|[^&]+&gt;)[^\d&]*)*$)/;function url(index) {return "http://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=votes&site=codegolf&filter=!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";}function getAnswers() {$.ajax({url: url(page++),method: "get",dataType: "jsonp",crossDomain: true,success: function (data) {answers.push.apply(answers, data.items);if (data.has_more) getAnswers();else process()}});}getAnswers();function shouldHaveHeading(a) {var pass = false;try {pass |= /^(#|&lt;h).*/.test(a.body_markdown);pass |= ["-", "="].indexOf(a.body_markdown.split("\n")[1][0]) > -1;} catch (ex) {}return pass;}function shouldHaveScore(a) {var pass = false;try {pass |= SCORE_REG.test(a.body_markdown.split("\n")[0]);} catch (ex) {}return pass;}function getRelDate(previous) {var current = Date.now();var msPerMinute = 60 * 1000;var msPerHour = msPerMinute * 60;var msPerDay = msPerHour * 24;var msPerMonth = msPerDay * 30;var msPerYear = msPerDay * 365;var elapsed = current - previous;if (elapsed < msPerMinute) {return Math.round(elapsed/1000) + ' seconds ago';}if (elapsed < msPerHour) {return Math.round(elapsed/msPerMinute) + ' minutes ago';}if (elapsed < msPerDay ) {return Math.round(elapsed/msPerHour ) + ' hours ago';}if (elapsed < msPerMonth) {return 'approx. ' + Math.round(elapsed/msPerDay) + ' days ago';}if (elapsed < msPerYear) {return 'approx. ' + Math.round(elapsed/msPerMonth) + ' months ago';}return 'approx. ' + Math.round(elapsed/msPerYear ) + ' years ago';}function process() {answers = answers.filter(shouldHaveHeading);answers = answers.filter(shouldHaveScore);answers.sort(function (a, b) {var aB = +(a.body_markdown.split("\n")[0].match(SCORE_REG) || [Infinity])[0],bB = +(b.body_markdown.split("\n")[0].match(SCORE_REG) || [Infinity])[0];return aB - bB});answers.forEach(function (a) {var answer = $("#answer-template").html();answer = answer.replace("{{BODY}}", a.body).replace("{{NAME}}", a.owner.display_name).replace("{{REP}}", a.owner.reputation).replace("{{VOTES}}", a.score).replace("{{DATE}}", new Date(a.creation_date*1e3).toUTCString()).replace("{{REL_TIME}}", getRelDate(a.creation_date*1e3)).replace("{{POST_LINK}}", a.share_link).replace(/{{USER_LINK}}/g, a.owner.link).replace('{{img}}=""', "src=\"" + a.owner.profile_image + '"');answer = $(answer);if (a.is_accepted) {answer.find(".vote-accepted-on").removeAttr("style");}$("#answers").append(answer);});} ``` ```css body { text-align: left !important} ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id="answers"></div><div id="answer-template" style="display: none"><div class="answer" ><table><tbody><tr><td class="votecell"><div class="vote"><span style="cursor: pointer;" title="Total Votes" itemprop="upvoteCount" class="vote-count-post ">{{VOTES}}</span><span style="display: none" class="vote-accepted-on load-accepted-answer-date" title="The question owner accepted this as the best answer">accepted</span></div></td><td class="answercell"><div class="post-text" itemprop="text">{{BODY}}</div><table class="fw"><tbody><tr><td class="vt"><div class="post-menu"><a href="{{POST_LINK}}" title="short permalink to this answer" class="short-link">share</a></div></td><td class="post-signature" align="right"><div class="user-info "><div class="user-action-time">answered <span title="{{DATE}}" class="relativetime">{{REL_TIME}}</span></div><div class="user-gravatar32"></div><div class="user-details"><br></div></div></td><td class="post-signature" align="right"><div class="user-info user-hover"><div class="user-action-time"></div><div class="user-gravatar32"><a href="{{USER_LINK}}"><div class="gravatar-wrapper-32"><img {{img}} alt="" height="32" width="32"></div></a></div><div class="user-details"><a href="{{USER_LINK}}">{{NAME}}</a><br><span class="reputation-score" title="reputation score " dir="ltr">{{REP}}</span></div></div></td></tr></tbody></table></td></tr></tbody></table></div></div> ```
2015/01/27
[ "https://codegolf.stackexchange.com/questions/45087", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/-1/" ]
CJam, ~~34~~ 32 bytes ===================== ``` 1l+256b2b1>l{~"11W:mm%!<>">4%~}/ ``` It uses the following characters for instructions: ``` 0: left rotation 1: right rotation 2: reverse 3: flip ``` The input is taking from STDIN with the word on the first line and the instruction string on the second line. [Test it here.](http://cjam.aditsu.net/) Explanation ----------- Getting the bit string is really just a matter of interpreting the character codes as the digits of a base-256 number (and getting its base-2 representation). The tricky thing is that the latter base conversion won't pad the result with 0s on the left. Therefore, I add a leading 1 to the initial input, and then split off that 1 again in the binary representation. As an example, if the input is `ab`, I turn that into an array `[1 'a 'b]`, interpret that as base-256 (characters are automatically converted to character codes), which is `90466` and the to base-2, which is `[1 0 1 1 0 0 0 0 1 0 1 1 0 0 0 1 0]`. Now if I just remove that leading `1` I've got the bitstream I'm looking for. That's what this part of the code does: ``` 1l+256b2b1> ``` Now I read the list of instructions and execute a block for each character in the instruction string: ``` l{...}/ ``` The first thing to do is to evaluate the character and actual integers`0`, `1`, `2` or `3`. Now the real golfy magic... depending on the instruction I want to run a short piece of code that implements the operation: ``` Integer: Code Operation 0 1m< "Left rotation"; 1 1m> "Right rotation"; 2 W% "Reverse"; 3 :! "Flip each bit"; ``` I could store these in an array of blocks and choose the right block to run, but encoding them in a string is actually shorter: ``` "11W:mm%!<>">4%~ ``` First, I use the integer associate with the instruction to slice off the beginning of the string. So for left rotation, the string is unchanged, for right rotation the first character is discarded and so on. Then I select every fourth character from the string, starting from the first, with `4%`. Notice how the four code snippets are distributed throughout the string. Finally I just evaluate the string as code with `~`. The bit string is printed automatically at the end of the program.
J, 164 ------ ``` ([: >@:}. (([: }. >&{.) ; >@:{.@:>@:{. 128!:2 >@:}.)^:({.@:$@:>@:{.))@:(>@:((<;._1 ' 1&|."1 _1&|."1 -. |."1') {~ 'lrfu' i. 0&({::)@:]) ; ;@:([: (8$2)&#: a. i. 1&({::))) ``` Formatted: ``` nextop=:([: }. >&{.) exec=: (>@:{.@:>@:{.) apply"1 >@:}. times=: ({.@:$@:>@:{.) gapply=: [: >@:}. (nextop ; exec)^:(times) f. tobin=: ;@:([: (8#2)&#:(a.i.1&{::)) g=:'1&|.';'_1&|.';'-.';'|.' tog =: g {~ ('lrfu' i. 0&{::@:]) golf=: gapply @: (>@:tog;tobin) f. ``` Example ``` golf ('rfu';'b') 0 1 1 1 0 0 1 1 golf ('lruuff';'b') 0 1 1 0 0 0 1 0 (8#2)#: 98 0 1 1 0 0 0 1 0 golf ('lruuff';'AB') 0 1 0 0 0 0 0 1 0 1 0 0 0 0 1 0 tobin '';'AB' 0 1 0 0 0 0 0 1 0 1 0 0 0 0 1 0 ```
45,087
This is based on [xkcd #153](http://xkcd.com/153/). Make a program or named function which takes 2 parameters, each of which is a string or a list or array of bytes or characters. The second parameter will only contain characters drawn from `lrfu` (or the equivalent ASCII bytes). It should be interpreted as a series of instructions to be performed on a bit sequence represented by the first parameter. The processing performed must be equivalent to the following: 1. Convert the first parameter into a single bitstring formed by concatenating the bits of each character (interpreted as one of 7-bit ASCII, an 8-bit extended ASCII, or a standard Unicode encoding). E.g. if the first parameter is `"AB"` then this would be one of `10000011000010` (7-bit), `0100000101000010` (8-bit or UTF-8), `00000000010000010000000001000010`, or `01000001000000000100001000000000` (UTF-16 in the two endiannesses), etc. 2. For each character in the second parameter, in order, execute the corresponding instruction: * `l` rotates the bitstring left one. E.g. `10000011000010` becomes `00000110000101`. * `r` rotates the bitstring right one. E.g. `10000011000010` becomes `01000001100001`. * `f` flips (or inverts) each bit in the bitstring. E.g. `10000011000010` becomes `01111100111101`. * `u` reverses the bitstring. E.g. `10000011000010` becomes `01000011000001`. 3. Convert the bitstring into an ASCII string which uses one character per bit. E.g. `10000011000010` becomes `"10000011000010"`. This is because not all sets of 7/8 bits have a character assigned to them. Example (in Python): ``` >>> f("b", "rfu") 01110011 ``` It turns `"b"` into its 8-bit ASCII binary representation `01100010`, rotates it right (`00110001`), flips each bit (`11001110`), and reverses it (`01110011`). ### Flexibility Other characters may be used instead of the characters `l`, `r`, `f`, and `u`, but they must be clearly documented. ### Scoreboard Thanks to [@Optimizer](http://meta.codegolf.stackexchange.com/users/31414/optimizer) for creating the following code snippet. To use, click "Show code snippet", scroll to the bottom and click "► Run code snippet". ```js var QUESTION_ID = 45087; var answers = [], page = 1;var SCORE_REG = /\d+(?=[^\d&]*(?:&lt;(?:s&gt;[^&]*&lt;\/s&gt;|[^&]+&gt;)[^\d&]*)*$)/;function url(index) {return "http://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=votes&site=codegolf&filter=!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";}function getAnswers() {$.ajax({url: url(page++),method: "get",dataType: "jsonp",crossDomain: true,success: function (data) {answers.push.apply(answers, data.items);if (data.has_more) getAnswers();else process()}});}getAnswers();function shouldHaveHeading(a) {var pass = false;try {pass |= /^(#|&lt;h).*/.test(a.body_markdown);pass |= ["-", "="].indexOf(a.body_markdown.split("\n")[1][0]) > -1;} catch (ex) {}return pass;}function shouldHaveScore(a) {var pass = false;try {pass |= SCORE_REG.test(a.body_markdown.split("\n")[0]);} catch (ex) {}return pass;}function getRelDate(previous) {var current = Date.now();var msPerMinute = 60 * 1000;var msPerHour = msPerMinute * 60;var msPerDay = msPerHour * 24;var msPerMonth = msPerDay * 30;var msPerYear = msPerDay * 365;var elapsed = current - previous;if (elapsed < msPerMinute) {return Math.round(elapsed/1000) + ' seconds ago';}if (elapsed < msPerHour) {return Math.round(elapsed/msPerMinute) + ' minutes ago';}if (elapsed < msPerDay ) {return Math.round(elapsed/msPerHour ) + ' hours ago';}if (elapsed < msPerMonth) {return 'approx. ' + Math.round(elapsed/msPerDay) + ' days ago';}if (elapsed < msPerYear) {return 'approx. ' + Math.round(elapsed/msPerMonth) + ' months ago';}return 'approx. ' + Math.round(elapsed/msPerYear ) + ' years ago';}function process() {answers = answers.filter(shouldHaveHeading);answers = answers.filter(shouldHaveScore);answers.sort(function (a, b) {var aB = +(a.body_markdown.split("\n")[0].match(SCORE_REG) || [Infinity])[0],bB = +(b.body_markdown.split("\n")[0].match(SCORE_REG) || [Infinity])[0];return aB - bB});answers.forEach(function (a) {var answer = $("#answer-template").html();answer = answer.replace("{{BODY}}", a.body).replace("{{NAME}}", a.owner.display_name).replace("{{REP}}", a.owner.reputation).replace("{{VOTES}}", a.score).replace("{{DATE}}", new Date(a.creation_date*1e3).toUTCString()).replace("{{REL_TIME}}", getRelDate(a.creation_date*1e3)).replace("{{POST_LINK}}", a.share_link).replace(/{{USER_LINK}}/g, a.owner.link).replace('{{img}}=""', "src=\"" + a.owner.profile_image + '"');answer = $(answer);if (a.is_accepted) {answer.find(".vote-accepted-on").removeAttr("style");}$("#answers").append(answer);});} ``` ```css body { text-align: left !important} ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id="answers"></div><div id="answer-template" style="display: none"><div class="answer" ><table><tbody><tr><td class="votecell"><div class="vote"><span style="cursor: pointer;" title="Total Votes" itemprop="upvoteCount" class="vote-count-post ">{{VOTES}}</span><span style="display: none" class="vote-accepted-on load-accepted-answer-date" title="The question owner accepted this as the best answer">accepted</span></div></td><td class="answercell"><div class="post-text" itemprop="text">{{BODY}}</div><table class="fw"><tbody><tr><td class="vt"><div class="post-menu"><a href="{{POST_LINK}}" title="short permalink to this answer" class="short-link">share</a></div></td><td class="post-signature" align="right"><div class="user-info "><div class="user-action-time">answered <span title="{{DATE}}" class="relativetime">{{REL_TIME}}</span></div><div class="user-gravatar32"></div><div class="user-details"><br></div></div></td><td class="post-signature" align="right"><div class="user-info user-hover"><div class="user-action-time"></div><div class="user-gravatar32"><a href="{{USER_LINK}}"><div class="gravatar-wrapper-32"><img {{img}} alt="" height="32" width="32"></div></a></div><div class="user-details"><a href="{{USER_LINK}}">{{NAME}}</a><br><span class="reputation-score" title="reputation score " dir="ltr">{{REP}}</span></div></div></td></tr></tbody></table></td></tr></tbody></table></div></div> ```
2015/01/27
[ "https://codegolf.stackexchange.com/questions/45087", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/-1/" ]
Matlab (166 bytes) ================== This uses letters `abcd` instead of `lrfu` respectively. ``` function D=f(B,C) D=dec2bin(B,8)'; D=D(:); g=@circshift; for c=C switch c-97 case 0 D=g(D,-1); case 1 D=g(D,1); case 2 D=char(97-D); case 3 D=flipud(D); end end D=D'; ``` Some tricks used here to save space: * Using `abcd` letters lets me subtract `97` once, and then the letters become `0`, `1`, `2`, `3`. This saves space in the `switch`-`case` clauses. * Defining `circshift` as a one-letter anonymous function also saves space, as it's used twice. * Since `D` consists of `'0'` and `'1'` characters (ASCII codes `48` and `49`), the statement `D=char(97-D)` corresponds to inversion between `'0'` and `'1'` values. Note that this `97` has nothing to do with that referred to above. * Complex-conjugate transpose `'` is used instead of transpose `.'`.
### C#, 418 bytes ``` using System;using System.Collections.Generic;using System.Linq;class P{string F(string a,string o){var f=new Dictionary<char,Func<string,IEnumerable<char>>>{{'l',s=>s.Substring(1)+s[0]},{'r',s=>s[s.Length-1]+s.Substring(0,s.Length-1)},{'u',s=>s.Reverse()},{'f',s=>s.Select(c=>(char)(97-c))}};return o.Aggregate(string.Join("",a.Select(c=>Convert.ToString(c,2).PadLeft(8,'0'))),(r,c)=>new string(f[c](r).ToArray()));}} ``` Formatted: ``` using System; using System.Collections.Generic; using System.Linq; class P { string F(string a, string o) { // define string operations var f = new Dictionary<char, Func<string, IEnumerable<char>>> { {'l', s => s.Substring(1) + s[0]}, {'r', s => s[s.Length - 1] + s.Substring(0, s.Length - 1)}, {'u', s => s.Reverse()}, {'f', s => s.Select(c => (char) (97 - c))} }; // for each operation invoke f[?]; start from converted a return o.Aggregate( // convert each char to binary string, pad left to 8 bytes and join them string.Join("", a.Select(c => Convert.ToString(c, 2).PadLeft(8, '0'))), // invoke f[c] on result of prev operation (r, c) => new string(f[c](r).ToArray()) ); } } ```
45,087
This is based on [xkcd #153](http://xkcd.com/153/). Make a program or named function which takes 2 parameters, each of which is a string or a list or array of bytes or characters. The second parameter will only contain characters drawn from `lrfu` (or the equivalent ASCII bytes). It should be interpreted as a series of instructions to be performed on a bit sequence represented by the first parameter. The processing performed must be equivalent to the following: 1. Convert the first parameter into a single bitstring formed by concatenating the bits of each character (interpreted as one of 7-bit ASCII, an 8-bit extended ASCII, or a standard Unicode encoding). E.g. if the first parameter is `"AB"` then this would be one of `10000011000010` (7-bit), `0100000101000010` (8-bit or UTF-8), `00000000010000010000000001000010`, or `01000001000000000100001000000000` (UTF-16 in the two endiannesses), etc. 2. For each character in the second parameter, in order, execute the corresponding instruction: * `l` rotates the bitstring left one. E.g. `10000011000010` becomes `00000110000101`. * `r` rotates the bitstring right one. E.g. `10000011000010` becomes `01000001100001`. * `f` flips (or inverts) each bit in the bitstring. E.g. `10000011000010` becomes `01111100111101`. * `u` reverses the bitstring. E.g. `10000011000010` becomes `01000011000001`. 3. Convert the bitstring into an ASCII string which uses one character per bit. E.g. `10000011000010` becomes `"10000011000010"`. This is because not all sets of 7/8 bits have a character assigned to them. Example (in Python): ``` >>> f("b", "rfu") 01110011 ``` It turns `"b"` into its 8-bit ASCII binary representation `01100010`, rotates it right (`00110001`), flips each bit (`11001110`), and reverses it (`01110011`). ### Flexibility Other characters may be used instead of the characters `l`, `r`, `f`, and `u`, but they must be clearly documented. ### Scoreboard Thanks to [@Optimizer](http://meta.codegolf.stackexchange.com/users/31414/optimizer) for creating the following code snippet. To use, click "Show code snippet", scroll to the bottom and click "► Run code snippet". ```js var QUESTION_ID = 45087; var answers = [], page = 1;var SCORE_REG = /\d+(?=[^\d&]*(?:&lt;(?:s&gt;[^&]*&lt;\/s&gt;|[^&]+&gt;)[^\d&]*)*$)/;function url(index) {return "http://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=votes&site=codegolf&filter=!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";}function getAnswers() {$.ajax({url: url(page++),method: "get",dataType: "jsonp",crossDomain: true,success: function (data) {answers.push.apply(answers, data.items);if (data.has_more) getAnswers();else process()}});}getAnswers();function shouldHaveHeading(a) {var pass = false;try {pass |= /^(#|&lt;h).*/.test(a.body_markdown);pass |= ["-", "="].indexOf(a.body_markdown.split("\n")[1][0]) > -1;} catch (ex) {}return pass;}function shouldHaveScore(a) {var pass = false;try {pass |= SCORE_REG.test(a.body_markdown.split("\n")[0]);} catch (ex) {}return pass;}function getRelDate(previous) {var current = Date.now();var msPerMinute = 60 * 1000;var msPerHour = msPerMinute * 60;var msPerDay = msPerHour * 24;var msPerMonth = msPerDay * 30;var msPerYear = msPerDay * 365;var elapsed = current - previous;if (elapsed < msPerMinute) {return Math.round(elapsed/1000) + ' seconds ago';}if (elapsed < msPerHour) {return Math.round(elapsed/msPerMinute) + ' minutes ago';}if (elapsed < msPerDay ) {return Math.round(elapsed/msPerHour ) + ' hours ago';}if (elapsed < msPerMonth) {return 'approx. ' + Math.round(elapsed/msPerDay) + ' days ago';}if (elapsed < msPerYear) {return 'approx. ' + Math.round(elapsed/msPerMonth) + ' months ago';}return 'approx. ' + Math.round(elapsed/msPerYear ) + ' years ago';}function process() {answers = answers.filter(shouldHaveHeading);answers = answers.filter(shouldHaveScore);answers.sort(function (a, b) {var aB = +(a.body_markdown.split("\n")[0].match(SCORE_REG) || [Infinity])[0],bB = +(b.body_markdown.split("\n")[0].match(SCORE_REG) || [Infinity])[0];return aB - bB});answers.forEach(function (a) {var answer = $("#answer-template").html();answer = answer.replace("{{BODY}}", a.body).replace("{{NAME}}", a.owner.display_name).replace("{{REP}}", a.owner.reputation).replace("{{VOTES}}", a.score).replace("{{DATE}}", new Date(a.creation_date*1e3).toUTCString()).replace("{{REL_TIME}}", getRelDate(a.creation_date*1e3)).replace("{{POST_LINK}}", a.share_link).replace(/{{USER_LINK}}/g, a.owner.link).replace('{{img}}=""', "src=\"" + a.owner.profile_image + '"');answer = $(answer);if (a.is_accepted) {answer.find(".vote-accepted-on").removeAttr("style");}$("#answers").append(answer);});} ``` ```css body { text-align: left !important} ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id="answers"></div><div id="answer-template" style="display: none"><div class="answer" ><table><tbody><tr><td class="votecell"><div class="vote"><span style="cursor: pointer;" title="Total Votes" itemprop="upvoteCount" class="vote-count-post ">{{VOTES}}</span><span style="display: none" class="vote-accepted-on load-accepted-answer-date" title="The question owner accepted this as the best answer">accepted</span></div></td><td class="answercell"><div class="post-text" itemprop="text">{{BODY}}</div><table class="fw"><tbody><tr><td class="vt"><div class="post-menu"><a href="{{POST_LINK}}" title="short permalink to this answer" class="short-link">share</a></div></td><td class="post-signature" align="right"><div class="user-info "><div class="user-action-time">answered <span title="{{DATE}}" class="relativetime">{{REL_TIME}}</span></div><div class="user-gravatar32"></div><div class="user-details"><br></div></div></td><td class="post-signature" align="right"><div class="user-info user-hover"><div class="user-action-time"></div><div class="user-gravatar32"><a href="{{USER_LINK}}"><div class="gravatar-wrapper-32"><img {{img}} alt="" height="32" width="32"></div></a></div><div class="user-details"><a href="{{USER_LINK}}">{{NAME}}</a><br><span class="reputation-score" title="reputation score " dir="ltr">{{REP}}</span></div></div></td></tr></tbody></table></td></tr></tbody></table></div></div> ```
2015/01/27
[ "https://codegolf.stackexchange.com/questions/45087", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/-1/" ]
CJam, 34 bytes ============== Another approach in CJam. ``` 1l+256b2b1>l_S/,1&@f=_,,@f{W%~}\f= ``` The input text is on the first line and the instructions are on the second line. Instructions: ``` ) Rotate left. ( Rotate right. (space) Flip. ~ Reverse. ```
### C#, 418 bytes ``` using System;using System.Collections.Generic;using System.Linq;class P{string F(string a,string o){var f=new Dictionary<char,Func<string,IEnumerable<char>>>{{'l',s=>s.Substring(1)+s[0]},{'r',s=>s[s.Length-1]+s.Substring(0,s.Length-1)},{'u',s=>s.Reverse()},{'f',s=>s.Select(c=>(char)(97-c))}};return o.Aggregate(string.Join("",a.Select(c=>Convert.ToString(c,2).PadLeft(8,'0'))),(r,c)=>new string(f[c](r).ToArray()));}} ``` Formatted: ``` using System; using System.Collections.Generic; using System.Linq; class P { string F(string a, string o) { // define string operations var f = new Dictionary<char, Func<string, IEnumerable<char>>> { {'l', s => s.Substring(1) + s[0]}, {'r', s => s[s.Length - 1] + s.Substring(0, s.Length - 1)}, {'u', s => s.Reverse()}, {'f', s => s.Select(c => (char) (97 - c))} }; // for each operation invoke f[?]; start from converted a return o.Aggregate( // convert each char to binary string, pad left to 8 bytes and join them string.Join("", a.Select(c => Convert.ToString(c, 2).PadLeft(8, '0'))), // invoke f[c] on result of prev operation (r, c) => new string(f[c](r).ToArray()) ); } } ```
45,087
This is based on [xkcd #153](http://xkcd.com/153/). Make a program or named function which takes 2 parameters, each of which is a string or a list or array of bytes or characters. The second parameter will only contain characters drawn from `lrfu` (or the equivalent ASCII bytes). It should be interpreted as a series of instructions to be performed on a bit sequence represented by the first parameter. The processing performed must be equivalent to the following: 1. Convert the first parameter into a single bitstring formed by concatenating the bits of each character (interpreted as one of 7-bit ASCII, an 8-bit extended ASCII, or a standard Unicode encoding). E.g. if the first parameter is `"AB"` then this would be one of `10000011000010` (7-bit), `0100000101000010` (8-bit or UTF-8), `00000000010000010000000001000010`, or `01000001000000000100001000000000` (UTF-16 in the two endiannesses), etc. 2. For each character in the second parameter, in order, execute the corresponding instruction: * `l` rotates the bitstring left one. E.g. `10000011000010` becomes `00000110000101`. * `r` rotates the bitstring right one. E.g. `10000011000010` becomes `01000001100001`. * `f` flips (or inverts) each bit in the bitstring. E.g. `10000011000010` becomes `01111100111101`. * `u` reverses the bitstring. E.g. `10000011000010` becomes `01000011000001`. 3. Convert the bitstring into an ASCII string which uses one character per bit. E.g. `10000011000010` becomes `"10000011000010"`. This is because not all sets of 7/8 bits have a character assigned to them. Example (in Python): ``` >>> f("b", "rfu") 01110011 ``` It turns `"b"` into its 8-bit ASCII binary representation `01100010`, rotates it right (`00110001`), flips each bit (`11001110`), and reverses it (`01110011`). ### Flexibility Other characters may be used instead of the characters `l`, `r`, `f`, and `u`, but they must be clearly documented. ### Scoreboard Thanks to [@Optimizer](http://meta.codegolf.stackexchange.com/users/31414/optimizer) for creating the following code snippet. To use, click "Show code snippet", scroll to the bottom and click "► Run code snippet". ```js var QUESTION_ID = 45087; var answers = [], page = 1;var SCORE_REG = /\d+(?=[^\d&]*(?:&lt;(?:s&gt;[^&]*&lt;\/s&gt;|[^&]+&gt;)[^\d&]*)*$)/;function url(index) {return "http://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=votes&site=codegolf&filter=!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";}function getAnswers() {$.ajax({url: url(page++),method: "get",dataType: "jsonp",crossDomain: true,success: function (data) {answers.push.apply(answers, data.items);if (data.has_more) getAnswers();else process()}});}getAnswers();function shouldHaveHeading(a) {var pass = false;try {pass |= /^(#|&lt;h).*/.test(a.body_markdown);pass |= ["-", "="].indexOf(a.body_markdown.split("\n")[1][0]) > -1;} catch (ex) {}return pass;}function shouldHaveScore(a) {var pass = false;try {pass |= SCORE_REG.test(a.body_markdown.split("\n")[0]);} catch (ex) {}return pass;}function getRelDate(previous) {var current = Date.now();var msPerMinute = 60 * 1000;var msPerHour = msPerMinute * 60;var msPerDay = msPerHour * 24;var msPerMonth = msPerDay * 30;var msPerYear = msPerDay * 365;var elapsed = current - previous;if (elapsed < msPerMinute) {return Math.round(elapsed/1000) + ' seconds ago';}if (elapsed < msPerHour) {return Math.round(elapsed/msPerMinute) + ' minutes ago';}if (elapsed < msPerDay ) {return Math.round(elapsed/msPerHour ) + ' hours ago';}if (elapsed < msPerMonth) {return 'approx. ' + Math.round(elapsed/msPerDay) + ' days ago';}if (elapsed < msPerYear) {return 'approx. ' + Math.round(elapsed/msPerMonth) + ' months ago';}return 'approx. ' + Math.round(elapsed/msPerYear ) + ' years ago';}function process() {answers = answers.filter(shouldHaveHeading);answers = answers.filter(shouldHaveScore);answers.sort(function (a, b) {var aB = +(a.body_markdown.split("\n")[0].match(SCORE_REG) || [Infinity])[0],bB = +(b.body_markdown.split("\n")[0].match(SCORE_REG) || [Infinity])[0];return aB - bB});answers.forEach(function (a) {var answer = $("#answer-template").html();answer = answer.replace("{{BODY}}", a.body).replace("{{NAME}}", a.owner.display_name).replace("{{REP}}", a.owner.reputation).replace("{{VOTES}}", a.score).replace("{{DATE}}", new Date(a.creation_date*1e3).toUTCString()).replace("{{REL_TIME}}", getRelDate(a.creation_date*1e3)).replace("{{POST_LINK}}", a.share_link).replace(/{{USER_LINK}}/g, a.owner.link).replace('{{img}}=""', "src=\"" + a.owner.profile_image + '"');answer = $(answer);if (a.is_accepted) {answer.find(".vote-accepted-on").removeAttr("style");}$("#answers").append(answer);});} ``` ```css body { text-align: left !important} ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id="answers"></div><div id="answer-template" style="display: none"><div class="answer" ><table><tbody><tr><td class="votecell"><div class="vote"><span style="cursor: pointer;" title="Total Votes" itemprop="upvoteCount" class="vote-count-post ">{{VOTES}}</span><span style="display: none" class="vote-accepted-on load-accepted-answer-date" title="The question owner accepted this as the best answer">accepted</span></div></td><td class="answercell"><div class="post-text" itemprop="text">{{BODY}}</div><table class="fw"><tbody><tr><td class="vt"><div class="post-menu"><a href="{{POST_LINK}}" title="short permalink to this answer" class="short-link">share</a></div></td><td class="post-signature" align="right"><div class="user-info "><div class="user-action-time">answered <span title="{{DATE}}" class="relativetime">{{REL_TIME}}</span></div><div class="user-gravatar32"></div><div class="user-details"><br></div></div></td><td class="post-signature" align="right"><div class="user-info user-hover"><div class="user-action-time"></div><div class="user-gravatar32"><a href="{{USER_LINK}}"><div class="gravatar-wrapper-32"><img {{img}} alt="" height="32" width="32"></div></a></div><div class="user-details"><a href="{{USER_LINK}}">{{NAME}}</a><br><span class="reputation-score" title="reputation score " dir="ltr">{{REP}}</span></div></div></td></tr></tbody></table></td></tr></tbody></table></div></div> ```
2015/01/27
[ "https://codegolf.stackexchange.com/questions/45087", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/-1/" ]
CJam, ~~34~~ 32 bytes ===================== ``` 1l+256b2b1>l{~"11W:mm%!<>">4%~}/ ``` It uses the following characters for instructions: ``` 0: left rotation 1: right rotation 2: reverse 3: flip ``` The input is taking from STDIN with the word on the first line and the instruction string on the second line. [Test it here.](http://cjam.aditsu.net/) Explanation ----------- Getting the bit string is really just a matter of interpreting the character codes as the digits of a base-256 number (and getting its base-2 representation). The tricky thing is that the latter base conversion won't pad the result with 0s on the left. Therefore, I add a leading 1 to the initial input, and then split off that 1 again in the binary representation. As an example, if the input is `ab`, I turn that into an array `[1 'a 'b]`, interpret that as base-256 (characters are automatically converted to character codes), which is `90466` and the to base-2, which is `[1 0 1 1 0 0 0 0 1 0 1 1 0 0 0 1 0]`. Now if I just remove that leading `1` I've got the bitstream I'm looking for. That's what this part of the code does: ``` 1l+256b2b1> ``` Now I read the list of instructions and execute a block for each character in the instruction string: ``` l{...}/ ``` The first thing to do is to evaluate the character and actual integers`0`, `1`, `2` or `3`. Now the real golfy magic... depending on the instruction I want to run a short piece of code that implements the operation: ``` Integer: Code Operation 0 1m< "Left rotation"; 1 1m> "Right rotation"; 2 W% "Reverse"; 3 :! "Flip each bit"; ``` I could store these in an array of blocks and choose the right block to run, but encoding them in a string is actually shorter: ``` "11W:mm%!<>">4%~ ``` First, I use the integer associate with the instruction to slice off the beginning of the string. So for left rotation, the string is unchanged, for right rotation the first character is discarded and so on. Then I select every fourth character from the string, starting from the first, with `4%`. Notice how the four code snippets are distributed throughout the string. Finally I just evaluate the string as code with `~`. The bit string is printed automatically at the end of the program.
Python 2 - 179 ============== ``` b="".join([bin(ord(i))[2:]for i in input()]) for i in input():b=b[-1]+b[:-1]if i=="r"else b[1:]+b[0]if i=="l"else[str("10".find(j))for j in b]if i=="f"else b[::-1] print"".join(b) ```
45,087
This is based on [xkcd #153](http://xkcd.com/153/). Make a program or named function which takes 2 parameters, each of which is a string or a list or array of bytes or characters. The second parameter will only contain characters drawn from `lrfu` (or the equivalent ASCII bytes). It should be interpreted as a series of instructions to be performed on a bit sequence represented by the first parameter. The processing performed must be equivalent to the following: 1. Convert the first parameter into a single bitstring formed by concatenating the bits of each character (interpreted as one of 7-bit ASCII, an 8-bit extended ASCII, or a standard Unicode encoding). E.g. if the first parameter is `"AB"` then this would be one of `10000011000010` (7-bit), `0100000101000010` (8-bit or UTF-8), `00000000010000010000000001000010`, or `01000001000000000100001000000000` (UTF-16 in the two endiannesses), etc. 2. For each character in the second parameter, in order, execute the corresponding instruction: * `l` rotates the bitstring left one. E.g. `10000011000010` becomes `00000110000101`. * `r` rotates the bitstring right one. E.g. `10000011000010` becomes `01000001100001`. * `f` flips (or inverts) each bit in the bitstring. E.g. `10000011000010` becomes `01111100111101`. * `u` reverses the bitstring. E.g. `10000011000010` becomes `01000011000001`. 3. Convert the bitstring into an ASCII string which uses one character per bit. E.g. `10000011000010` becomes `"10000011000010"`. This is because not all sets of 7/8 bits have a character assigned to them. Example (in Python): ``` >>> f("b", "rfu") 01110011 ``` It turns `"b"` into its 8-bit ASCII binary representation `01100010`, rotates it right (`00110001`), flips each bit (`11001110`), and reverses it (`01110011`). ### Flexibility Other characters may be used instead of the characters `l`, `r`, `f`, and `u`, but they must be clearly documented. ### Scoreboard Thanks to [@Optimizer](http://meta.codegolf.stackexchange.com/users/31414/optimizer) for creating the following code snippet. To use, click "Show code snippet", scroll to the bottom and click "► Run code snippet". ```js var QUESTION_ID = 45087; var answers = [], page = 1;var SCORE_REG = /\d+(?=[^\d&]*(?:&lt;(?:s&gt;[^&]*&lt;\/s&gt;|[^&]+&gt;)[^\d&]*)*$)/;function url(index) {return "http://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=votes&site=codegolf&filter=!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";}function getAnswers() {$.ajax({url: url(page++),method: "get",dataType: "jsonp",crossDomain: true,success: function (data) {answers.push.apply(answers, data.items);if (data.has_more) getAnswers();else process()}});}getAnswers();function shouldHaveHeading(a) {var pass = false;try {pass |= /^(#|&lt;h).*/.test(a.body_markdown);pass |= ["-", "="].indexOf(a.body_markdown.split("\n")[1][0]) > -1;} catch (ex) {}return pass;}function shouldHaveScore(a) {var pass = false;try {pass |= SCORE_REG.test(a.body_markdown.split("\n")[0]);} catch (ex) {}return pass;}function getRelDate(previous) {var current = Date.now();var msPerMinute = 60 * 1000;var msPerHour = msPerMinute * 60;var msPerDay = msPerHour * 24;var msPerMonth = msPerDay * 30;var msPerYear = msPerDay * 365;var elapsed = current - previous;if (elapsed < msPerMinute) {return Math.round(elapsed/1000) + ' seconds ago';}if (elapsed < msPerHour) {return Math.round(elapsed/msPerMinute) + ' minutes ago';}if (elapsed < msPerDay ) {return Math.round(elapsed/msPerHour ) + ' hours ago';}if (elapsed < msPerMonth) {return 'approx. ' + Math.round(elapsed/msPerDay) + ' days ago';}if (elapsed < msPerYear) {return 'approx. ' + Math.round(elapsed/msPerMonth) + ' months ago';}return 'approx. ' + Math.round(elapsed/msPerYear ) + ' years ago';}function process() {answers = answers.filter(shouldHaveHeading);answers = answers.filter(shouldHaveScore);answers.sort(function (a, b) {var aB = +(a.body_markdown.split("\n")[0].match(SCORE_REG) || [Infinity])[0],bB = +(b.body_markdown.split("\n")[0].match(SCORE_REG) || [Infinity])[0];return aB - bB});answers.forEach(function (a) {var answer = $("#answer-template").html();answer = answer.replace("{{BODY}}", a.body).replace("{{NAME}}", a.owner.display_name).replace("{{REP}}", a.owner.reputation).replace("{{VOTES}}", a.score).replace("{{DATE}}", new Date(a.creation_date*1e3).toUTCString()).replace("{{REL_TIME}}", getRelDate(a.creation_date*1e3)).replace("{{POST_LINK}}", a.share_link).replace(/{{USER_LINK}}/g, a.owner.link).replace('{{img}}=""', "src=\"" + a.owner.profile_image + '"');answer = $(answer);if (a.is_accepted) {answer.find(".vote-accepted-on").removeAttr("style");}$("#answers").append(answer);});} ``` ```css body { text-align: left !important} ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id="answers"></div><div id="answer-template" style="display: none"><div class="answer" ><table><tbody><tr><td class="votecell"><div class="vote"><span style="cursor: pointer;" title="Total Votes" itemprop="upvoteCount" class="vote-count-post ">{{VOTES}}</span><span style="display: none" class="vote-accepted-on load-accepted-answer-date" title="The question owner accepted this as the best answer">accepted</span></div></td><td class="answercell"><div class="post-text" itemprop="text">{{BODY}}</div><table class="fw"><tbody><tr><td class="vt"><div class="post-menu"><a href="{{POST_LINK}}" title="short permalink to this answer" class="short-link">share</a></div></td><td class="post-signature" align="right"><div class="user-info "><div class="user-action-time">answered <span title="{{DATE}}" class="relativetime">{{REL_TIME}}</span></div><div class="user-gravatar32"></div><div class="user-details"><br></div></div></td><td class="post-signature" align="right"><div class="user-info user-hover"><div class="user-action-time"></div><div class="user-gravatar32"><a href="{{USER_LINK}}"><div class="gravatar-wrapper-32"><img {{img}} alt="" height="32" width="32"></div></a></div><div class="user-details"><a href="{{USER_LINK}}">{{NAME}}</a><br><span class="reputation-score" title="reputation score " dir="ltr">{{REP}}</span></div></div></td></tr></tbody></table></td></tr></tbody></table></div></div> ```
2015/01/27
[ "https://codegolf.stackexchange.com/questions/45087", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/-1/" ]
Pyth 33 ------- ``` jku@[+eGPG+tGhG_Gms!dG)sHwsmjCk2z ``` Uses: ``` 0 : rotate right 1 : rotate left 2 : reverse order 3 : flip values ``` [Pyth github](https://github.com/isaacg1/pyth) [Try it online here.](https://pyth.herokuapp.com/) This is a program that takes the string as it's first argument and the string of commands as the second argument. In the online version, you should give the strings separated by a newline, like so: ``` AbC 0321 ``` Explanation: ``` : z=input() (implicit) jk : join("", ...) u@[ )sHw : reduce(select from [...] the value at int(H), input(), ...) +eGPG : [ G[-1] + G[:1], +tGhG : G[1:] + G[1], _G : G[::-1], ms!dG : map(lambda d: int(not(d)), G) ] smjCk2z : first arg = sum(map(lambda k:convert_to_base(ord(k),2),z) ``` Something I couldn't quite squeeze in: Pyth's `reduce` automatically uses `G` for the previous value, and `H` for the next value.
Matlab (166 bytes) ================== This uses letters `abcd` instead of `lrfu` respectively. ``` function D=f(B,C) D=dec2bin(B,8)'; D=D(:); g=@circshift; for c=C switch c-97 case 0 D=g(D,-1); case 1 D=g(D,1); case 2 D=char(97-D); case 3 D=flipud(D); end end D=D'; ``` Some tricks used here to save space: * Using `abcd` letters lets me subtract `97` once, and then the letters become `0`, `1`, `2`, `3`. This saves space in the `switch`-`case` clauses. * Defining `circshift` as a one-letter anonymous function also saves space, as it's used twice. * Since `D` consists of `'0'` and `'1'` characters (ASCII codes `48` and `49`), the statement `D=char(97-D)` corresponds to inversion between `'0'` and `'1'` values. Note that this `97` has nothing to do with that referred to above. * Complex-conjugate transpose `'` is used instead of transpose `.'`.
45,087
This is based on [xkcd #153](http://xkcd.com/153/). Make a program or named function which takes 2 parameters, each of which is a string or a list or array of bytes or characters. The second parameter will only contain characters drawn from `lrfu` (or the equivalent ASCII bytes). It should be interpreted as a series of instructions to be performed on a bit sequence represented by the first parameter. The processing performed must be equivalent to the following: 1. Convert the first parameter into a single bitstring formed by concatenating the bits of each character (interpreted as one of 7-bit ASCII, an 8-bit extended ASCII, or a standard Unicode encoding). E.g. if the first parameter is `"AB"` then this would be one of `10000011000010` (7-bit), `0100000101000010` (8-bit or UTF-8), `00000000010000010000000001000010`, or `01000001000000000100001000000000` (UTF-16 in the two endiannesses), etc. 2. For each character in the second parameter, in order, execute the corresponding instruction: * `l` rotates the bitstring left one. E.g. `10000011000010` becomes `00000110000101`. * `r` rotates the bitstring right one. E.g. `10000011000010` becomes `01000001100001`. * `f` flips (or inverts) each bit in the bitstring. E.g. `10000011000010` becomes `01111100111101`. * `u` reverses the bitstring. E.g. `10000011000010` becomes `01000011000001`. 3. Convert the bitstring into an ASCII string which uses one character per bit. E.g. `10000011000010` becomes `"10000011000010"`. This is because not all sets of 7/8 bits have a character assigned to them. Example (in Python): ``` >>> f("b", "rfu") 01110011 ``` It turns `"b"` into its 8-bit ASCII binary representation `01100010`, rotates it right (`00110001`), flips each bit (`11001110`), and reverses it (`01110011`). ### Flexibility Other characters may be used instead of the characters `l`, `r`, `f`, and `u`, but they must be clearly documented. ### Scoreboard Thanks to [@Optimizer](http://meta.codegolf.stackexchange.com/users/31414/optimizer) for creating the following code snippet. To use, click "Show code snippet", scroll to the bottom and click "► Run code snippet". ```js var QUESTION_ID = 45087; var answers = [], page = 1;var SCORE_REG = /\d+(?=[^\d&]*(?:&lt;(?:s&gt;[^&]*&lt;\/s&gt;|[^&]+&gt;)[^\d&]*)*$)/;function url(index) {return "http://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=votes&site=codegolf&filter=!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";}function getAnswers() {$.ajax({url: url(page++),method: "get",dataType: "jsonp",crossDomain: true,success: function (data) {answers.push.apply(answers, data.items);if (data.has_more) getAnswers();else process()}});}getAnswers();function shouldHaveHeading(a) {var pass = false;try {pass |= /^(#|&lt;h).*/.test(a.body_markdown);pass |= ["-", "="].indexOf(a.body_markdown.split("\n")[1][0]) > -1;} catch (ex) {}return pass;}function shouldHaveScore(a) {var pass = false;try {pass |= SCORE_REG.test(a.body_markdown.split("\n")[0]);} catch (ex) {}return pass;}function getRelDate(previous) {var current = Date.now();var msPerMinute = 60 * 1000;var msPerHour = msPerMinute * 60;var msPerDay = msPerHour * 24;var msPerMonth = msPerDay * 30;var msPerYear = msPerDay * 365;var elapsed = current - previous;if (elapsed < msPerMinute) {return Math.round(elapsed/1000) + ' seconds ago';}if (elapsed < msPerHour) {return Math.round(elapsed/msPerMinute) + ' minutes ago';}if (elapsed < msPerDay ) {return Math.round(elapsed/msPerHour ) + ' hours ago';}if (elapsed < msPerMonth) {return 'approx. ' + Math.round(elapsed/msPerDay) + ' days ago';}if (elapsed < msPerYear) {return 'approx. ' + Math.round(elapsed/msPerMonth) + ' months ago';}return 'approx. ' + Math.round(elapsed/msPerYear ) + ' years ago';}function process() {answers = answers.filter(shouldHaveHeading);answers = answers.filter(shouldHaveScore);answers.sort(function (a, b) {var aB = +(a.body_markdown.split("\n")[0].match(SCORE_REG) || [Infinity])[0],bB = +(b.body_markdown.split("\n")[0].match(SCORE_REG) || [Infinity])[0];return aB - bB});answers.forEach(function (a) {var answer = $("#answer-template").html();answer = answer.replace("{{BODY}}", a.body).replace("{{NAME}}", a.owner.display_name).replace("{{REP}}", a.owner.reputation).replace("{{VOTES}}", a.score).replace("{{DATE}}", new Date(a.creation_date*1e3).toUTCString()).replace("{{REL_TIME}}", getRelDate(a.creation_date*1e3)).replace("{{POST_LINK}}", a.share_link).replace(/{{USER_LINK}}/g, a.owner.link).replace('{{img}}=""', "src=\"" + a.owner.profile_image + '"');answer = $(answer);if (a.is_accepted) {answer.find(".vote-accepted-on").removeAttr("style");}$("#answers").append(answer);});} ``` ```css body { text-align: left !important} ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id="answers"></div><div id="answer-template" style="display: none"><div class="answer" ><table><tbody><tr><td class="votecell"><div class="vote"><span style="cursor: pointer;" title="Total Votes" itemprop="upvoteCount" class="vote-count-post ">{{VOTES}}</span><span style="display: none" class="vote-accepted-on load-accepted-answer-date" title="The question owner accepted this as the best answer">accepted</span></div></td><td class="answercell"><div class="post-text" itemprop="text">{{BODY}}</div><table class="fw"><tbody><tr><td class="vt"><div class="post-menu"><a href="{{POST_LINK}}" title="short permalink to this answer" class="short-link">share</a></div></td><td class="post-signature" align="right"><div class="user-info "><div class="user-action-time">answered <span title="{{DATE}}" class="relativetime">{{REL_TIME}}</span></div><div class="user-gravatar32"></div><div class="user-details"><br></div></div></td><td class="post-signature" align="right"><div class="user-info user-hover"><div class="user-action-time"></div><div class="user-gravatar32"><a href="{{USER_LINK}}"><div class="gravatar-wrapper-32"><img {{img}} alt="" height="32" width="32"></div></a></div><div class="user-details"><a href="{{USER_LINK}}">{{NAME}}</a><br><span class="reputation-score" title="reputation score " dir="ltr">{{REP}}</span></div></div></td></tr></tbody></table></td></tr></tbody></table></div></div> ```
2015/01/27
[ "https://codegolf.stackexchange.com/questions/45087", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/-1/" ]
CJam, ~~34~~ 32 bytes ===================== ``` 1l+256b2b1>l{~"11W:mm%!<>">4%~}/ ``` It uses the following characters for instructions: ``` 0: left rotation 1: right rotation 2: reverse 3: flip ``` The input is taking from STDIN with the word on the first line and the instruction string on the second line. [Test it here.](http://cjam.aditsu.net/) Explanation ----------- Getting the bit string is really just a matter of interpreting the character codes as the digits of a base-256 number (and getting its base-2 representation). The tricky thing is that the latter base conversion won't pad the result with 0s on the left. Therefore, I add a leading 1 to the initial input, and then split off that 1 again in the binary representation. As an example, if the input is `ab`, I turn that into an array `[1 'a 'b]`, interpret that as base-256 (characters are automatically converted to character codes), which is `90466` and the to base-2, which is `[1 0 1 1 0 0 0 0 1 0 1 1 0 0 0 1 0]`. Now if I just remove that leading `1` I've got the bitstream I'm looking for. That's what this part of the code does: ``` 1l+256b2b1> ``` Now I read the list of instructions and execute a block for each character in the instruction string: ``` l{...}/ ``` The first thing to do is to evaluate the character and actual integers`0`, `1`, `2` or `3`. Now the real golfy magic... depending on the instruction I want to run a short piece of code that implements the operation: ``` Integer: Code Operation 0 1m< "Left rotation"; 1 1m> "Right rotation"; 2 W% "Reverse"; 3 :! "Flip each bit"; ``` I could store these in an array of blocks and choose the right block to run, but encoding them in a string is actually shorter: ``` "11W:mm%!<>">4%~ ``` First, I use the integer associate with the instruction to slice off the beginning of the string. So for left rotation, the string is unchanged, for right rotation the first character is discarded and so on. Then I select every fourth character from the string, starting from the first, with `4%`. Notice how the four code snippets are distributed throughout the string. Finally I just evaluate the string as code with `~`. The bit string is printed automatically at the end of the program.
Scala - 192 =========== ``` def f(i:String,l:String)=(i.flatMap(_.toBinaryString).map(_.toInt-48)/:l){ case(b,'l')⇒b.tail:+b.head case(b,'r')⇒b.last+:b.init case(b,'f')⇒b.map(1-_) case(b,'u')⇒b.reverse}.mkString ```
45,087
This is based on [xkcd #153](http://xkcd.com/153/). Make a program or named function which takes 2 parameters, each of which is a string or a list or array of bytes or characters. The second parameter will only contain characters drawn from `lrfu` (or the equivalent ASCII bytes). It should be interpreted as a series of instructions to be performed on a bit sequence represented by the first parameter. The processing performed must be equivalent to the following: 1. Convert the first parameter into a single bitstring formed by concatenating the bits of each character (interpreted as one of 7-bit ASCII, an 8-bit extended ASCII, or a standard Unicode encoding). E.g. if the first parameter is `"AB"` then this would be one of `10000011000010` (7-bit), `0100000101000010` (8-bit or UTF-8), `00000000010000010000000001000010`, or `01000001000000000100001000000000` (UTF-16 in the two endiannesses), etc. 2. For each character in the second parameter, in order, execute the corresponding instruction: * `l` rotates the bitstring left one. E.g. `10000011000010` becomes `00000110000101`. * `r` rotates the bitstring right one. E.g. `10000011000010` becomes `01000001100001`. * `f` flips (or inverts) each bit in the bitstring. E.g. `10000011000010` becomes `01111100111101`. * `u` reverses the bitstring. E.g. `10000011000010` becomes `01000011000001`. 3. Convert the bitstring into an ASCII string which uses one character per bit. E.g. `10000011000010` becomes `"10000011000010"`. This is because not all sets of 7/8 bits have a character assigned to them. Example (in Python): ``` >>> f("b", "rfu") 01110011 ``` It turns `"b"` into its 8-bit ASCII binary representation `01100010`, rotates it right (`00110001`), flips each bit (`11001110`), and reverses it (`01110011`). ### Flexibility Other characters may be used instead of the characters `l`, `r`, `f`, and `u`, but they must be clearly documented. ### Scoreboard Thanks to [@Optimizer](http://meta.codegolf.stackexchange.com/users/31414/optimizer) for creating the following code snippet. To use, click "Show code snippet", scroll to the bottom and click "► Run code snippet". ```js var QUESTION_ID = 45087; var answers = [], page = 1;var SCORE_REG = /\d+(?=[^\d&]*(?:&lt;(?:s&gt;[^&]*&lt;\/s&gt;|[^&]+&gt;)[^\d&]*)*$)/;function url(index) {return "http://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=votes&site=codegolf&filter=!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";}function getAnswers() {$.ajax({url: url(page++),method: "get",dataType: "jsonp",crossDomain: true,success: function (data) {answers.push.apply(answers, data.items);if (data.has_more) getAnswers();else process()}});}getAnswers();function shouldHaveHeading(a) {var pass = false;try {pass |= /^(#|&lt;h).*/.test(a.body_markdown);pass |= ["-", "="].indexOf(a.body_markdown.split("\n")[1][0]) > -1;} catch (ex) {}return pass;}function shouldHaveScore(a) {var pass = false;try {pass |= SCORE_REG.test(a.body_markdown.split("\n")[0]);} catch (ex) {}return pass;}function getRelDate(previous) {var current = Date.now();var msPerMinute = 60 * 1000;var msPerHour = msPerMinute * 60;var msPerDay = msPerHour * 24;var msPerMonth = msPerDay * 30;var msPerYear = msPerDay * 365;var elapsed = current - previous;if (elapsed < msPerMinute) {return Math.round(elapsed/1000) + ' seconds ago';}if (elapsed < msPerHour) {return Math.round(elapsed/msPerMinute) + ' minutes ago';}if (elapsed < msPerDay ) {return Math.round(elapsed/msPerHour ) + ' hours ago';}if (elapsed < msPerMonth) {return 'approx. ' + Math.round(elapsed/msPerDay) + ' days ago';}if (elapsed < msPerYear) {return 'approx. ' + Math.round(elapsed/msPerMonth) + ' months ago';}return 'approx. ' + Math.round(elapsed/msPerYear ) + ' years ago';}function process() {answers = answers.filter(shouldHaveHeading);answers = answers.filter(shouldHaveScore);answers.sort(function (a, b) {var aB = +(a.body_markdown.split("\n")[0].match(SCORE_REG) || [Infinity])[0],bB = +(b.body_markdown.split("\n")[0].match(SCORE_REG) || [Infinity])[0];return aB - bB});answers.forEach(function (a) {var answer = $("#answer-template").html();answer = answer.replace("{{BODY}}", a.body).replace("{{NAME}}", a.owner.display_name).replace("{{REP}}", a.owner.reputation).replace("{{VOTES}}", a.score).replace("{{DATE}}", new Date(a.creation_date*1e3).toUTCString()).replace("{{REL_TIME}}", getRelDate(a.creation_date*1e3)).replace("{{POST_LINK}}", a.share_link).replace(/{{USER_LINK}}/g, a.owner.link).replace('{{img}}=""', "src=\"" + a.owner.profile_image + '"');answer = $(answer);if (a.is_accepted) {answer.find(".vote-accepted-on").removeAttr("style");}$("#answers").append(answer);});} ``` ```css body { text-align: left !important} ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id="answers"></div><div id="answer-template" style="display: none"><div class="answer" ><table><tbody><tr><td class="votecell"><div class="vote"><span style="cursor: pointer;" title="Total Votes" itemprop="upvoteCount" class="vote-count-post ">{{VOTES}}</span><span style="display: none" class="vote-accepted-on load-accepted-answer-date" title="The question owner accepted this as the best answer">accepted</span></div></td><td class="answercell"><div class="post-text" itemprop="text">{{BODY}}</div><table class="fw"><tbody><tr><td class="vt"><div class="post-menu"><a href="{{POST_LINK}}" title="short permalink to this answer" class="short-link">share</a></div></td><td class="post-signature" align="right"><div class="user-info "><div class="user-action-time">answered <span title="{{DATE}}" class="relativetime">{{REL_TIME}}</span></div><div class="user-gravatar32"></div><div class="user-details"><br></div></div></td><td class="post-signature" align="right"><div class="user-info user-hover"><div class="user-action-time"></div><div class="user-gravatar32"><a href="{{USER_LINK}}"><div class="gravatar-wrapper-32"><img {{img}} alt="" height="32" width="32"></div></a></div><div class="user-details"><a href="{{USER_LINK}}">{{NAME}}</a><br><span class="reputation-score" title="reputation score " dir="ltr">{{REP}}</span></div></div></td></tr></tbody></table></td></tr></tbody></table></div></div> ```
2015/01/27
[ "https://codegolf.stackexchange.com/questions/45087", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/-1/" ]
Pyth 33 ------- ``` jku@[+eGPG+tGhG_Gms!dG)sHwsmjCk2z ``` Uses: ``` 0 : rotate right 1 : rotate left 2 : reverse order 3 : flip values ``` [Pyth github](https://github.com/isaacg1/pyth) [Try it online here.](https://pyth.herokuapp.com/) This is a program that takes the string as it's first argument and the string of commands as the second argument. In the online version, you should give the strings separated by a newline, like so: ``` AbC 0321 ``` Explanation: ``` : z=input() (implicit) jk : join("", ...) u@[ )sHw : reduce(select from [...] the value at int(H), input(), ...) +eGPG : [ G[-1] + G[:1], +tGhG : G[1:] + G[1], _G : G[::-1], ms!dG : map(lambda d: int(not(d)), G) ] smjCk2z : first arg = sum(map(lambda k:convert_to_base(ord(k),2),z) ``` Something I couldn't quite squeeze in: Pyth's `reduce` automatically uses `G` for the previous value, and `H` for the next value.
Ruby, 151 ========= ```ruby f=->i,s{s.chars.inject(i.unpack("B*")[0]){|a,c| a.reverse! if c==?u a.tr!"01","10" if c==?f a<<a.slice!(1..-1) if c==?l a<<a.slice!(0..-2) if c==?r a}} ``` Fairly straightforward. Loops trough the characters in `s` and performs an action for any of them.
45,087
This is based on [xkcd #153](http://xkcd.com/153/). Make a program or named function which takes 2 parameters, each of which is a string or a list or array of bytes or characters. The second parameter will only contain characters drawn from `lrfu` (or the equivalent ASCII bytes). It should be interpreted as a series of instructions to be performed on a bit sequence represented by the first parameter. The processing performed must be equivalent to the following: 1. Convert the first parameter into a single bitstring formed by concatenating the bits of each character (interpreted as one of 7-bit ASCII, an 8-bit extended ASCII, or a standard Unicode encoding). E.g. if the first parameter is `"AB"` then this would be one of `10000011000010` (7-bit), `0100000101000010` (8-bit or UTF-8), `00000000010000010000000001000010`, or `01000001000000000100001000000000` (UTF-16 in the two endiannesses), etc. 2. For each character in the second parameter, in order, execute the corresponding instruction: * `l` rotates the bitstring left one. E.g. `10000011000010` becomes `00000110000101`. * `r` rotates the bitstring right one. E.g. `10000011000010` becomes `01000001100001`. * `f` flips (or inverts) each bit in the bitstring. E.g. `10000011000010` becomes `01111100111101`. * `u` reverses the bitstring. E.g. `10000011000010` becomes `01000011000001`. 3. Convert the bitstring into an ASCII string which uses one character per bit. E.g. `10000011000010` becomes `"10000011000010"`. This is because not all sets of 7/8 bits have a character assigned to them. Example (in Python): ``` >>> f("b", "rfu") 01110011 ``` It turns `"b"` into its 8-bit ASCII binary representation `01100010`, rotates it right (`00110001`), flips each bit (`11001110`), and reverses it (`01110011`). ### Flexibility Other characters may be used instead of the characters `l`, `r`, `f`, and `u`, but they must be clearly documented. ### Scoreboard Thanks to [@Optimizer](http://meta.codegolf.stackexchange.com/users/31414/optimizer) for creating the following code snippet. To use, click "Show code snippet", scroll to the bottom and click "► Run code snippet". ```js var QUESTION_ID = 45087; var answers = [], page = 1;var SCORE_REG = /\d+(?=[^\d&]*(?:&lt;(?:s&gt;[^&]*&lt;\/s&gt;|[^&]+&gt;)[^\d&]*)*$)/;function url(index) {return "http://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=votes&site=codegolf&filter=!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";}function getAnswers() {$.ajax({url: url(page++),method: "get",dataType: "jsonp",crossDomain: true,success: function (data) {answers.push.apply(answers, data.items);if (data.has_more) getAnswers();else process()}});}getAnswers();function shouldHaveHeading(a) {var pass = false;try {pass |= /^(#|&lt;h).*/.test(a.body_markdown);pass |= ["-", "="].indexOf(a.body_markdown.split("\n")[1][0]) > -1;} catch (ex) {}return pass;}function shouldHaveScore(a) {var pass = false;try {pass |= SCORE_REG.test(a.body_markdown.split("\n")[0]);} catch (ex) {}return pass;}function getRelDate(previous) {var current = Date.now();var msPerMinute = 60 * 1000;var msPerHour = msPerMinute * 60;var msPerDay = msPerHour * 24;var msPerMonth = msPerDay * 30;var msPerYear = msPerDay * 365;var elapsed = current - previous;if (elapsed < msPerMinute) {return Math.round(elapsed/1000) + ' seconds ago';}if (elapsed < msPerHour) {return Math.round(elapsed/msPerMinute) + ' minutes ago';}if (elapsed < msPerDay ) {return Math.round(elapsed/msPerHour ) + ' hours ago';}if (elapsed < msPerMonth) {return 'approx. ' + Math.round(elapsed/msPerDay) + ' days ago';}if (elapsed < msPerYear) {return 'approx. ' + Math.round(elapsed/msPerMonth) + ' months ago';}return 'approx. ' + Math.round(elapsed/msPerYear ) + ' years ago';}function process() {answers = answers.filter(shouldHaveHeading);answers = answers.filter(shouldHaveScore);answers.sort(function (a, b) {var aB = +(a.body_markdown.split("\n")[0].match(SCORE_REG) || [Infinity])[0],bB = +(b.body_markdown.split("\n")[0].match(SCORE_REG) || [Infinity])[0];return aB - bB});answers.forEach(function (a) {var answer = $("#answer-template").html();answer = answer.replace("{{BODY}}", a.body).replace("{{NAME}}", a.owner.display_name).replace("{{REP}}", a.owner.reputation).replace("{{VOTES}}", a.score).replace("{{DATE}}", new Date(a.creation_date*1e3).toUTCString()).replace("{{REL_TIME}}", getRelDate(a.creation_date*1e3)).replace("{{POST_LINK}}", a.share_link).replace(/{{USER_LINK}}/g, a.owner.link).replace('{{img}}=""', "src=\"" + a.owner.profile_image + '"');answer = $(answer);if (a.is_accepted) {answer.find(".vote-accepted-on").removeAttr("style");}$("#answers").append(answer);});} ``` ```css body { text-align: left !important} ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id="answers"></div><div id="answer-template" style="display: none"><div class="answer" ><table><tbody><tr><td class="votecell"><div class="vote"><span style="cursor: pointer;" title="Total Votes" itemprop="upvoteCount" class="vote-count-post ">{{VOTES}}</span><span style="display: none" class="vote-accepted-on load-accepted-answer-date" title="The question owner accepted this as the best answer">accepted</span></div></td><td class="answercell"><div class="post-text" itemprop="text">{{BODY}}</div><table class="fw"><tbody><tr><td class="vt"><div class="post-menu"><a href="{{POST_LINK}}" title="short permalink to this answer" class="short-link">share</a></div></td><td class="post-signature" align="right"><div class="user-info "><div class="user-action-time">answered <span title="{{DATE}}" class="relativetime">{{REL_TIME}}</span></div><div class="user-gravatar32"></div><div class="user-details"><br></div></div></td><td class="post-signature" align="right"><div class="user-info user-hover"><div class="user-action-time"></div><div class="user-gravatar32"><a href="{{USER_LINK}}"><div class="gravatar-wrapper-32"><img {{img}} alt="" height="32" width="32"></div></a></div><div class="user-details"><a href="{{USER_LINK}}">{{NAME}}</a><br><span class="reputation-score" title="reputation score " dir="ltr">{{REP}}</span></div></div></td></tr></tbody></table></td></tr></tbody></table></div></div> ```
2015/01/27
[ "https://codegolf.stackexchange.com/questions/45087", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/-1/" ]
Pyth 33 ------- ``` jku@[+eGPG+tGhG_Gms!dG)sHwsmjCk2z ``` Uses: ``` 0 : rotate right 1 : rotate left 2 : reverse order 3 : flip values ``` [Pyth github](https://github.com/isaacg1/pyth) [Try it online here.](https://pyth.herokuapp.com/) This is a program that takes the string as it's first argument and the string of commands as the second argument. In the online version, you should give the strings separated by a newline, like so: ``` AbC 0321 ``` Explanation: ``` : z=input() (implicit) jk : join("", ...) u@[ )sHw : reduce(select from [...] the value at int(H), input(), ...) +eGPG : [ G[-1] + G[:1], +tGhG : G[1:] + G[1], _G : G[::-1], ms!dG : map(lambda d: int(not(d)), G) ] smjCk2z : first arg = sum(map(lambda k:convert_to_base(ord(k),2),z) ``` Something I couldn't quite squeeze in: Pyth's `reduce` automatically uses `G` for the previous value, and `H` for the next value.
### C#, 418 bytes ``` using System;using System.Collections.Generic;using System.Linq;class P{string F(string a,string o){var f=new Dictionary<char,Func<string,IEnumerable<char>>>{{'l',s=>s.Substring(1)+s[0]},{'r',s=>s[s.Length-1]+s.Substring(0,s.Length-1)},{'u',s=>s.Reverse()},{'f',s=>s.Select(c=>(char)(97-c))}};return o.Aggregate(string.Join("",a.Select(c=>Convert.ToString(c,2).PadLeft(8,'0'))),(r,c)=>new string(f[c](r).ToArray()));}} ``` Formatted: ``` using System; using System.Collections.Generic; using System.Linq; class P { string F(string a, string o) { // define string operations var f = new Dictionary<char, Func<string, IEnumerable<char>>> { {'l', s => s.Substring(1) + s[0]}, {'r', s => s[s.Length - 1] + s.Substring(0, s.Length - 1)}, {'u', s => s.Reverse()}, {'f', s => s.Select(c => (char) (97 - c))} }; // for each operation invoke f[?]; start from converted a return o.Aggregate( // convert each char to binary string, pad left to 8 bytes and join them string.Join("", a.Select(c => Convert.ToString(c, 2).PadLeft(8, '0'))), // invoke f[c] on result of prev operation (r, c) => new string(f[c](r).ToArray()) ); } } ```
38,401,671
I have this part of code (everything is in background.js), which basically executes javascript in pages based on page's URL. It should work on toolbar button click, and Ctrl + Q command. I assign it to button click like this, and it works: ``` chrome.browserAction.onClicked.addListener(function(tab) { browser.tabs.query( {active:true}, function(tabs) { var tab = tabs[0]; if(tab.url.indexOf("app.fillz.com/orders/edit") != -1){ chrome.tabs.executeScript({ file: "fillz.js" }); } else if(tab.url.indexOf("amazon") != -1 && tab.url.indexOf("buy/addressselect/handlers/display.html") != -1){ chrome.tabs.executeScript({ file: "amazon.js" }); } } ); }); ``` Problem is when I try to assign that same code to the onCommand event, like this: ``` chrome.commands.onCommand.addListener(function(command) { if (command == "fills2amazonCopyAndPaste") { browser.tabs.query( {active:true}, function(tabs) { var tab = tabs[0]; if(tab.url.indexOf("app.fillz.com/orders/edit") != -1){ console.log("FILLZ"); chrome.tabs.executeScript({ file: "fillz.js" }); } else if(tab.url.indexOf("amazon") != -1 && tab.url.indexOf("buy/addressselect/handlers/display.html") != -1){ console.log("AMAZON"); chrome.tabs.executeScript({ file: "amazon.js" }); } } ); } }); ``` Command is recognized, also the url of currently active tab, I checked it with those two console.log() commands in code above, but scripts don't get executed when I try to do it with command. In Browser Console, there is only this error: ``` Unchecked lastError value: Error: No matching window ``` originating from: //gre/modules/ExtensionUtils.jsm What could be the problem, I know my manifest.json file is alright as command gets recognized, but it simply won't execute javascript...
2016/07/15
[ "https://Stackoverflow.com/questions/38401671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2558764/" ]
I found out the problem, it was the missing "all\_urls" permission. Apparently "tabs" and "activeTab" permissions weren't enough.
The error you are getting is what is produced when you attempt to inject into a tab for which you do not have permission to inject. This could be a normal tab, if you do not have appropriate `permissions` set in your *manifest.json*. More commonly it is that you are attempting to inject into a tab containing a page into which it is not permitted to inject. This includes most `about:*` pages (notably `about:debugging` from which add-ons are loaded as Temporary add-ons), but also now includes pages on AMO (e.g. `https://addons.mozilla.org`). In addition your code does not definitively test the active tab *in the current window* for the URL you are testing. Effectively, this means that you may be trying to inject into a tab which you have not checked the URL matches one you want. You do the following: ``` function(tabs) { var tab = tabs[0]; ``` This makes the assumption that the array of [`tabs.Tab`](https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/Tabs/Tab) returned by [`tabs.query()`](https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/tabs/query) will have the active tab for the current window as the first object in that array when you have asked for all `active:true` tabs. While the assumption may be correct in most cases, it is not guaranteed that it is a valid assumption. If you have multiple windows open you will have multiple active tabs. The order of those tabs in the array is not guaranteed to have the one for the current window first. You probably should change your queryInfo object to be `{active:true,currentWindow:true}`. As it is, you may be attempting to inject into a tab which is not the active tab in the current window.
26,044,416
I'm studying the C++ programming language and I'm reading the chapter about assignment operator ( = ). In C++ initalization and assignment are operation so similar that we can use the same notation. But my question is : when i initialize a variable am I doing it with the assignment operator ? When i assign to a variable, am I doing it with the assignment operator ? I think that the only difference is between initialization and assignment because when we initalize a variable we are giving it a new value with the assignmnet operator, when we assign to a variable we are replacing the old value of that variable with a new value using the assignment operator. Is it right ?
2014/09/25
[ "https://Stackoverflow.com/questions/26044416", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3697275/" ]
You asked > > when i initialize a variable am I doing it with the assignment operator ? > > > and said > > when we initialize a variable we are giving it a new value with the assignment operator > > > But, no, you are not. The symbol `=` is used for both copy-initialization and assignment, but initialization does NOT use the assignment operator. Initialization of a variable actually uses a constructor. In copy-initialization, it uses a copy constructor. ``` type x = e; // NOT an assignment operator ``` First `e` is converted to `type`, creating a temporary variable, and then `type::type(const type&)` initializes `x` by copying that temporary. `type::operator=(const type&)` is not called at all. There is also direct initialization, which does not use the `=` symbol: ``` type x(e); type x{e}; // since C++11 otherclass::otherclass() : x(e) {} // initialization of member variable ``` While both initialization and assignment give a variable a value, the two do not use the same code to do it. --- Further details: With C++11 and later, if there is a move constructor, copy initialization will use it instead, because the result of the conversion is a temporary. Also, in copy-initialization, the compiler is permitted to skip actually calling the copy or move constructor, it can convert the initializer directly into the variable. But it still must check that the copy or move constructor exists and is accessible. And copy constructors can also take a non-const reference. So it might be `type::type(type&&)` that is used, or `type::type(const type&&)` (very uncommon), or `type::type(type&)` that is used, instead of `type::type(const type&)`. What I described above is the most common case.
Your thought are quite correct. With a constructor you are allocating a new object of that type, which has its own overhead. When you copy assign to a variable, instead, you don't want to create a new object since you already have one. What you just need is to set the corresponding member variables of the left hand side of the assignment object to the right size. For example: ``` MyClass object = MyClass(10); // here the constructor is called MyClass other = MyClass(5); // here another constructor is called object = other // here the copy assignment operator is called, you don't need to build any new object, just setting fields ``` In addition there is another situation which invokes a copy constructor which is the following: ``` MyClass other2 = MyClass(object); ``` Here a special constructor is called which basically does the same work of a copy assignment operation but with a new object, instead that an existing one.
1,023,306
It seems to me that Linux has it easy with /proc/self/exe. But I'd like to know if there is a convenient way to find the current application's directory in C/C++ with cross-platform interfaces. I've seen some projects mucking around with argv[0], but it doesn't seem entirely reliable. If you ever had to support, say, Mac OS X, which doesn't have /proc/, what would you have done? Use #ifdefs to isolate the platform-specific code (NSBundle, for example)? Or try to deduce the executable's path from argv[0], $PATH and whatnot, risking finding bugs in edge cases?
2009/06/21
[ "https://Stackoverflow.com/questions/1023306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41896/" ]
The [**whereami** library by Gregory Pakosz](https://github.com/gpakosz/whereami) implements this for a variety of platforms, using the APIs mentioned in [mark4o's post](https://stackoverflow.com/questions/1023306/finding-current-executables-path-without-proc-self-exe/1024937#1024937). This is most interesting if you "just" need a solution that works for a portable project and are not interested in the peculiarities of the various platforms. At the time of writing, supported platforms are: * Windows * Linux * Mac * iOS * Android * QNX Neutrino * FreeBSD * NetBSD * DragonFly BSD * SunOS The library consists of `whereami.c` and `whereami.h` and is licensed under MIT and WTFPL2. Drop the files into your project, include the header and use it: ``` #include "whereami.h" int main() { int length = wai_getExecutablePath(NULL, 0, NULL); char* path = (char*)malloc(length + 1); wai_getExecutablePath(path, length, &dirname_length); path[length] = '\0'; printf("My path: %s", path); free(path); return 0; } ```
An alternative on Linux to using either `/proc/self/exe` or `argv[0]` is using the information passed by the ELF interpreter, made available by glibc as such: ``` #include <stdio.h> #include <sys/auxv.h> int main(int argc, char **argv) { printf("%s\n", (char *)getauxval(AT_EXECFN)); return(0); } ``` Note that `getauxval` is a glibc extension, and to be robust you should check so that it doesn't return `NULL` (indicating that the ELF interpreter hasn't provided the `AT_EXECFN` parameter), but I don't think this is ever actually a problem on Linux.
1,023,306
It seems to me that Linux has it easy with /proc/self/exe. But I'd like to know if there is a convenient way to find the current application's directory in C/C++ with cross-platform interfaces. I've seen some projects mucking around with argv[0], but it doesn't seem entirely reliable. If you ever had to support, say, Mac OS X, which doesn't have /proc/, what would you have done? Use #ifdefs to isolate the platform-specific code (NSBundle, for example)? Or try to deduce the executable's path from argv[0], $PATH and whatnot, risking finding bugs in edge cases?
2009/06/21
[ "https://Stackoverflow.com/questions/1023306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41896/" ]
Depending on the version of **QNX Neutrino**, there are different ways to find the full path and name of the executable file that was used to start the running process. I denote the process identifier as `<PID>`. Try the following: 1. If the file `/proc/self/exefile` exists, then its contents are the requested information. 2. If the file `/proc/<PID>/exefile` exists, then its contents are the requested information. 3. If the file `/proc/self/as` exists, then: 1. `open()` the file. 2. Allocate a buffer of, at least, `sizeof(procfs_debuginfo) + _POSIX_PATH_MAX`. 3. Give that buffer as input to `devctl(fd, DCMD_PROC_MAPDEBUG_BASE,...`. 4. Cast the buffer to a `procfs_debuginfo*`. 5. The requested information is at the `path` field of the `procfs_debuginfo` structure. **Warning**: For some reason, sometimes, QNX omits the first slash `/` of the file path. Prepend that `/` when needed. 6. Clean up (close the file, free the buffer, etc.). 4. Try the procedure in `3.` with the file `/proc/<PID>/as`. 5. Try `dladdr(dlsym(RTLD_DEFAULT, "main"), &dlinfo)` where `dlinfo` is a `Dl_info` structure whose `dli_fname` might contain the requested information. I hope this helps.
If you're writing GPLed code and using GNU autotools, then a portable way that takes care of the details on many OSes (including Windows and macOS) is gnulib's [`relocatable-prog`](https://www.gnu.org/software/gnulib/manual/html_node/Supporting-Relocation.html) module.
1,023,306
It seems to me that Linux has it easy with /proc/self/exe. But I'd like to know if there is a convenient way to find the current application's directory in C/C++ with cross-platform interfaces. I've seen some projects mucking around with argv[0], but it doesn't seem entirely reliable. If you ever had to support, say, Mac OS X, which doesn't have /proc/, what would you have done? Use #ifdefs to isolate the platform-specific code (NSBundle, for example)? Or try to deduce the executable's path from argv[0], $PATH and whatnot, risking finding bugs in edge cases?
2009/06/21
[ "https://Stackoverflow.com/questions/1023306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41896/" ]
If you're writing GPLed code and using GNU autotools, then a portable way that takes care of the details on many OSes (including Windows and macOS) is gnulib's [`relocatable-prog`](https://www.gnu.org/software/gnulib/manual/html_node/Supporting-Relocation.html) module.
You can use argv[0] and analyze the PATH environment variable. Look at : [A sample of a program that can find itself](http://h21007.www2.hp.com/portal/site/dspp/menuitem.863c3e4cbcdc3f3515b49c108973a801?ciid=88086d6e1de021106d6e1de02110275d6e10RCRD)
1,023,306
It seems to me that Linux has it easy with /proc/self/exe. But I'd like to know if there is a convenient way to find the current application's directory in C/C++ with cross-platform interfaces. I've seen some projects mucking around with argv[0], but it doesn't seem entirely reliable. If you ever had to support, say, Mac OS X, which doesn't have /proc/, what would you have done? Use #ifdefs to isolate the platform-specific code (NSBundle, for example)? Or try to deduce the executable's path from argv[0], $PATH and whatnot, risking finding bugs in edge cases?
2009/06/21
[ "https://Stackoverflow.com/questions/1023306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41896/" ]
> > If you ever had to support, say, Mac > OS X, which doesn't have /proc/, what > would you have done? Use #ifdefs to > isolate the platform-specific code > (NSBundle, for example)? > > > Yes, isolating platform-specific code with `#ifdefs` is the conventional way this is done. Another approach would be to have a have clean `#ifdef`-less header which contains function declarations and put the implementations in platform specific source files. For example, check out how *POCO* (Portable Components) C++ library does something similar for their *[Environment](https://github.com/pocoproject/poco/blob/develop/Foundation/include/Poco/Environment.h)* class.
> > But I'd like to know if there is a convenient way to find the current application's directory in C/C++ with cross-platform interfaces. > > > You cannot do that (at least on Linux) -------------------------------------- Since an executable could, during execution of a [process](https://en.wikipedia.org/wiki/Process_(computing)) running it, [rename(2)](https://man7.org/linux/man-pages/man2/rename.2.html) its file path to a different directory (of the same file system). See also [syscalls(2)](https://man7.org/linux/man-pages/man2/syscalls.2.html) and [inode(7)](https://man7.org/linux/man-pages/man7/inode.7.html). On Linux, an executable could even (in principle) [remove(3)](https://man7.org/linux/man-pages/man3/remove.3.html) itself by calling [unlink(2)](https://man7.org/linux/man-pages/man2/unlink.2.html). The [Linux kernel](https://en.wikipedia.org/wiki/Linux_kernel) should then keep the file allocated till no process references it anymore. With [proc(5)](https://man7.org/linux/man-pages/man5/proc.5.html) you could do weird things (e.g. [rename(2)](https://man7.org/linux/man-pages/man2/rename.2.html) that `/proc/self/exe` file, etc...) In other words, on Linux, the notion of a "current application's directory" does not make any sense. Read also [*Advanced Linux Programming*](https://mentorembedded.github.io/advancedlinuxprogramming/) and [*Operating Systems: Three Easy Pieces*](http://pages.cs.wisc.edu/%7Eremzi/OSTEP/) for more. Look also on [OSDEV](https://osdev.org/) for several open source operating systems (including [FreeBSD](https://www.freebsd.org/) or [GNU Hurd](https://www.gnu.org/software/hurd/)). Several of them provide an interface (API) close to POSIX ones. Consider using (with permission) cross-platform C++ frameworks like [Qt](https://qt.io/) or [POCO](https://pocoproject.org/), perhaps contributing to them by porting them to your favorite OS.
1,023,306
It seems to me that Linux has it easy with /proc/self/exe. But I'd like to know if there is a convenient way to find the current application's directory in C/C++ with cross-platform interfaces. I've seen some projects mucking around with argv[0], but it doesn't seem entirely reliable. If you ever had to support, say, Mac OS X, which doesn't have /proc/, what would you have done? Use #ifdefs to isolate the platform-specific code (NSBundle, for example)? Or try to deduce the executable's path from argv[0], $PATH and whatnot, risking finding bugs in edge cases?
2009/06/21
[ "https://Stackoverflow.com/questions/1023306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41896/" ]
The [**whereami** library by Gregory Pakosz](https://github.com/gpakosz/whereami) implements this for a variety of platforms, using the APIs mentioned in [mark4o's post](https://stackoverflow.com/questions/1023306/finding-current-executables-path-without-proc-self-exe/1024937#1024937). This is most interesting if you "just" need a solution that works for a portable project and are not interested in the peculiarities of the various platforms. At the time of writing, supported platforms are: * Windows * Linux * Mac * iOS * Android * QNX Neutrino * FreeBSD * NetBSD * DragonFly BSD * SunOS The library consists of `whereami.c` and `whereami.h` and is licensed under MIT and WTFPL2. Drop the files into your project, include the header and use it: ``` #include "whereami.h" int main() { int length = wai_getExecutablePath(NULL, 0, NULL); char* path = (char*)malloc(length + 1); wai_getExecutablePath(path, length, &dirname_length); path[length] = '\0'; printf("My path: %s", path); free(path); return 0; } ```
Making this work reliably across platforms requires using #ifdef statements. The below code finds the executable's path in Windows, Linux, MacOS, Solaris or FreeBSD (although FreeBSD is untested). It uses [Boost](http://www.boost.org) 1.55.0 (or later) to simplify the code, but it's easy enough to remove if you want. Just use defines like \_MSC\_VER and \_\_linux as the OS and compiler require. ``` #include <string> #include <boost/predef/os.h> #if (BOOST_OS_WINDOWS) # include <stdlib.h> #elif (BOOST_OS_SOLARIS) # include <stdlib.h> # include <limits.h> #elif (BOOST_OS_LINUX) # include <unistd.h> # include <limits.h> #elif (BOOST_OS_MACOS) # include <mach-o/dyld.h> #elif (BOOST_OS_BSD_FREE) # include <sys/types.h> # include <sys/sysctl.h> #endif /* * Returns the full path to the currently running executable, * or an empty string in case of failure. */ std::string getExecutablePath() { #if (BOOST_OS_WINDOWS) char *exePath; if (_get_pgmptr(&exePath) != 0) exePath = ""; #elif (BOOST_OS_SOLARIS) char exePath[PATH_MAX]; if (realpath(getexecname(), exePath) == NULL) exePath[0] = '\0'; #elif (BOOST_OS_LINUX) char exePath[PATH_MAX]; ssize_t len = ::readlink("/proc/self/exe", exePath, sizeof(exePath)); if (len == -1 || len == sizeof(exePath)) len = 0; exePath[len] = '\0'; #elif (BOOST_OS_MACOS) char exePath[PATH_MAX]; uint32_t len = sizeof(exePath); if (_NSGetExecutablePath(exePath, &len) != 0) { exePath[0] = '\0'; // buffer too small (!) } else { // resolve symlinks, ., .. if possible char *canonicalPath = realpath(exePath, NULL); if (canonicalPath != NULL) { strncpy(exePath,canonicalPath,len); free(canonicalPath); } } #elif (BOOST_OS_BSD_FREE) char exePath[2048]; int mib[4]; mib[0] = CTL_KERN; mib[1] = KERN_PROC; mib[2] = KERN_PROC_PATHNAME; mib[3] = -1; size_t len = sizeof(exePath); if (sysctl(mib, 4, exePath, &len, NULL, 0) != 0) exePath[0] = '\0'; #endif return std::string(exePath); } ``` The above version returns full paths including the executable name. If instead you want the path without the executable name, `#include boost/filesystem.hpp>` and change the return statement to: ``` return strlen(exePath)>0 ? boost::filesystem::path(exePath).remove_filename().make_preferred().string() : std::string(); ```
1,023,306
It seems to me that Linux has it easy with /proc/self/exe. But I'd like to know if there is a convenient way to find the current application's directory in C/C++ with cross-platform interfaces. I've seen some projects mucking around with argv[0], but it doesn't seem entirely reliable. If you ever had to support, say, Mac OS X, which doesn't have /proc/, what would you have done? Use #ifdefs to isolate the platform-specific code (NSBundle, for example)? Or try to deduce the executable's path from argv[0], $PATH and whatnot, risking finding bugs in edge cases?
2009/06/21
[ "https://Stackoverflow.com/questions/1023306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41896/" ]
Some OS-specific interfaces: * Mac OS X: [`_NSGetExecutablePath()`](https://stackoverflow.com/questions/799679/programatically-retrieving-the-absolute-path-of-an-os-x-command-line-app/1024933#1024933) ([man 3 dyld](https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man3/dyld.3.html)) * Linux: [`readlink /proc/self/exe`](https://man7.org/linux/man-pages/man5/proc.5.html) * Solaris: [`getexecname()`](http://download.oracle.com/docs/cd/E19253-01/816-5168/6mbb3hrb1/index.html) * FreeBSD: [`sysctl CTL_KERN KERN_PROC KERN_PROC_PATHNAME -1`](https://stackoverflow.com/questions/799679) * FreeBSD *if* it has procfs: `readlink /proc/curproc/file` (FreeBSD doesn't have procfs by default) * NetBSD: `readlink /proc/curproc/exe` * DragonFly BSD: `readlink /proc/curproc/file` * Windows: [`GetModuleFileName()`](https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getmodulefilenamea) with `hModule` = `NULL` There are also third party libraries that can be used to get this information, such as [whereami as mentioned in prideout's answer](https://stackoverflow.com/a/32793556/112212), or if you are using Qt, [QCoreApplication::applicationFilePath()](https://doc.qt.io/qt-5/qcoreapplication.html#applicationFilePath) as mentioned in the comments. The portable (but less reliable) method is to use `argv[0]`. Although it could be set to anything by the calling program, by convention it is set to either a path name of the executable or a name that was found using `$PATH`. Some shells, including bash and ksh, [set the environment variable "`_`"](http://www.gnu.org/software/bash/manual/bashref.html#Environment) to the full path of the executable before it is executed. In that case you can use `getenv("_")` to get it. However this is unreliable because not all shells do this, and it could be set to anything or be left over from a parent process which did not change it before executing your program.
An alternative on Linux to using either `/proc/self/exe` or `argv[0]` is using the information passed by the ELF interpreter, made available by glibc as such: ``` #include <stdio.h> #include <sys/auxv.h> int main(int argc, char **argv) { printf("%s\n", (char *)getauxval(AT_EXECFN)); return(0); } ``` Note that `getauxval` is a glibc extension, and to be robust you should check so that it doesn't return `NULL` (indicating that the ELF interpreter hasn't provided the `AT_EXECFN` parameter), but I don't think this is ever actually a problem on Linux.
1,023,306
It seems to me that Linux has it easy with /proc/self/exe. But I'd like to know if there is a convenient way to find the current application's directory in C/C++ with cross-platform interfaces. I've seen some projects mucking around with argv[0], but it doesn't seem entirely reliable. If you ever had to support, say, Mac OS X, which doesn't have /proc/, what would you have done? Use #ifdefs to isolate the platform-specific code (NSBundle, for example)? Or try to deduce the executable's path from argv[0], $PATH and whatnot, risking finding bugs in edge cases?
2009/06/21
[ "https://Stackoverflow.com/questions/1023306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41896/" ]
Depending on the version of **QNX Neutrino**, there are different ways to find the full path and name of the executable file that was used to start the running process. I denote the process identifier as `<PID>`. Try the following: 1. If the file `/proc/self/exefile` exists, then its contents are the requested information. 2. If the file `/proc/<PID>/exefile` exists, then its contents are the requested information. 3. If the file `/proc/self/as` exists, then: 1. `open()` the file. 2. Allocate a buffer of, at least, `sizeof(procfs_debuginfo) + _POSIX_PATH_MAX`. 3. Give that buffer as input to `devctl(fd, DCMD_PROC_MAPDEBUG_BASE,...`. 4. Cast the buffer to a `procfs_debuginfo*`. 5. The requested information is at the `path` field of the `procfs_debuginfo` structure. **Warning**: For some reason, sometimes, QNX omits the first slash `/` of the file path. Prepend that `/` when needed. 6. Clean up (close the file, free the buffer, etc.). 4. Try the procedure in `3.` with the file `/proc/<PID>/as`. 5. Try `dladdr(dlsym(RTLD_DEFAULT, "main"), &dlinfo)` where `dlinfo` is a `Dl_info` structure whose `dli_fname` might contain the requested information. I hope this helps.
Well, of course, this doesn't apply to all projects. Still, `QCoreApplication::applicationFilePath()` never failed me in 6 years of C++/Qt development. Of course, one should read documentation thoroughly before attempting to use it: > > Warning: On Linux, this function will try to get the path from the > /proc file system. If that fails, it assumes that argv[0] contains the > absolute file name of the executable. The function also assumes that > the current directory has not been changed by the application. > > > To be honest, I think that `#ifdef` and other solutions like that shouldn't be used in modern code at all. I'm sure that smaller cross-platform libraries also exist. Let them encapsulate all that platform-specific stuff inside.
1,023,306
It seems to me that Linux has it easy with /proc/self/exe. But I'd like to know if there is a convenient way to find the current application's directory in C/C++ with cross-platform interfaces. I've seen some projects mucking around with argv[0], but it doesn't seem entirely reliable. If you ever had to support, say, Mac OS X, which doesn't have /proc/, what would you have done? Use #ifdefs to isolate the platform-specific code (NSBundle, for example)? Or try to deduce the executable's path from argv[0], $PATH and whatnot, risking finding bugs in edge cases?
2009/06/21
[ "https://Stackoverflow.com/questions/1023306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41896/" ]
Some OS-specific interfaces: * Mac OS X: [`_NSGetExecutablePath()`](https://stackoverflow.com/questions/799679/programatically-retrieving-the-absolute-path-of-an-os-x-command-line-app/1024933#1024933) ([man 3 dyld](https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man3/dyld.3.html)) * Linux: [`readlink /proc/self/exe`](https://man7.org/linux/man-pages/man5/proc.5.html) * Solaris: [`getexecname()`](http://download.oracle.com/docs/cd/E19253-01/816-5168/6mbb3hrb1/index.html) * FreeBSD: [`sysctl CTL_KERN KERN_PROC KERN_PROC_PATHNAME -1`](https://stackoverflow.com/questions/799679) * FreeBSD *if* it has procfs: `readlink /proc/curproc/file` (FreeBSD doesn't have procfs by default) * NetBSD: `readlink /proc/curproc/exe` * DragonFly BSD: `readlink /proc/curproc/file` * Windows: [`GetModuleFileName()`](https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getmodulefilenamea) with `hModule` = `NULL` There are also third party libraries that can be used to get this information, such as [whereami as mentioned in prideout's answer](https://stackoverflow.com/a/32793556/112212), or if you are using Qt, [QCoreApplication::applicationFilePath()](https://doc.qt.io/qt-5/qcoreapplication.html#applicationFilePath) as mentioned in the comments. The portable (but less reliable) method is to use `argv[0]`. Although it could be set to anything by the calling program, by convention it is set to either a path name of the executable or a name that was found using `$PATH`. Some shells, including bash and ksh, [set the environment variable "`_`"](http://www.gnu.org/software/bash/manual/bashref.html#Environment) to the full path of the executable before it is executed. In that case you can use `getenv("_")` to get it. However this is unreliable because not all shells do this, and it could be set to anything or be left over from a parent process which did not change it before executing your program.
Just my two cents. You can find the current application's directory in C/C++ with cross-platform interfaces by using this code. ``` void getExecutablePath(char ** path, unsigned int * pathLength) { // Early exit when invalid out-parameters are passed if (!checkStringOutParameter(path, pathLength)) { return; } #if defined SYSTEM_LINUX // Preallocate PATH_MAX (e.g., 4096) characters and hope the executable path isn't longer (including null byte) char exePath[PATH_MAX]; // Return written bytes, indicating if memory was sufficient int len = readlink("/proc/self/exe", exePath, PATH_MAX); if (len <= 0 || len == PATH_MAX) // memory not sufficient or general error occured { invalidateStringOutParameter(path, pathLength); return; } // Copy contents to caller, create caller ownership copyToStringOutParameter(exePath, len, path, pathLength); #elif defined SYSTEM_WINDOWS // Preallocate MAX_PATH (e.g., 4095) characters and hope the executable path isn't longer (including null byte) char exePath[MAX_PATH]; // Return written bytes, indicating if memory was sufficient unsigned int len = GetModuleFileNameA(GetModuleHandleA(0x0), exePath, MAX_PATH); if (len == 0) // memory not sufficient or general error occured { invalidateStringOutParameter(path, pathLength); return; } // Copy contents to caller, create caller ownership copyToStringOutParameter(exePath, len, path, pathLength); #elif defined SYSTEM_SOLARIS // Preallocate PATH_MAX (e.g., 4096) characters and hope the executable path isn't longer (including null byte) char exePath[PATH_MAX]; // Convert executable path to canonical path, return null pointer on error if (realpath(getexecname(), exePath) == 0x0) { invalidateStringOutParameter(path, pathLength); return; } // Copy contents to caller, create caller ownership unsigned int len = strlen(exePath); copyToStringOutParameter(exePath, len, path, pathLength); #elif defined SYSTEM_DARWIN // Preallocate PATH_MAX (e.g., 4096) characters and hope the executable path isn't longer (including null byte) char exePath[PATH_MAX]; unsigned int len = (unsigned int)PATH_MAX; // Obtain executable path to canonical path, return zero on success if (_NSGetExecutablePath(exePath, &len) == 0) { // Convert executable path to canonical path, return null pointer on error char * realPath = realpath(exePath, 0x0); if (realPath == 0x0) { invalidateStringOutParameter(path, pathLength); return; } // Copy contents to caller, create caller ownership unsigned int len = strlen(realPath); copyToStringOutParameter(realPath, len, path, pathLength); free(realPath); } else // len is initialized with the required number of bytes (including zero byte) { char * intermediatePath = (char *)malloc(sizeof(char) * len); // Convert executable path to canonical path, return null pointer on error if (_NSGetExecutablePath(intermediatePath, &len) != 0) { free(intermediatePath); invalidateStringOutParameter(path, pathLength); return; } char * realPath = realpath(intermediatePath, 0x0); free(intermediatePath); // Check if conversion to canonical path succeeded if (realPath == 0x0) { invalidateStringOutParameter(path, pathLength); return; } // Copy contents to caller, create caller ownership unsigned int len = strlen(realPath); copyToStringOutParameter(realPath, len, path, pathLength); free(realPath); } #elif defined SYSTEM_FREEBSD // Preallocate characters and hope the executable path isn't longer (including null byte) char exePath[2048]; unsigned int len = 2048; int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1 }; // Obtain executable path by syscall if (sysctl(mib, 4, exePath, &len, 0x0, 0) != 0) { invalidateStringOutParameter(path, pathLength); return; } // Copy contents to caller, create caller ownership copyToStringOutParameter(exePath, len, path, pathLength); #else // If no OS could be detected ... degrade gracefully invalidateStringOutParameter(path, pathLength); #endif } ``` You can take a look in detail [here](https://github.com/cginternals/cpplocate/blob/master/source/liblocate/source/liblocate.c).
1,023,306
It seems to me that Linux has it easy with /proc/self/exe. But I'd like to know if there is a convenient way to find the current application's directory in C/C++ with cross-platform interfaces. I've seen some projects mucking around with argv[0], but it doesn't seem entirely reliable. If you ever had to support, say, Mac OS X, which doesn't have /proc/, what would you have done? Use #ifdefs to isolate the platform-specific code (NSBundle, for example)? Or try to deduce the executable's path from argv[0], $PATH and whatnot, risking finding bugs in edge cases?
2009/06/21
[ "https://Stackoverflow.com/questions/1023306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41896/" ]
AFAIK, no such way. And there is also an ambiguity: what would you like to get as the answer if the same executable has multiple hard-links "pointing" to it? (Hard-links don't actually "point", they *are* the same file, just at another place in the file system hierarchy.) Once `execve()` successfully executes a new binary, all information about the arguments to the original program is lost.
> > But I'd like to know if there is a convenient way to find the current application's directory in C/C++ with cross-platform interfaces. > > > You cannot do that (at least on Linux) -------------------------------------- Since an executable could, during execution of a [process](https://en.wikipedia.org/wiki/Process_(computing)) running it, [rename(2)](https://man7.org/linux/man-pages/man2/rename.2.html) its file path to a different directory (of the same file system). See also [syscalls(2)](https://man7.org/linux/man-pages/man2/syscalls.2.html) and [inode(7)](https://man7.org/linux/man-pages/man7/inode.7.html). On Linux, an executable could even (in principle) [remove(3)](https://man7.org/linux/man-pages/man3/remove.3.html) itself by calling [unlink(2)](https://man7.org/linux/man-pages/man2/unlink.2.html). The [Linux kernel](https://en.wikipedia.org/wiki/Linux_kernel) should then keep the file allocated till no process references it anymore. With [proc(5)](https://man7.org/linux/man-pages/man5/proc.5.html) you could do weird things (e.g. [rename(2)](https://man7.org/linux/man-pages/man2/rename.2.html) that `/proc/self/exe` file, etc...) In other words, on Linux, the notion of a "current application's directory" does not make any sense. Read also [*Advanced Linux Programming*](https://mentorembedded.github.io/advancedlinuxprogramming/) and [*Operating Systems: Three Easy Pieces*](http://pages.cs.wisc.edu/%7Eremzi/OSTEP/) for more. Look also on [OSDEV](https://osdev.org/) for several open source operating systems (including [FreeBSD](https://www.freebsd.org/) or [GNU Hurd](https://www.gnu.org/software/hurd/)). Several of them provide an interface (API) close to POSIX ones. Consider using (with permission) cross-platform C++ frameworks like [Qt](https://qt.io/) or [POCO](https://pocoproject.org/), perhaps contributing to them by porting them to your favorite OS.
1,023,306
It seems to me that Linux has it easy with /proc/self/exe. But I'd like to know if there is a convenient way to find the current application's directory in C/C++ with cross-platform interfaces. I've seen some projects mucking around with argv[0], but it doesn't seem entirely reliable. If you ever had to support, say, Mac OS X, which doesn't have /proc/, what would you have done? Use #ifdefs to isolate the platform-specific code (NSBundle, for example)? Or try to deduce the executable's path from argv[0], $PATH and whatnot, risking finding bugs in edge cases?
2009/06/21
[ "https://Stackoverflow.com/questions/1023306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41896/" ]
The use of `/proc/self/exe` is non-portable and unreliable. On my Ubuntu 12.04 system, you must be root to read/follow the symlink. This will make the Boost example and probably the `whereami()` solutions posted fail. This post is very long but discusses the actual issues and presents code which actually works along with validation against a test suite. The best way to find your program is to retrace the same steps the system uses. This is done by using `argv[0]` resolved against file system root, pwd, path environment and considering symlinks, and pathname canonicalization. This is from memory but I have done this in the past successfully and tested it in a variety of different situations. It is not guaranteed to work, but if it doesn't you probably have much bigger problems and it is more reliable overall than any of the other methods discussed. There are situations on a Unix compatible system in which proper handling of `argv[0]` will not get you to your program but then you are executing in a certifiably broken environment. It is also fairly portable to all Unix derived systems since around 1970 and even some non-Unix derived systems as it basically relies on libc() standard functionality and standard command line functionality. It should work on Linux (all versions), Android, Chrome OS, [Minix](https://duckduckgo.com/html/?q=Wikipedia%20Minix), original Bell Labs Unix, [FreeBSD](https://en.wikipedia.org/wiki/FreeBSD), [NetBSD](https://en.wikipedia.org/wiki/NetBSD), [OpenBSD](https://en.wikipedia.org/wiki/OpenBSD), [BSD](https://en.wikipedia.org/wiki/Berkeley_Software_Distribution) x.x, SunOS, [Solaris](https://en.wikipedia.org/wiki/Solaris_%28operating_system%29), SYSV, [HP-UX](https://en.wikipedia.org/wiki/HP-UX), Concentrix, SCO, Darwin, [AIX](https://en.wikipedia.org/wiki/IBM_AIX), OS X, [NeXTSTEP](https://en.wikipedia.org/wiki/NeXTSTEP), etc. And with a little modification probably [VMS](https://en.wikipedia.org/wiki/OpenVMS#Origin_and_name_changes), VM/CMS, DOS/Windows, [ReactOS](https://en.wikipedia.org/wiki/ReactOS), [OS/2](https://duckduckgo.com/html/?q=Wikipedia%20OS/2), etc. If a program was launched directly from a GUI environment, it should have set `argv[0]` to an absolute path. Understand that almost every shell on every Unix compatible operating system that has ever been released basically finds programs the same way and sets up the operating environment almost the same way (with some optional extras). And any other program that launches a program is expected to create the same environment (argv, environment strings, etc.) for that program as if it were run from a shell, with some optional extras. A program or user can setup an environment that deviates from this convention for other subordinate programs that it launches but if it does, this is a bug and the program has no reasonable expectation that the subordinate program or its subordinates will function correctly. Possible values of `argv[0]` include: * `/path/to/executable` — absolute path * `../bin/executable` — relative to pwd * `bin/executable` — relative to pwd * `./foo` — relative to pwd * `executable` — basename, find in path * `bin//executable` — relative to pwd, non-canonical * `src/../bin/executable` — relative to pwd, non-canonical, backtracking * `bin/./echoargc` — relative to pwd, non-canonical Values you should not see: * `~/bin/executable` — rewritten before your program runs. * `~user/bin/executable` — rewritten before your program runs * `alias` — rewritten before your program runs * `$shellvariable` — rewritten before your program runs * `*foo*` — wildcard, rewritten before your program runs, not very useful * `?foo?` — wildcard, rewritten before your program runs, not very useful In addition, these may contain non-canonical path names and multiple layers of symbolic links. In some cases, there may be multiple hard links to the same program. For example, `/bin/ls`, `/bin/ps`, `/bin/chmod`, `/bin/rm`, etc. may be hard links to `/bin/busybox`. To find yourself, follow the steps below: * Save pwd, PATH, and argv[0] on entry to your program (or initialization of your library) as they may change later. * Optional: particularly for non-Unix systems, separate out but don't discard the pathname host/user/drive prefix part, if present; the part which often precedes a colon or follows an initial "//". * If `argv[0]` is an absolute path, use that as a starting point. An absolute path probably starts with "/" but on some non-Unix systems it might start with "" or a drive letter or name prefix followed by a colon. * Else if `argv[0]` is a relative path (contains "/" or "" but doesn't start with it, such as "../../bin/foo", then combine pwd+"/"+argv[0] (use present working directory from when program started, not current). * Else if argv[0] is a plain basename (no slashes), then combine it with each entry in PATH environment variable in turn and try those and use the first one which succeeds. * Optional: Else try the very platform specific `/proc/self/exe`, `/proc/curproc/file` (BSD), and `(char *)getauxval(AT_EXECFN)`, and `dlgetname(...)` if present. You might even try these before `argv[0]`-based methods, if they are available and you don't encounter permission issues. In the somewhat unlikely event (when you consider all versions of all systems) that they are present and don't fail, they might be more authoritative. * Optional: check for a path name passed in using a command line parameter. * Optional: check for a pathname in the environment explicitly passed in by your wrapper script, if any. * Optional: As a last resort try environment variable "\_". It might point to a different program entirely, such as the users shell. * Resolve symlinks, there may be multiple layers. There is the possibility of infinite loops, though if they exist your program probably won't get invoked. * Canonicalize filename by resolving substrings like "/foo/../bar/" to "/bar/". Note this may potentially change the meaning if you cross a network mount point, so canonization is not always a good thing. On a network server, ".." in symlink may be used to traverse a path to another file in the server context instead of on the client. In this case, you probably want the client context so canonicalization is ok. Also convert patterns like "/./" to "/" and "//" to "/". In shell, `readlink --canonicalize` will resolve multiple symlinks and canonicalize name. Chase may do similar but isn't installed. `realpath()` or `canonicalize_file_name()`, if present, may help. If `realpath()` doesn't exist at compile time, you might borrow a copy from a permissively licensed library distribution, and compile it in yourself rather than reinventing the wheel. Fix the potential buffer overflow (pass in sizeof output buffer, think strncpy() vs strcpy()) if you will be using a buffer less than PATH\_MAX. It may be easier just to use a renamed private copy rather than testing if it exists. Permissive license copy from android/darwin/bsd: <https://android.googlesource.com/platform/bionic/+/f077784/libc/upstream-freebsd/lib/libc/stdlib/realpath.c> Be aware that multiple attempts may be successful or partially successful and they might not all point to the same executable, so consider verifying your executable; however, you may not have read permission — if you can't read it, don't treat that as a failure. Or verify something in proximity to your executable such as the "../lib/" directory you are trying to find. You may have multiple versions, packaged and locally compiled versions, local and network versions, and local and USB-drive portable versions, etc. and there is a small possibility that you might get two incompatible results from different methods of locating. And "\_" may simply point to the wrong program. A program using `execve` can deliberately set `argv[0]` to be incompatible with the actual path used to load the program and corrupt PATH, "\_", pwd, etc. though there isn't generally much reason to do so; but this could have security implications if you have vulnerable code that ignores the fact that your execution environment can be changed in variety of ways including, but not limited, to this one (chroot, fuse filesystem, hard links, etc.) It is possible for shell commands to set PATH but fail to export it. You don't necessarily need to code for non-Unix systems but it would be a good idea to be aware of some of the peculiarities so you can write the code in such a way that it isn't as hard for someone to port later. Be aware that some systems (DEC VMS, DOS, URLs, etc.) might have drive names or other prefixes which end with a colon such as "C:", "sys$drive:[foo]bar", and "file:///foo/bar/baz". Old DEC VMS systems use "[" and "]" to enclose the directory portion of the path though this may have changed if your program is compiled in a POSIX environment. Some systems, such as VMS, may have a file version (separated by a semicolon at the end). Some systems use two consecutive slashes as in "//drive/path/to/file" or "user@host:/path/to/file" (scp command) or "file://hostname/path/to/file" (URL). In some cases (DOS and Windows), PATH might have different separator characters — ";" vs ":" and "" vs "/" for a path separator. In csh/tsh there is "path" (delimited with spaces) and "PATH" delimited with colons but your program should receive PATH so you don't need to worry about path. DOS and some other systems can have relative paths that start with a drive prefix. C:foo.exe refers to foo.exe in the current directory on drive C, so you do need to lookup current directory on C: and use that for pwd. An example of symlinks and wrappers on my system: ``` /usr/bin/google-chrome is symlink to /etc/alternatives/google-chrome which is symlink to /usr/bin/google-chrome-stable which is symlink to /opt/google/chrome/google-chrome which is a bash script which runs /opt/google/chome/chrome ``` Note that user [bill](https://stackoverflow.com/users/121958/bill) [posted](https://stackoverflow.com/a/1023377) a link above to a program at HP that handles the three basic cases of `argv[0]`. It needs some changes, though: * It will be necessary to rewrite all the `strcat()` and `strcpy()` to use `strncat()` and `strncpy()`. Even though the variables are declared of length PATHMAX, an input value of length PATHMAX-1 plus the length of concatenated strings is > PATHMAX and an input value of length PATHMAX would be unterminated. * It needs to be rewritten as a library function, rather than just to print out results. * It fails to canonicalize names (use the realpath code I linked to above) * It fails to resolve symbolic links (use the realpath code) So, if you combine both the HP code and the realpath code and fix both to be resistant to buffer overflows, then you should have something which can properly interpret `argv[0]`. The following illustrates actual values of `argv[0]` for various ways of invoking the same program on Ubuntu 12.04. And yes, the program was accidentally named echoargc instead of echoargv. This was done using a script for clean copying but doing it manually in shell gets same results (except aliases don't work in script unless you explicitly enable them). ``` cat ~/src/echoargc.c #include <stdlib.h> #include <stdio.h> #include <unistd.h> main(int argc, char **argv) { printf(" argv[0]=\"%s\"\n", argv[0]); sleep(1); /* in case run from desktop */ } tcc -o ~/bin/echoargc ~/src/echoargc.c cd ~ /home/whitis/bin/echoargc argv[0]="/home/whitis/bin/echoargc" echoargc argv[0]="echoargc" bin/echoargc argv[0]="bin/echoargc" bin//echoargc argv[0]="bin//echoargc" bin/./echoargc argv[0]="bin/./echoargc" src/../bin/echoargc argv[0]="src/../bin/echoargc" cd ~/bin *echo* argv[0]="echoargc" e?hoargc argv[0]="echoargc" ./echoargc argv[0]="./echoargc" cd ~/src ../bin/echoargc argv[0]="../bin/echoargc" cd ~/junk ~/bin/echoargc argv[0]="/home/whitis/bin/echoargc" ~whitis/bin/echoargc argv[0]="/home/whitis/bin/echoargc" alias echoit=~/bin/echoargc echoit argv[0]="/home/whitis/bin/echoargc" echoarg=~/bin/echoargc $echoarg argv[0]="/home/whitis/bin/echoargc" ln -s ~/bin/echoargc junk1 ./junk1 argv[0]="./junk1" ln -s /home/whitis/bin/echoargc junk2 ./junk2 argv[0]="./junk2" ln -s junk1 junk3 ./junk3 argv[0]="./junk3" gnome-desktop-item-edit --create-new ~/Desktop # interactive, create desktop link, then click on it argv[0]="/home/whitis/bin/echoargc" # interactive, right click on gnome application menu, pick edit menus # add menu item for echoargc, then run it from gnome menu argv[0]="/home/whitis/bin/echoargc" cat ./testargcscript 2>&1 | sed -e 's/^/ /g' #!/bin/bash # echoargc is in ~/bin/echoargc # bin is in path shopt -s expand_aliases set -v cat ~/src/echoargc.c tcc -o ~/bin/echoargc ~/src/echoargc.c cd ~ /home/whitis/bin/echoargc echoargc bin/echoargc bin//echoargc bin/./echoargc src/../bin/echoargc cd ~/bin *echo* e?hoargc ./echoargc cd ~/src ../bin/echoargc cd ~/junk ~/bin/echoargc ~whitis/bin/echoargc alias echoit=~/bin/echoargc echoit echoarg=~/bin/echoargc $echoarg ln -s ~/bin/echoargc junk1 ./junk1 ln -s /home/whitis/bin/echoargc junk2 ./junk2 ln -s junk1 junk3 ./junk3 ``` These examples illustrate that the techniques described in this post should work in a wide range of circumstances and why some of the steps are necessary. EDIT: Now, the program that prints argv[0] has been updated to actually find itself. ``` // Copyright 2015 by Mark Whitis. License=MIT style #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <limits.h> #include <assert.h> #include <string.h> #include <errno.h> // "look deep into yourself, Clarice" -- Hanibal Lector char findyourself_save_pwd[PATH_MAX]; char findyourself_save_argv0[PATH_MAX]; char findyourself_save_path[PATH_MAX]; char findyourself_path_separator='/'; char findyourself_path_separator_as_string[2]="/"; char findyourself_path_list_separator[8]=":"; // could be ":; " char findyourself_debug=0; int findyourself_initialized=0; void findyourself_init(char *argv0) { getcwd(findyourself_save_pwd, sizeof(findyourself_save_pwd)); strncpy(findyourself_save_argv0, argv0, sizeof(findyourself_save_argv0)); findyourself_save_argv0[sizeof(findyourself_save_argv0)-1]=0; strncpy(findyourself_save_path, getenv("PATH"), sizeof(findyourself_save_path)); findyourself_save_path[sizeof(findyourself_save_path)-1]=0; findyourself_initialized=1; } int find_yourself(char *result, size_t size_of_result) { char newpath[PATH_MAX+256]; char newpath2[PATH_MAX+256]; assert(findyourself_initialized); result[0]=0; if(findyourself_save_argv0[0]==findyourself_path_separator) { if(findyourself_debug) printf(" absolute path\n"); realpath(findyourself_save_argv0, newpath); if(findyourself_debug) printf(" newpath=\"%s\"\n", newpath); if(!access(newpath, F_OK)) { strncpy(result, newpath, size_of_result); result[size_of_result-1]=0; return(0); } else { perror("access failed 1"); } } else if( strchr(findyourself_save_argv0, findyourself_path_separator )) { if(findyourself_debug) printf(" relative path to pwd\n"); strncpy(newpath2, findyourself_save_pwd, sizeof(newpath2)); newpath2[sizeof(newpath2)-1]=0; strncat(newpath2, findyourself_path_separator_as_string, sizeof(newpath2)); newpath2[sizeof(newpath2)-1]=0; strncat(newpath2, findyourself_save_argv0, sizeof(newpath2)); newpath2[sizeof(newpath2)-1]=0; realpath(newpath2, newpath); if(findyourself_debug) printf(" newpath=\"%s\"\n", newpath); if(!access(newpath, F_OK)) { strncpy(result, newpath, size_of_result); result[size_of_result-1]=0; return(0); } else { perror("access failed 2"); } } else { if(findyourself_debug) printf(" searching $PATH\n"); char *saveptr; char *pathitem; for(pathitem=strtok_r(findyourself_save_path, findyourself_path_list_separator, &saveptr); pathitem; pathitem=strtok_r(NULL, findyourself_path_list_separator, &saveptr) ) { if(findyourself_debug>=2) printf("pathitem=\"%s\"\n", pathitem); strncpy(newpath2, pathitem, sizeof(newpath2)); newpath2[sizeof(newpath2)-1]=0; strncat(newpath2, findyourself_path_separator_as_string, sizeof(newpath2)); newpath2[sizeof(newpath2)-1]=0; strncat(newpath2, findyourself_save_argv0, sizeof(newpath2)); newpath2[sizeof(newpath2)-1]=0; realpath(newpath2, newpath); if(findyourself_debug) printf(" newpath=\"%s\"\n", newpath); if(!access(newpath, F_OK)) { strncpy(result, newpath, size_of_result); result[size_of_result-1]=0; return(0); } } // end for perror("access failed 3"); } // end else // if we get here, we have tried all three methods on argv[0] and still haven't succeeded. Include fallback methods here. return(1); } main(int argc, char **argv) { findyourself_init(argv[0]); char newpath[PATH_MAX]; printf(" argv[0]=\"%s\"\n", argv[0]); realpath(argv[0], newpath); if(strcmp(argv[0],newpath)) { printf(" realpath=\"%s\"\n", newpath); } find_yourself(newpath, sizeof(newpath)); if(1 || strcmp(argv[0],newpath)) { printf(" findyourself=\"%s\"\n", newpath); } sleep(1); /* in case run from desktop */ } ``` And here is the output which demonstrates that in every one of the previous tests it actually did find itself. ``` tcc -o ~/bin/echoargc ~/src/echoargc.c cd ~ /home/whitis/bin/echoargc argv[0]="/home/whitis/bin/echoargc" findyourself="/home/whitis/bin/echoargc" echoargc argv[0]="echoargc" realpath="/home/whitis/echoargc" findyourself="/home/whitis/bin/echoargc" bin/echoargc argv[0]="bin/echoargc" realpath="/home/whitis/bin/echoargc" findyourself="/home/whitis/bin/echoargc" bin//echoargc argv[0]="bin//echoargc" realpath="/home/whitis/bin/echoargc" findyourself="/home/whitis/bin/echoargc" bin/./echoargc argv[0]="bin/./echoargc" realpath="/home/whitis/bin/echoargc" findyourself="/home/whitis/bin/echoargc" src/../bin/echoargc argv[0]="src/../bin/echoargc" realpath="/home/whitis/bin/echoargc" findyourself="/home/whitis/bin/echoargc" cd ~/bin *echo* argv[0]="echoargc" realpath="/home/whitis/bin/echoargc" findyourself="/home/whitis/bin/echoargc" e?hoargc argv[0]="echoargc" realpath="/home/whitis/bin/echoargc" findyourself="/home/whitis/bin/echoargc" ./echoargc argv[0]="./echoargc" realpath="/home/whitis/bin/echoargc" findyourself="/home/whitis/bin/echoargc" cd ~/src ../bin/echoargc argv[0]="../bin/echoargc" realpath="/home/whitis/bin/echoargc" findyourself="/home/whitis/bin/echoargc" cd ~/junk ~/bin/echoargc argv[0]="/home/whitis/bin/echoargc" findyourself="/home/whitis/bin/echoargc" ~whitis/bin/echoargc argv[0]="/home/whitis/bin/echoargc" findyourself="/home/whitis/bin/echoargc" alias echoit=~/bin/echoargc echoit argv[0]="/home/whitis/bin/echoargc" findyourself="/home/whitis/bin/echoargc" echoarg=~/bin/echoargc $echoarg argv[0]="/home/whitis/bin/echoargc" findyourself="/home/whitis/bin/echoargc" rm junk1 junk2 junk3 ln -s ~/bin/echoargc junk1 ./junk1 argv[0]="./junk1" realpath="/home/whitis/bin/echoargc" findyourself="/home/whitis/bin/echoargc" ln -s /home/whitis/bin/echoargc junk2 ./junk2 argv[0]="./junk2" realpath="/home/whitis/bin/echoargc" findyourself="/home/whitis/bin/echoargc" ln -s junk1 junk3 ./junk3 argv[0]="./junk3" realpath="/home/whitis/bin/echoargc" findyourself="/home/whitis/bin/echoargc" ``` The two GUI launches described above also correctly find the program. There is one potential pitfall. The `access()` function drops permissions if the program is setuid before testing. If there is a situation where the program can be found as an elevated user but not as a regular user, then there might be a situation where these tests would fail, although it is unlikely the program could actually be executed under those circumstances. One could use euidaccess() instead. It is possible, however, that it might find an inaccessable program earlier on path than the actual user could.
AFAIK, no such way. And there is also an ambiguity: what would you like to get as the answer if the same executable has multiple hard-links "pointing" to it? (Hard-links don't actually "point", they *are* the same file, just at another place in the file system hierarchy.) Once `execve()` successfully executes a new binary, all information about the arguments to the original program is lost.
37,399,228
There is an [article](https://jlordiales.wordpress.com/2012/12/13/the-builder-pattern-in-practice/) that I came across while I was looking for a good practice of [builder pattern](https://en.wikipedia.org/wiki/Builder_pattern). In the article, the author mentions about something that drew my attention. the pattern being thread safe. The first variation of `build()` method is thread-safe: ``` public User build() { User user = new user(this); if (user.getAge() > 120) { throw new IllegalStateException("Age out of range"); // thread-safe } return user; } ``` Whereas, this one is not: ``` public User build() { if (age > 120) { throw new IllegalStateException("Age out of range"); // bad, not thread-safe } // This is the window of opportunity for a second thread to modify the value of age return new User(this); } ``` Although, I think a better approach would be throwing `IllegalStateException` in the setters: ``` public User build() { User u = null; try { u = new User(this); } catch(IllegalStateException e){ e.printStackTrace(); } return u; } ``` where the constructor looks like this: ``` private User(UserBuilder builder) { setAge(builder.age); } ``` and the setter is: ``` void setAge(int age) throws IllegalStateException { if(age > 0 && age < 120) this.age = age; else throw new IllegalStateException("Age out of range"); } ``` would my approach still be thread-safe? If not, why? And what is the best way to implement the builder pattern in a thread-safe way?
2016/05/23
[ "https://Stackoverflow.com/questions/37399228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3403689/" ]
> > "id":([0-9]), "name":"give the name you want" > > > Try this which will work for the example which has been given by you. "data":{"elements":[{"id":1, "name":"name1",...},{"id":2, "name":"name2",...},...]}
I would rather go for [JSON Path Extractor](http://jmeter-plugins.org/wiki/JSONPathExtractor/) it is much more suitable for dealing with JSON data than Regular Expression Extractor. The relevant JSON Path Query will look like: ``` $.data[?(@.name == 'name1')].id ``` Use [Debug Sampler](http://jmeter.apache.org/usermanual/component_reference.html#Debug_Sampler) and [View Results Tree](http://jmeter.apache.org/usermanual/component_reference.html#View_Results_Tree) listener combination to check the extracted values. If you have already upgraded to the brand new [Apache JMeter 3.0](https://www.blazemeter.com/blog/5-key-things-you-need-know-about-jmeter-30) you can use "JSON Path Tester" mode of the View Results Tree listener. [![JMeter 3.0](https://i.stack.imgur.com/eKmyd.png)](https://i.stack.imgur.com/eKmyd.png)
37,399,228
There is an [article](https://jlordiales.wordpress.com/2012/12/13/the-builder-pattern-in-practice/) that I came across while I was looking for a good practice of [builder pattern](https://en.wikipedia.org/wiki/Builder_pattern). In the article, the author mentions about something that drew my attention. the pattern being thread safe. The first variation of `build()` method is thread-safe: ``` public User build() { User user = new user(this); if (user.getAge() > 120) { throw new IllegalStateException("Age out of range"); // thread-safe } return user; } ``` Whereas, this one is not: ``` public User build() { if (age > 120) { throw new IllegalStateException("Age out of range"); // bad, not thread-safe } // This is the window of opportunity for a second thread to modify the value of age return new User(this); } ``` Although, I think a better approach would be throwing `IllegalStateException` in the setters: ``` public User build() { User u = null; try { u = new User(this); } catch(IllegalStateException e){ e.printStackTrace(); } return u; } ``` where the constructor looks like this: ``` private User(UserBuilder builder) { setAge(builder.age); } ``` and the setter is: ``` void setAge(int age) throws IllegalStateException { if(age > 0 && age < 120) this.age = age; else throw new IllegalStateException("Age out of range"); } ``` would my approach still be thread-safe? If not, why? And what is the best way to implement the builder pattern in a thread-safe way?
2016/05/23
[ "https://Stackoverflow.com/questions/37399228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3403689/" ]
> > "id":([0-9]), "name":"give the name you want" > > > Try this which will work for the example which has been given by you. "data":{"elements":[{"id":1, "name":"name1",...},{"id":2, "name":"name2",...},...]}
I used the following regex to solve the issue: \\"id\\":(\d+)[^{}[]]\*?\\”name\d\\"
37,399,228
There is an [article](https://jlordiales.wordpress.com/2012/12/13/the-builder-pattern-in-practice/) that I came across while I was looking for a good practice of [builder pattern](https://en.wikipedia.org/wiki/Builder_pattern). In the article, the author mentions about something that drew my attention. the pattern being thread safe. The first variation of `build()` method is thread-safe: ``` public User build() { User user = new user(this); if (user.getAge() > 120) { throw new IllegalStateException("Age out of range"); // thread-safe } return user; } ``` Whereas, this one is not: ``` public User build() { if (age > 120) { throw new IllegalStateException("Age out of range"); // bad, not thread-safe } // This is the window of opportunity for a second thread to modify the value of age return new User(this); } ``` Although, I think a better approach would be throwing `IllegalStateException` in the setters: ``` public User build() { User u = null; try { u = new User(this); } catch(IllegalStateException e){ e.printStackTrace(); } return u; } ``` where the constructor looks like this: ``` private User(UserBuilder builder) { setAge(builder.age); } ``` and the setter is: ``` void setAge(int age) throws IllegalStateException { if(age > 0 && age < 120) this.age = age; else throw new IllegalStateException("Age out of range"); } ``` would my approach still be thread-safe? If not, why? And what is the best way to implement the builder pattern in a thread-safe way?
2016/05/23
[ "https://Stackoverflow.com/questions/37399228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3403689/" ]
I would rather go for [JSON Path Extractor](http://jmeter-plugins.org/wiki/JSONPathExtractor/) it is much more suitable for dealing with JSON data than Regular Expression Extractor. The relevant JSON Path Query will look like: ``` $.data[?(@.name == 'name1')].id ``` Use [Debug Sampler](http://jmeter.apache.org/usermanual/component_reference.html#Debug_Sampler) and [View Results Tree](http://jmeter.apache.org/usermanual/component_reference.html#View_Results_Tree) listener combination to check the extracted values. If you have already upgraded to the brand new [Apache JMeter 3.0](https://www.blazemeter.com/blog/5-key-things-you-need-know-about-jmeter-30) you can use "JSON Path Tester" mode of the View Results Tree listener. [![JMeter 3.0](https://i.stack.imgur.com/eKmyd.png)](https://i.stack.imgur.com/eKmyd.png)
I used the following regex to solve the issue: \\"id\\":(\d+)[^{}[]]\*?\\”name\d\\"
5,410,749
Is it semantically correct to have multiple h2 or any header tags in one HTML document?
2011/03/23
[ "https://Stackoverflow.com/questions/5410749", "https://Stackoverflow.com", "https://Stackoverflow.com/users/561957/" ]
Yes semantically that is correct. **Edit** It does not look like the w3 has any restriction on the max occurrences of header entities. <http://www.w3.org/TR/html40/struct/global.html#edef-H1> <http://www.w3.org/TR/html40/sgml/dtd.html#heading>
Yes. Note that you can also group headers in [header groups](http://www.whatwg.org/specs/web-apps/current-work/multipage/sections.html#the-hgroup-element).
8,099,171
Should this delete all records in my SQL table? ``` <?php $con = mysql_connect("localhost","bikemap","pedalhard"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("test", $con); mysql_query("DELETE * FROM gpsdata"); mysql_close($con); ?> ```
2011/11/11
[ "https://Stackoverflow.com/questions/8099171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/467054/" ]
The [`DELETE` syntax](http://dev.mysql.com/doc/refman/5.6/en/delete.html) doesn't allow a star between `DELETE` and `FROM`. Try this instead: ``` mysql_query("DELETE FROM gpsdata"); ```
You might want to check out MySQL's [Truncate](http://dev.mysql.com/doc/refman/5.0/en/truncate-table.html) command. That should remove all records easily.
8,099,171
Should this delete all records in my SQL table? ``` <?php $con = mysql_connect("localhost","bikemap","pedalhard"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("test", $con); mysql_query("DELETE * FROM gpsdata"); mysql_close($con); ?> ```
2011/11/11
[ "https://Stackoverflow.com/questions/8099171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/467054/" ]
The [`DELETE` syntax](http://dev.mysql.com/doc/refman/5.6/en/delete.html) doesn't allow a star between `DELETE` and `FROM`. Try this instead: ``` mysql_query("DELETE FROM gpsdata"); ```
`DELETE` differs from `Truncate`. But if your use case is simple, go to any one. `Truncate` * DDL command * You can't rollback * Table Structure will be re-created. * Your indexes will be lost. * Will delete all rows. `DELETE` * DML command * You can rollback. * Structure remains as it is. * You can specify a range of rows to delete.
8,099,171
Should this delete all records in my SQL table? ``` <?php $con = mysql_connect("localhost","bikemap","pedalhard"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("test", $con); mysql_query("DELETE * FROM gpsdata"); mysql_close($con); ?> ```
2011/11/11
[ "https://Stackoverflow.com/questions/8099171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/467054/" ]
You might want to check out MySQL's [Truncate](http://dev.mysql.com/doc/refman/5.0/en/truncate-table.html) command. That should remove all records easily.
`DELETE` differs from `Truncate`. But if your use case is simple, go to any one. `Truncate` * DDL command * You can't rollback * Table Structure will be re-created. * Your indexes will be lost. * Will delete all rows. `DELETE` * DML command * You can rollback. * Structure remains as it is. * You can specify a range of rows to delete.
28,385,650
I am trying to populate an expandable listview from the database and the app crashes without any log My code: The onCreateView: ``` private View rootView; private ExpandableListView lv; private BaseExpandableListAdapter adapter; private String jsonResult; private String url = "http://reservations.cretantaxiservices.gr/files/getspirits.php"; ProgressDialog pDialog; ArrayList<ProductList> childs; String[] products; ArrayList<ExpandableListParent> customList; @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { rootView = inflater.inflate(R.layout.activity_spirits_fragment, container, false); lv = (ExpandableListView)rootView.findViewById(R.id.spiritsListView); final SwipeRefreshLayout mSwipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.activity_main_swipe_refresh_layout); ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(getActivity().getApplicationContext().CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean network_connected = activeNetwork != null && activeNetwork.isAvailable() && activeNetwork.isConnectedOrConnecting(); if (!network_connected) { onDetectNetworkState().show(); } else { if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) { accessWebService(); registerCallClickBack(); mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { accessWebService(); mSwipeRefreshLayout.setRefreshing(false); } }); } } return rootView; } ``` The JSONTask ``` public class JsonReadTask extends AsyncTask<String , Void, ArrayList<ExpandableListParent>> { public JsonReadTask() { super(); } @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(getActivity(), ProgressDialog.THEME_DEVICE_DEFAULT_DARK); pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); pDialog.setIndeterminate(true); pDialog.setMessage(getString(R.string.get_stocks)); pDialog.setCancelable(false); pDialog.setInverseBackgroundForced(true); pDialog.show(); } @Override protected ArrayList<ExpandableListParent> doInBackground(String... params) { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(params[0]); try { HttpResponse response = httpclient.execute(httppost); jsonResult = inputStreamToString( response.getEntity().getContent()).toString(); customList = new ArrayList<>(); JSONObject jsonResponse = new JSONObject(jsonResult); JSONArray jsonMainNode = jsonResponse.optJSONArray("spirits"); for (int i = 0; i < jsonMainNode.length(); i++) { JSONObject jsonChildNode = jsonMainNode.getJSONObject(i); String name = jsonChildNode.optString("type"); String price = jsonChildNode.optString("price"); String image = jsonChildNode.optString("image"); String p1 = jsonChildNode.optString("product1"); String p2 = jsonChildNode.optString("product2"); String p3 = jsonChildNode.optString("product3"); products = new String[]{p1, p2, p3}; childs.add(new ProductList(price, products, image)); customList.add(new ExpandableListParent(name, childs)); } return customList; } catch (Exception e) { e.printStackTrace(); getActivity().finish(); } return null; } private StringBuilder inputStreamToString(InputStream is) { String rLine = ""; StringBuilder answer = new StringBuilder(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); try { while ((rLine = rd.readLine()) != null) { answer.append(rLine); } } catch (Exception e) { getActivity().finish(); } return answer; } @Override protected void onPostExecute(ArrayList<ExpandableListParent> customList) { if(customList == null){ Log.d("ERORR", "No result to show."); return; } ListDrawer(customList); pDialog.dismiss(); } }// end async task public void accessWebService() { JsonReadTask task = new JsonReadTask(); task.execute(new String[]{url}); } public void ListDrawer(ArrayList<ExpandableListParent> customList) { adapter = new ExpandListAdapter(getActivity().getApplicationContext(), customList); lv.setAdapter(adapter); } ``` My Adapter class: ``` public class ExpandListAdapter extends BaseExpandableListAdapter { private Context context; private ArrayList<ExpandableListParent> groups; public ExpandListAdapter(Context context, ArrayList<ExpandableListParent> groups) { this.context = context; this.groups = groups; } @Override public int getGroupCount() { return groups.size(); } @Override public int getChildrenCount(int groupPosition) { return groups.get(groupPosition).getChilds().size(); } @Override public Object getGroup(int groupPosition) { return groups.get(groupPosition); } @Override public Object getChild(int groupPosition, int childPosition) { return groups.get(groupPosition).getChilds().get(childPosition); } @Override public long getGroupId(int groupPosition) { return groupPosition; } @Override public long getChildId(int groupPosition, int childPosition) { return childPosition; } @Override public boolean hasStableIds() { return true; } @Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { ExpandableListParent group = (ExpandableListParent) getGroup(groupPosition); if (convertView == null) { LayoutInflater inf = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE); convertView = inf.inflate(R.layout.exp_list_item_parent, null); } TextView tv = (TextView) convertView.findViewById(R.id.exp_text); tv.setText(group.getName()); return convertView; } @Override public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { ProductList child = (ProductList) getChild(groupPosition, childPosition); if (convertView == null) { LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE); convertView = infalInflater.inflate(R.layout.list_item, null); } TextView tv = (TextView) convertView.findViewById(R.id.product_name_coffee); tv.setText(child.getName()); TextView tvp = (TextView) convertView.findViewById(R.id.product_price_coffee); tvp.setText("5"); ImageView iv = (ImageView)convertView.findViewById(R.id.product_image_coffee); Ion.with(iv).error(R.drawable.ic_launcher).placeholder(R.drawable.ic_launcher).load(child.getImage()); return convertView; } @Override public boolean isChildSelectable(int groupPosition, int childPosition) { return true; } } ``` The logcat error: ``` Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.ArrayList.add(java.lang.Object)' on a null object reference at fragments.SpiritsFragment$JsonReadTask.doInBackground(SpiritsFragment.java:225) at fragments.SpiritsFragment$JsonReadTask.doInBackground(SpiritsFragment.java:161) ``` The error lines: ``` SpiritsFragment.java 225: childs.add(new ProductList(price, products, image)); SpiritsFragment.java 161: public class JsonReadTask extends AsyncTask<String , Void, ArrayList<ExpandableListParent>> ``` And when i open the app it just gets me back to the 1st activity without any logcat output for the reason this is happening. Any ideas?? Thanks in advance!!
2015/02/07
[ "https://Stackoverflow.com/questions/28385650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Inline styling has a [higher specificity](https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity). Therefore `background` is overwriting the property [shorthand `background-size`](https://developer.mozilla.org/en-US/docs/Web/CSS/Shorthand_properties#Background_Properties). Change `background` to `background-image`: [**Updated Example**](http://jsfiddle.net/008f5yjb/) ``` <div class="box" style="background-image:url('http://www.addictedtoibiza.com/wp-content/uploads/2012/12/example.png');"> <div class="overlay"> <div class="buttonContainer"> <button>preview</button> </div> </div> </div> ``` After looking at the example, it seems like you may be more interested in using the value `contain` rather than `cover`. [**(example)**](http://jsfiddle.net/oefmfc97/)
`background` is a **general** property, so this includes: `backgound-image`, `background-size`, `background-color`, `background-position`, etc. So **you should to use** in this case `background-image` only, because `background` is overwriting your above css defined properties. Regards
28,385,650
I am trying to populate an expandable listview from the database and the app crashes without any log My code: The onCreateView: ``` private View rootView; private ExpandableListView lv; private BaseExpandableListAdapter adapter; private String jsonResult; private String url = "http://reservations.cretantaxiservices.gr/files/getspirits.php"; ProgressDialog pDialog; ArrayList<ProductList> childs; String[] products; ArrayList<ExpandableListParent> customList; @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { rootView = inflater.inflate(R.layout.activity_spirits_fragment, container, false); lv = (ExpandableListView)rootView.findViewById(R.id.spiritsListView); final SwipeRefreshLayout mSwipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.activity_main_swipe_refresh_layout); ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(getActivity().getApplicationContext().CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean network_connected = activeNetwork != null && activeNetwork.isAvailable() && activeNetwork.isConnectedOrConnecting(); if (!network_connected) { onDetectNetworkState().show(); } else { if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) { accessWebService(); registerCallClickBack(); mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { accessWebService(); mSwipeRefreshLayout.setRefreshing(false); } }); } } return rootView; } ``` The JSONTask ``` public class JsonReadTask extends AsyncTask<String , Void, ArrayList<ExpandableListParent>> { public JsonReadTask() { super(); } @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(getActivity(), ProgressDialog.THEME_DEVICE_DEFAULT_DARK); pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); pDialog.setIndeterminate(true); pDialog.setMessage(getString(R.string.get_stocks)); pDialog.setCancelable(false); pDialog.setInverseBackgroundForced(true); pDialog.show(); } @Override protected ArrayList<ExpandableListParent> doInBackground(String... params) { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(params[0]); try { HttpResponse response = httpclient.execute(httppost); jsonResult = inputStreamToString( response.getEntity().getContent()).toString(); customList = new ArrayList<>(); JSONObject jsonResponse = new JSONObject(jsonResult); JSONArray jsonMainNode = jsonResponse.optJSONArray("spirits"); for (int i = 0; i < jsonMainNode.length(); i++) { JSONObject jsonChildNode = jsonMainNode.getJSONObject(i); String name = jsonChildNode.optString("type"); String price = jsonChildNode.optString("price"); String image = jsonChildNode.optString("image"); String p1 = jsonChildNode.optString("product1"); String p2 = jsonChildNode.optString("product2"); String p3 = jsonChildNode.optString("product3"); products = new String[]{p1, p2, p3}; childs.add(new ProductList(price, products, image)); customList.add(new ExpandableListParent(name, childs)); } return customList; } catch (Exception e) { e.printStackTrace(); getActivity().finish(); } return null; } private StringBuilder inputStreamToString(InputStream is) { String rLine = ""; StringBuilder answer = new StringBuilder(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); try { while ((rLine = rd.readLine()) != null) { answer.append(rLine); } } catch (Exception e) { getActivity().finish(); } return answer; } @Override protected void onPostExecute(ArrayList<ExpandableListParent> customList) { if(customList == null){ Log.d("ERORR", "No result to show."); return; } ListDrawer(customList); pDialog.dismiss(); } }// end async task public void accessWebService() { JsonReadTask task = new JsonReadTask(); task.execute(new String[]{url}); } public void ListDrawer(ArrayList<ExpandableListParent> customList) { adapter = new ExpandListAdapter(getActivity().getApplicationContext(), customList); lv.setAdapter(adapter); } ``` My Adapter class: ``` public class ExpandListAdapter extends BaseExpandableListAdapter { private Context context; private ArrayList<ExpandableListParent> groups; public ExpandListAdapter(Context context, ArrayList<ExpandableListParent> groups) { this.context = context; this.groups = groups; } @Override public int getGroupCount() { return groups.size(); } @Override public int getChildrenCount(int groupPosition) { return groups.get(groupPosition).getChilds().size(); } @Override public Object getGroup(int groupPosition) { return groups.get(groupPosition); } @Override public Object getChild(int groupPosition, int childPosition) { return groups.get(groupPosition).getChilds().get(childPosition); } @Override public long getGroupId(int groupPosition) { return groupPosition; } @Override public long getChildId(int groupPosition, int childPosition) { return childPosition; } @Override public boolean hasStableIds() { return true; } @Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { ExpandableListParent group = (ExpandableListParent) getGroup(groupPosition); if (convertView == null) { LayoutInflater inf = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE); convertView = inf.inflate(R.layout.exp_list_item_parent, null); } TextView tv = (TextView) convertView.findViewById(R.id.exp_text); tv.setText(group.getName()); return convertView; } @Override public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { ProductList child = (ProductList) getChild(groupPosition, childPosition); if (convertView == null) { LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE); convertView = infalInflater.inflate(R.layout.list_item, null); } TextView tv = (TextView) convertView.findViewById(R.id.product_name_coffee); tv.setText(child.getName()); TextView tvp = (TextView) convertView.findViewById(R.id.product_price_coffee); tvp.setText("5"); ImageView iv = (ImageView)convertView.findViewById(R.id.product_image_coffee); Ion.with(iv).error(R.drawable.ic_launcher).placeholder(R.drawable.ic_launcher).load(child.getImage()); return convertView; } @Override public boolean isChildSelectable(int groupPosition, int childPosition) { return true; } } ``` The logcat error: ``` Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.ArrayList.add(java.lang.Object)' on a null object reference at fragments.SpiritsFragment$JsonReadTask.doInBackground(SpiritsFragment.java:225) at fragments.SpiritsFragment$JsonReadTask.doInBackground(SpiritsFragment.java:161) ``` The error lines: ``` SpiritsFragment.java 225: childs.add(new ProductList(price, products, image)); SpiritsFragment.java 161: public class JsonReadTask extends AsyncTask<String , Void, ArrayList<ExpandableListParent>> ``` And when i open the app it just gets me back to the 1st activity without any logcat output for the reason this is happening. Any ideas?? Thanks in advance!!
2015/02/07
[ "https://Stackoverflow.com/questions/28385650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Inline styling has a [higher specificity](https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity). Therefore `background` is overwriting the property [shorthand `background-size`](https://developer.mozilla.org/en-US/docs/Web/CSS/Shorthand_properties#Background_Properties). Change `background` to `background-image`: [**Updated Example**](http://jsfiddle.net/008f5yjb/) ``` <div class="box" style="background-image:url('http://www.addictedtoibiza.com/wp-content/uploads/2012/12/example.png');"> <div class="overlay"> <div class="buttonContainer"> <button>preview</button> </div> </div> </div> ``` After looking at the example, it seems like you may be more interested in using the value `contain` rather than `cover`. [**(example)**](http://jsfiddle.net/oefmfc97/)
This will work if you change `background` to `background-image` see working demo here: <http://jsfiddle.net/3t7ftpky/> **Why does this work?** `background` is a shorthand property and by putting it inline it overrides the other `background-size` properties in the stylesheet. you can find out more about the [css background property here](https://developer.mozilla.org/en/docs/Web/CSS/background):
1,848,216
I need to find a second order linear homogeneous equation with constant coefficients that has the given function as a solution question a) $xe^{-3x}$ question b) $e^{3x} \sin x$ We have learned about the aux equations in second order, and we have touched on the reduction of order process Question $a)$ I see that $-3$ must be a root of the characteristic equation and because there is $a x$ in $xe^{-3x}$ it must be a repeated root, so my solution that I have is $y"-6y+9$ Question $b)$ I have got $y"-6y'+10y=0$
2016/07/04
[ "https://math.stackexchange.com/questions/1848216", "https://math.stackexchange.com", "https://math.stackexchange.com/users/343437/" ]
Earlier I had linked my question with this one of yours and it was closed as a duplicate. But you are not so much interested in knowing a proof of the result, but rather you are interested in understanding the proof given in your textbook. The following answer is thus an explanation for the proof given in your textbook. The solution given in your textbook is very concise and does not give all the details. Since $f$ is continuous on $[a, b]$ its range is also a closed interval $[m, M]$. The solution assumes that $m < M$ otherwise $f$ is a constant and does not meet hypotheses of the question. Next it says that the value $M$ is taken at two distinct points $c, d$ and says that one of them say $c \in (a, b)$ and $d \in [a, b]$. *It is however possible that both $c, d$ are endpoints of $[a, b]$. This is not mentioned or considered in the solution.* Anyway proceeding with the textbook solution let $c \in (a, b), d \in [a, b]$ and $f(c) = f(d) = M$. Moreover $f(x) < M$ for all $x \in [a, b], x \neq c, x\neq d$. Next the solution proposes the existence of $\delta > 0$ such that $f(x) < M$ for all $x \in [c - \delta, c) \cup (c, c + \delta)$. Further if $d \neq a$ then we also have $f(x) < M$ for all $x \in [d - \delta, d)$ (*there is a typo in the solution where it writes $[d - \delta, d]$ instead of $[d - \delta, d)$)*. All these statements are true by the last sentence of previous paragraph. And note that *the solution does not handle the case $d = a$*. Now it considers $$A = \max(f(c - \delta), f(c + \delta), f(d - \delta))$$ BTW out of these values $f(c - \delta), f(c + \delta), f(d - \delta)$ at max two can be equal. If $B$ is the minimum of these values then $B < A < M$ and thus by intermediate value theorem $A$ is attained once in each of the three intervals $[c - \delta, c], [c, c + \delta]$ and $[d - \delta, d]$ and thus $f$ takes the value $A$ at three distinct points $x, y, z$. That these three points are distinct follows from the fact that $\delta$ can be chosen so that $(c - \delta), (c, c + \delta)$ and $(d - \delta, d)$ are pairwise disjoint. This is contrary to the hypotheses in the question. This completes the proof. The solution needs to address the two cases which are left out: * The case when $c, d$ are both the end points of $[a, b]$. * The case when $d = a$ and $c \in (a, b)$. Here we consider $[d, d + \delta]$ and argue like your textbook solution. For the first case when $c, d$ are endpoints so that for example $c = a, d = b$, we necessarily need to consider the points $p, q \in (a, b), p < q$ where $f$ takes minimum value $m$. Thus we have $f(p) = f(q) = m < M = f(a) = f(b)$. Note further that all the values of $f$ in $(p, q)$ are greater than $m$ and hence if $M'$ is maximum value of $f$ in $[p, q]$ then $m < M' < M$. And suppose $M'$ is attained at $r \in (p, q)$. Let $K$ be any number such that $m < K < M' < M$. Then by intermediate value theorem $f$ takes the value $K$ once in each of the intervals $(a, p), (p, r), (r, q), (q, b)$ and this contradicts the hypotheses.
**Hint**: you don't need to use continuity, only the Darboux (intermediate value) property. Look at the minimum and maximum value of $f$ in the interval. Notice that they have to be distinct (otherwise it is clearly false), and then consider the relative placement of the four points where the extreme values are attained, and using the Darboux property argue that in each cases, some values will be attained at least three times.
1,848,216
I need to find a second order linear homogeneous equation with constant coefficients that has the given function as a solution question a) $xe^{-3x}$ question b) $e^{3x} \sin x$ We have learned about the aux equations in second order, and we have touched on the reduction of order process Question $a)$ I see that $-3$ must be a root of the characteristic equation and because there is $a x$ in $xe^{-3x}$ it must be a repeated root, so my solution that I have is $y"-6y+9$ Question $b)$ I have got $y"-6y'+10y=0$
2016/07/04
[ "https://math.stackexchange.com/questions/1848216", "https://math.stackexchange.com", "https://math.stackexchange.com/users/343437/" ]
Suppose $f:[0,1]\to\mathbb{R}$ takes each of its values exactly twice. Consider the self-map FLIP of the interval $[0,1]$ switching the two points where the values of the function are equal. This FLIP a continuous map without fixed points. But any self-map of the closed interval must have a fixed point by (the trivial one-dimensional case of) Brouwer's fixed point theorem. This proves that there is no such function $f$.
**Hint**: you don't need to use continuity, only the Darboux (intermediate value) property. Look at the minimum and maximum value of $f$ in the interval. Notice that they have to be distinct (otherwise it is clearly false), and then consider the relative placement of the four points where the extreme values are attained, and using the Darboux property argue that in each cases, some values will be attained at least three times.
1,848,216
I need to find a second order linear homogeneous equation with constant coefficients that has the given function as a solution question a) $xe^{-3x}$ question b) $e^{3x} \sin x$ We have learned about the aux equations in second order, and we have touched on the reduction of order process Question $a)$ I see that $-3$ must be a root of the characteristic equation and because there is $a x$ in $xe^{-3x}$ it must be a repeated root, so my solution that I have is $y"-6y+9$ Question $b)$ I have got $y"-6y'+10y=0$
2016/07/04
[ "https://math.stackexchange.com/questions/1848216", "https://math.stackexchange.com", "https://math.stackexchange.com/users/343437/" ]
Earlier I had linked my question with this one of yours and it was closed as a duplicate. But you are not so much interested in knowing a proof of the result, but rather you are interested in understanding the proof given in your textbook. The following answer is thus an explanation for the proof given in your textbook. The solution given in your textbook is very concise and does not give all the details. Since $f$ is continuous on $[a, b]$ its range is also a closed interval $[m, M]$. The solution assumes that $m < M$ otherwise $f$ is a constant and does not meet hypotheses of the question. Next it says that the value $M$ is taken at two distinct points $c, d$ and says that one of them say $c \in (a, b)$ and $d \in [a, b]$. *It is however possible that both $c, d$ are endpoints of $[a, b]$. This is not mentioned or considered in the solution.* Anyway proceeding with the textbook solution let $c \in (a, b), d \in [a, b]$ and $f(c) = f(d) = M$. Moreover $f(x) < M$ for all $x \in [a, b], x \neq c, x\neq d$. Next the solution proposes the existence of $\delta > 0$ such that $f(x) < M$ for all $x \in [c - \delta, c) \cup (c, c + \delta)$. Further if $d \neq a$ then we also have $f(x) < M$ for all $x \in [d - \delta, d)$ (*there is a typo in the solution where it writes $[d - \delta, d]$ instead of $[d - \delta, d)$)*. All these statements are true by the last sentence of previous paragraph. And note that *the solution does not handle the case $d = a$*. Now it considers $$A = \max(f(c - \delta), f(c + \delta), f(d - \delta))$$ BTW out of these values $f(c - \delta), f(c + \delta), f(d - \delta)$ at max two can be equal. If $B$ is the minimum of these values then $B < A < M$ and thus by intermediate value theorem $A$ is attained once in each of the three intervals $[c - \delta, c], [c, c + \delta]$ and $[d - \delta, d]$ and thus $f$ takes the value $A$ at three distinct points $x, y, z$. That these three points are distinct follows from the fact that $\delta$ can be chosen so that $(c - \delta), (c, c + \delta)$ and $(d - \delta, d)$ are pairwise disjoint. This is contrary to the hypotheses in the question. This completes the proof. The solution needs to address the two cases which are left out: * The case when $c, d$ are both the end points of $[a, b]$. * The case when $d = a$ and $c \in (a, b)$. Here we consider $[d, d + \delta]$ and argue like your textbook solution. For the first case when $c, d$ are endpoints so that for example $c = a, d = b$, we necessarily need to consider the points $p, q \in (a, b), p < q$ where $f$ takes minimum value $m$. Thus we have $f(p) = f(q) = m < M = f(a) = f(b)$. Note further that all the values of $f$ in $(p, q)$ are greater than $m$ and hence if $M'$ is maximum value of $f$ in $[p, q]$ then $m < M' < M$. And suppose $M'$ is attained at $r \in (p, q)$. Let $K$ be any number such that $m < K < M' < M$. Then by intermediate value theorem $f$ takes the value $K$ once in each of the intervals $(a, p), (p, r), (r, q), (q, b)$ and this contradicts the hypotheses.
Suppose $f:[0,1]\to\mathbb{R}$ takes each of its values exactly twice. Consider the self-map FLIP of the interval $[0,1]$ switching the two points where the values of the function are equal. This FLIP a continuous map without fixed points. But any self-map of the closed interval must have a fixed point by (the trivial one-dimensional case of) Brouwer's fixed point theorem. This proves that there is no such function $f$.
1,848,216
I need to find a second order linear homogeneous equation with constant coefficients that has the given function as a solution question a) $xe^{-3x}$ question b) $e^{3x} \sin x$ We have learned about the aux equations in second order, and we have touched on the reduction of order process Question $a)$ I see that $-3$ must be a root of the characteristic equation and because there is $a x$ in $xe^{-3x}$ it must be a repeated root, so my solution that I have is $y"-6y+9$ Question $b)$ I have got $y"-6y'+10y=0$
2016/07/04
[ "https://math.stackexchange.com/questions/1848216", "https://math.stackexchange.com", "https://math.stackexchange.com/users/343437/" ]
Earlier I had linked my question with this one of yours and it was closed as a duplicate. But you are not so much interested in knowing a proof of the result, but rather you are interested in understanding the proof given in your textbook. The following answer is thus an explanation for the proof given in your textbook. The solution given in your textbook is very concise and does not give all the details. Since $f$ is continuous on $[a, b]$ its range is also a closed interval $[m, M]$. The solution assumes that $m < M$ otherwise $f$ is a constant and does not meet hypotheses of the question. Next it says that the value $M$ is taken at two distinct points $c, d$ and says that one of them say $c \in (a, b)$ and $d \in [a, b]$. *It is however possible that both $c, d$ are endpoints of $[a, b]$. This is not mentioned or considered in the solution.* Anyway proceeding with the textbook solution let $c \in (a, b), d \in [a, b]$ and $f(c) = f(d) = M$. Moreover $f(x) < M$ for all $x \in [a, b], x \neq c, x\neq d$. Next the solution proposes the existence of $\delta > 0$ such that $f(x) < M$ for all $x \in [c - \delta, c) \cup (c, c + \delta)$. Further if $d \neq a$ then we also have $f(x) < M$ for all $x \in [d - \delta, d)$ (*there is a typo in the solution where it writes $[d - \delta, d]$ instead of $[d - \delta, d)$)*. All these statements are true by the last sentence of previous paragraph. And note that *the solution does not handle the case $d = a$*. Now it considers $$A = \max(f(c - \delta), f(c + \delta), f(d - \delta))$$ BTW out of these values $f(c - \delta), f(c + \delta), f(d - \delta)$ at max two can be equal. If $B$ is the minimum of these values then $B < A < M$ and thus by intermediate value theorem $A$ is attained once in each of the three intervals $[c - \delta, c], [c, c + \delta]$ and $[d - \delta, d]$ and thus $f$ takes the value $A$ at three distinct points $x, y, z$. That these three points are distinct follows from the fact that $\delta$ can be chosen so that $(c - \delta), (c, c + \delta)$ and $(d - \delta, d)$ are pairwise disjoint. This is contrary to the hypotheses in the question. This completes the proof. The solution needs to address the two cases which are left out: * The case when $c, d$ are both the end points of $[a, b]$. * The case when $d = a$ and $c \in (a, b)$. Here we consider $[d, d + \delta]$ and argue like your textbook solution. For the first case when $c, d$ are endpoints so that for example $c = a, d = b$, we necessarily need to consider the points $p, q \in (a, b), p < q$ where $f$ takes minimum value $m$. Thus we have $f(p) = f(q) = m < M = f(a) = f(b)$. Note further that all the values of $f$ in $(p, q)$ are greater than $m$ and hence if $M'$ is maximum value of $f$ in $[p, q]$ then $m < M' < M$. And suppose $M'$ is attained at $r \in (p, q)$. Let $K$ be any number such that $m < K < M' < M$. Then by intermediate value theorem $f$ takes the value $K$ once in each of the intervals $(a, p), (p, r), (r, q), (q, b)$ and this contradicts the hypotheses.
Given such a function, $[a,b]$ is partitioned into uncountably many pairs $\{x\_1,x\_2\}$ with $f(x\_1)=f(x\_2)$. Can two pairs $\{x\_1,x\_2\}$ and $\{x\_3,x\_4\}$ overlap? In such a acase we would have wlog $x\_1<x\_3<x\_2<x\_4$. Pick $c$ between $f(x\_1)$ and $f(x\_2)$. By the Intermediate value property, there exists $\xi\in(x\_1,x\_3)$ with $f(\xi)=c$. But such $\xi$ also exists in $(x\_3,x\_2)$ and in $(x\_2,x\_4)$, contradicting the special property of $f$. We conclude that two distinct pairs $\{x\_1,x\_2\}$ and $\{x\_3,x\_4\}$ can only be nested. Then the intersection of the nested closed intervals with these pairs as endpoints is non-empty and contains a point $\bar x\_1$ that cannot occur in a pair $\{\bar x\_1,\bar x\_2\}$.
1,848,216
I need to find a second order linear homogeneous equation with constant coefficients that has the given function as a solution question a) $xe^{-3x}$ question b) $e^{3x} \sin x$ We have learned about the aux equations in second order, and we have touched on the reduction of order process Question $a)$ I see that $-3$ must be a root of the characteristic equation and because there is $a x$ in $xe^{-3x}$ it must be a repeated root, so my solution that I have is $y"-6y+9$ Question $b)$ I have got $y"-6y'+10y=0$
2016/07/04
[ "https://math.stackexchange.com/questions/1848216", "https://math.stackexchange.com", "https://math.stackexchange.com/users/343437/" ]
Earlier I had linked my question with this one of yours and it was closed as a duplicate. But you are not so much interested in knowing a proof of the result, but rather you are interested in understanding the proof given in your textbook. The following answer is thus an explanation for the proof given in your textbook. The solution given in your textbook is very concise and does not give all the details. Since $f$ is continuous on $[a, b]$ its range is also a closed interval $[m, M]$. The solution assumes that $m < M$ otherwise $f$ is a constant and does not meet hypotheses of the question. Next it says that the value $M$ is taken at two distinct points $c, d$ and says that one of them say $c \in (a, b)$ and $d \in [a, b]$. *It is however possible that both $c, d$ are endpoints of $[a, b]$. This is not mentioned or considered in the solution.* Anyway proceeding with the textbook solution let $c \in (a, b), d \in [a, b]$ and $f(c) = f(d) = M$. Moreover $f(x) < M$ for all $x \in [a, b], x \neq c, x\neq d$. Next the solution proposes the existence of $\delta > 0$ such that $f(x) < M$ for all $x \in [c - \delta, c) \cup (c, c + \delta)$. Further if $d \neq a$ then we also have $f(x) < M$ for all $x \in [d - \delta, d)$ (*there is a typo in the solution where it writes $[d - \delta, d]$ instead of $[d - \delta, d)$)*. All these statements are true by the last sentence of previous paragraph. And note that *the solution does not handle the case $d = a$*. Now it considers $$A = \max(f(c - \delta), f(c + \delta), f(d - \delta))$$ BTW out of these values $f(c - \delta), f(c + \delta), f(d - \delta)$ at max two can be equal. If $B$ is the minimum of these values then $B < A < M$ and thus by intermediate value theorem $A$ is attained once in each of the three intervals $[c - \delta, c], [c, c + \delta]$ and $[d - \delta, d]$ and thus $f$ takes the value $A$ at three distinct points $x, y, z$. That these three points are distinct follows from the fact that $\delta$ can be chosen so that $(c - \delta), (c, c + \delta)$ and $(d - \delta, d)$ are pairwise disjoint. This is contrary to the hypotheses in the question. This completes the proof. The solution needs to address the two cases which are left out: * The case when $c, d$ are both the end points of $[a, b]$. * The case when $d = a$ and $c \in (a, b)$. Here we consider $[d, d + \delta]$ and argue like your textbook solution. For the first case when $c, d$ are endpoints so that for example $c = a, d = b$, we necessarily need to consider the points $p, q \in (a, b), p < q$ where $f$ takes minimum value $m$. Thus we have $f(p) = f(q) = m < M = f(a) = f(b)$. Note further that all the values of $f$ in $(p, q)$ are greater than $m$ and hence if $M'$ is maximum value of $f$ in $[p, q]$ then $m < M' < M$. And suppose $M'$ is attained at $r \in (p, q)$. Let $K$ be any number such that $m < K < M' < M$. Then by intermediate value theorem $f$ takes the value $K$ once in each of the intervals $(a, p), (p, r), (r, q), (q, b)$ and this contradicts the hypotheses.
I think the following way may be simpler. Translation of the function doesnot change the generality. So assume that by translating f(x) we make it crosses the $x$ axis. Let denote it by $\tilde f$ By the hypothesis, $\exists x\_1,x\_2\in \mathbb R$ such that $\tilde f(x\_1)=0=\tilde f(x\_2)$ with $x\_1<x\_2$. Moreover there is no another point $x\in\mathbb R$ that $\tilde f(x)=0$. So either $\tilde f\le 0$ or $\tilde f\ge 0$ on $[x\_1,x\_2]$ by extreme value theorem $\tilde f$ takes one of its extreme values at interior of $[x\_1,x\_2]$, according to its sign. And it is unique so we get contradiction. **Why is one of the extremas on $[x\_1,x\_2]$ unique?** **i)** Inductive geometrically: If we were to draw horizontal lines from $x$ axis since the hyphothesis states graph should intersect with these lines exactly twice, until to maxima or minima, there may be no problem but at these extremas the horizontal line can only intersects once. (This explanation is only intuitional, see the figure below) **ii)** More formally (we emphasize the idea in formal way to elaborate the idea), WLOG assume $\tilde f\ge 0$ and we have minimum at boundaries, denote first maximum $c\_1$. Assume we have another maximum at $x=c\_2$. Since $\tilde f$ is continuous at $c\_1,c\_2$ there exist two closed neighborhood $\delta\_1,\delta\_2$, now consider $\delta=min\{\delta\_1,\delta\_2\}$. Observe $\tilde f(\delta\_{c\_1})=[c^{\*}\_1, \tilde f(c\_1)=M]$ and $\tilde f(\delta\_{c\_2})=[c^{\*}\_2,\tilde f(c\_2)=M]$ So in the $y$ axis closed interval $[min\{c^{\*}\_1,c^{\*}\_2\},M]$ every point corresponds to $4$ different value in $x$ axis. **Edit:** About geometric interpretation of uniqueness of one of the extremas. [![enter image description here](https://i.stack.imgur.com/CuGRX.png)](https://i.stack.imgur.com/CuGRX.png)
1,848,216
I need to find a second order linear homogeneous equation with constant coefficients that has the given function as a solution question a) $xe^{-3x}$ question b) $e^{3x} \sin x$ We have learned about the aux equations in second order, and we have touched on the reduction of order process Question $a)$ I see that $-3$ must be a root of the characteristic equation and because there is $a x$ in $xe^{-3x}$ it must be a repeated root, so my solution that I have is $y"-6y+9$ Question $b)$ I have got $y"-6y'+10y=0$
2016/07/04
[ "https://math.stackexchange.com/questions/1848216", "https://math.stackexchange.com", "https://math.stackexchange.com/users/343437/" ]
Suppose $f:[0,1]\to\mathbb{R}$ takes each of its values exactly twice. Consider the self-map FLIP of the interval $[0,1]$ switching the two points where the values of the function are equal. This FLIP a continuous map without fixed points. But any self-map of the closed interval must have a fixed point by (the trivial one-dimensional case of) Brouwer's fixed point theorem. This proves that there is no such function $f$.
Given such a function, $[a,b]$ is partitioned into uncountably many pairs $\{x\_1,x\_2\}$ with $f(x\_1)=f(x\_2)$. Can two pairs $\{x\_1,x\_2\}$ and $\{x\_3,x\_4\}$ overlap? In such a acase we would have wlog $x\_1<x\_3<x\_2<x\_4$. Pick $c$ between $f(x\_1)$ and $f(x\_2)$. By the Intermediate value property, there exists $\xi\in(x\_1,x\_3)$ with $f(\xi)=c$. But such $\xi$ also exists in $(x\_3,x\_2)$ and in $(x\_2,x\_4)$, contradicting the special property of $f$. We conclude that two distinct pairs $\{x\_1,x\_2\}$ and $\{x\_3,x\_4\}$ can only be nested. Then the intersection of the nested closed intervals with these pairs as endpoints is non-empty and contains a point $\bar x\_1$ that cannot occur in a pair $\{\bar x\_1,\bar x\_2\}$.
1,848,216
I need to find a second order linear homogeneous equation with constant coefficients that has the given function as a solution question a) $xe^{-3x}$ question b) $e^{3x} \sin x$ We have learned about the aux equations in second order, and we have touched on the reduction of order process Question $a)$ I see that $-3$ must be a root of the characteristic equation and because there is $a x$ in $xe^{-3x}$ it must be a repeated root, so my solution that I have is $y"-6y+9$ Question $b)$ I have got $y"-6y'+10y=0$
2016/07/04
[ "https://math.stackexchange.com/questions/1848216", "https://math.stackexchange.com", "https://math.stackexchange.com/users/343437/" ]
Suppose $f:[0,1]\to\mathbb{R}$ takes each of its values exactly twice. Consider the self-map FLIP of the interval $[0,1]$ switching the two points where the values of the function are equal. This FLIP a continuous map without fixed points. But any self-map of the closed interval must have a fixed point by (the trivial one-dimensional case of) Brouwer's fixed point theorem. This proves that there is no such function $f$.
I think the following way may be simpler. Translation of the function doesnot change the generality. So assume that by translating f(x) we make it crosses the $x$ axis. Let denote it by $\tilde f$ By the hypothesis, $\exists x\_1,x\_2\in \mathbb R$ such that $\tilde f(x\_1)=0=\tilde f(x\_2)$ with $x\_1<x\_2$. Moreover there is no another point $x\in\mathbb R$ that $\tilde f(x)=0$. So either $\tilde f\le 0$ or $\tilde f\ge 0$ on $[x\_1,x\_2]$ by extreme value theorem $\tilde f$ takes one of its extreme values at interior of $[x\_1,x\_2]$, according to its sign. And it is unique so we get contradiction. **Why is one of the extremas on $[x\_1,x\_2]$ unique?** **i)** Inductive geometrically: If we were to draw horizontal lines from $x$ axis since the hyphothesis states graph should intersect with these lines exactly twice, until to maxima or minima, there may be no problem but at these extremas the horizontal line can only intersects once. (This explanation is only intuitional, see the figure below) **ii)** More formally (we emphasize the idea in formal way to elaborate the idea), WLOG assume $\tilde f\ge 0$ and we have minimum at boundaries, denote first maximum $c\_1$. Assume we have another maximum at $x=c\_2$. Since $\tilde f$ is continuous at $c\_1,c\_2$ there exist two closed neighborhood $\delta\_1,\delta\_2$, now consider $\delta=min\{\delta\_1,\delta\_2\}$. Observe $\tilde f(\delta\_{c\_1})=[c^{\*}\_1, \tilde f(c\_1)=M]$ and $\tilde f(\delta\_{c\_2})=[c^{\*}\_2,\tilde f(c\_2)=M]$ So in the $y$ axis closed interval $[min\{c^{\*}\_1,c^{\*}\_2\},M]$ every point corresponds to $4$ different value in $x$ axis. **Edit:** About geometric interpretation of uniqueness of one of the extremas. [![enter image description here](https://i.stack.imgur.com/CuGRX.png)](https://i.stack.imgur.com/CuGRX.png)
46,310,909
I want to change the attribute "srcset" to "data-srcset" and "srt" to "data-srt" in Drupal 8 responsive images and i didn't find a solution in hours. Any ideas? Thanks. :-) AK
2017/09/19
[ "https://Stackoverflow.com/questions/46310909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2718363/" ]
Well looks like both are not currently possible. As of now I just used a forced way which is hopefully temporary. I have created and used the following base class for hubs: ```cs public abstract class MyHub : Hub { private static Dictionary<string, IHubClients> _clients = new Dictionary<string, IHubClients>(); public override Task OnConnectedAsync() { var c = base.OnConnectedAsync(); _clients.Remove(Name); _clients.Add(Name, Clients); return c; } public static IHubClients GetClients(string Name) { return _clients.GetValueOrDefault(Name); } } ```
1. GlobalHost is gone. You need to inject `IHubContext<THub>` like in [this sample.](https://github.com/aspnet/SignalR-samples/blob/1fa7d8a330e77dcd21ced9220670c8772c1610a7/StockTickR/StockTickRApp/StockTicker.cs#L29) 2. This can be a bug in SignalR alpha1. Can you file an issue on <https://github.com/aspnet/signalr> and include a simplified repro?
24,778
My 2013 Subaru WRX has a 5-speed manual, and I long for it to have a 6th gear when cruising on the highway. A friend has a 2012 Subaru STI with a 6-speed manual, and I noticed his car runs through the gears more quickly to achieve the same speeds. At 3300-3500 RPMs, shouldn't the WRX be able to achieve better gas mileage by keeping the same 5-speed gear ratios, while adding an additional gear to lower RPMs to 2800-3000?
2016/01/15
[ "https://mechanics.stackexchange.com/questions/24778", "https://mechanics.stackexchange.com", "https://mechanics.stackexchange.com/users/7047/" ]
**tl;dr: different gear ratios are a feature, not a bug. Some cars use more gears for acceleration, some use them for better gas mileage. You can't do both.** > > At 3300-3500 RPMs, shouldn't the WRX be able to achieve better gas mileage by keeping the same 5-speed gear ratios, while adding an additional gear to lower RPMs to 2800-3000? > > > You've exposed the classic trade off in transmissions. We want to get the spinning motion of the motor to turn into spinning motion of the wheels. Unfortunately, the engine has a maximum rotational speed (the redline is there for a reason). The gears in the transmission are really just multipliers in the rotational velocity equation. **First, a picture:** In this image, you can see that the larger gear A (being driven by the motor) is driving the smaller gear B (used to turn the wheels). *Yes, I know that there are more bits after this gear but for the sake of discussion let's forget final drives, etc.* [![An animated GIF of a low gear ratio.](https://i.stack.imgur.com/0yOKo.gif)](https://i.stack.imgur.com/0yOKo.gif) In this example, you can see that each turn of gear A results in two turns of gear B. This translates to a gear ratio of 1:2 or 0.5. If you had this gear in your car, you could cruise at very low revs on the highway (but you'd never get up a hill!). **Saying it again, in words:** A low ratio gear will turn the car tires a low number of times for each engine rotation. A high ratio will turn the car times several times per engine rotation. Thus, a high gear ratio at the top end permits a high top speed. It also means that, at highway speeds, the engine revolves less per linear meter of road. Fewer revs == less gasoline burned per second. *Note: sometimes you will about hear "short" and "tall" gears. Short gears are the low speed gears (with high ratios) and tall gears are for high speeds (with low ratios). This inversion of terminology is one of the great joys of trying to discuss transmissions.* However, a high gear ratio has a lower mechanical advantage. This means that it's harder to accelerate the vehicle (tires have to turn faster to get the car to go faster). A fuel efficient gear ratio is also not a fun gear ratio (less zip). When you really want to accelerate quickly, adding gear ratios down low (say a six speed rather than a five speed) lets you stay at a higher mechanical advantage for longer. However, if you're focused on fuel efficiency, you can also take what is effectively a five speed and put a really low gear up top for highway cruising. This will get your mpg numbers up but will be extremely non fun (you might even be below the minimum revs required to spin up the turbo). **Back to the specific cars in question:** From looking at the WRX vs STI gear ratios, it's clear that the WRX has a low ratio first and second gear so that you only have to shift once to reach 60 mph. This is purely an effort to optimize the 0-60 time (marketing. Sigh). In the STI six speed, the gear ratios of the first five gears are spaced pretty evenly between the gear ratios of the first four of the WRX. This means that the STI won't feel that slog through first and second that we five speeders have to labor through. Even the sixth gear of the STI is still a higher ratio than the fifth gear of the WRX. Cruising won't be as relaxed but you'll be better able to accelerate from 50 mph to some higher number....
Most vehicles will only have a single overdrive, where the second to the last gear will be a 1:1 ratio (or something near it). The notable thing here is the Tremec 6-speed transmissions (used in the Camaro, Viper, Corvette, Mustang, and others) which have the double overdrive. The main purpose of *more gears* is to allow the vehicle to stay in the torque/hp range for the trade-off to gain fuel economy. More gears means the engine can be tuned to perform it's best at the smaller rpm range. For instance, with more gears the rpm range in question may be from 1500-2250rpm rather than 1000-3000rpm (for normal operations ... we're excluding *spirited driving* here). If the manufacturer tunes for the smaller range, they can get more out of the engine while maintaining better fuel efficiency. With the broader range the engine has to be able to perform over the complete range, so the tune has to be done to accommodate. Most vehicles will not have a double overdrive because they do not have the torque to maintain the speed at the lower RPMs. Given a 4-cyl engine which, while having great hp output at the higher rpms, does not have the torque needed to successfully propel a car if it were driven at 1500 rpm at 70+ mph. The car would either need to be dropped down a gear to accommodate, or the engine would be lugged with the driver mashing on the pedal ... both of which would defeat the purpose of having more gears in the first place ... that being to gain fuel mileage and drivability.
24,778
My 2013 Subaru WRX has a 5-speed manual, and I long for it to have a 6th gear when cruising on the highway. A friend has a 2012 Subaru STI with a 6-speed manual, and I noticed his car runs through the gears more quickly to achieve the same speeds. At 3300-3500 RPMs, shouldn't the WRX be able to achieve better gas mileage by keeping the same 5-speed gear ratios, while adding an additional gear to lower RPMs to 2800-3000?
2016/01/15
[ "https://mechanics.stackexchange.com/questions/24778", "https://mechanics.stackexchange.com", "https://mechanics.stackexchange.com/users/7047/" ]
Most vehicles will only have a single overdrive, where the second to the last gear will be a 1:1 ratio (or something near it). The notable thing here is the Tremec 6-speed transmissions (used in the Camaro, Viper, Corvette, Mustang, and others) which have the double overdrive. The main purpose of *more gears* is to allow the vehicle to stay in the torque/hp range for the trade-off to gain fuel economy. More gears means the engine can be tuned to perform it's best at the smaller rpm range. For instance, with more gears the rpm range in question may be from 1500-2250rpm rather than 1000-3000rpm (for normal operations ... we're excluding *spirited driving* here). If the manufacturer tunes for the smaller range, they can get more out of the engine while maintaining better fuel efficiency. With the broader range the engine has to be able to perform over the complete range, so the tune has to be done to accommodate. Most vehicles will not have a double overdrive because they do not have the torque to maintain the speed at the lower RPMs. Given a 4-cyl engine which, while having great hp output at the higher rpms, does not have the torque needed to successfully propel a car if it were driven at 1500 rpm at 70+ mph. The car would either need to be dropped down a gear to accommodate, or the engine would be lugged with the driver mashing on the pedal ... both of which would defeat the purpose of having more gears in the first place ... that being to gain fuel mileage and drivability.
If you have 20 gears, you would have to "shorten" each gear (ratio) to "match" the gear it came from and the gear it is going in. So you go through "smaller gears" faster (more gears).
24,778
My 2013 Subaru WRX has a 5-speed manual, and I long for it to have a 6th gear when cruising on the highway. A friend has a 2012 Subaru STI with a 6-speed manual, and I noticed his car runs through the gears more quickly to achieve the same speeds. At 3300-3500 RPMs, shouldn't the WRX be able to achieve better gas mileage by keeping the same 5-speed gear ratios, while adding an additional gear to lower RPMs to 2800-3000?
2016/01/15
[ "https://mechanics.stackexchange.com/questions/24778", "https://mechanics.stackexchange.com", "https://mechanics.stackexchange.com/users/7047/" ]
Most vehicles will only have a single overdrive, where the second to the last gear will be a 1:1 ratio (or something near it). The notable thing here is the Tremec 6-speed transmissions (used in the Camaro, Viper, Corvette, Mustang, and others) which have the double overdrive. The main purpose of *more gears* is to allow the vehicle to stay in the torque/hp range for the trade-off to gain fuel economy. More gears means the engine can be tuned to perform it's best at the smaller rpm range. For instance, with more gears the rpm range in question may be from 1500-2250rpm rather than 1000-3000rpm (for normal operations ... we're excluding *spirited driving* here). If the manufacturer tunes for the smaller range, they can get more out of the engine while maintaining better fuel efficiency. With the broader range the engine has to be able to perform over the complete range, so the tune has to be done to accommodate. Most vehicles will not have a double overdrive because they do not have the torque to maintain the speed at the lower RPMs. Given a 4-cyl engine which, while having great hp output at the higher rpms, does not have the torque needed to successfully propel a car if it were driven at 1500 rpm at 70+ mph. The car would either need to be dropped down a gear to accommodate, or the engine would be lugged with the driver mashing on the pedal ... both of which would defeat the purpose of having more gears in the first place ... that being to gain fuel mileage and drivability.
In most sport-oriented (and heavy towing) vehicles, the point of an extra transmission gear is to keep the engine operating between it's torque peak and HP peak. Thus, most models of vehicles that are base models will have a 5 speed manual (or 3 speed auto), while the sportier or heavy duty versions will have more gears to chose from. Many 6 speed transmissions have relatively similar 1st (perhaps a smidge lower) and 6th gear (perhaps a smidge higher) ratios in comparison to their 5 speed counterparts. If you want to go through the effort, you can change the final drive ratio or tire size to go a little faster at a given engine speed. Semi trucks have 10-18 gears because they need to be able to stay at just the perfect RPM to get max torque, and to be able to get up into the next gear (while the truck is slowing down) and still be close to perfect. Semi transmissions are usually in fact 2 transmissions in a row, and very close attention is paid to final drive ratio so that both transmissions are in a 1:1 gear at 60mph and the engine at it's peak *fuel* efficiency RPM.. Every time the power has to go through a set of gears, some is wasted as heat, and most transmissions in any gear except 4th all the power has to flow through TWO sets.. now multiplied by 2 transmissions, and you can easily lose 30% of your power (and thus fuel economy) Lastly, just because your engine isn't turning as fast does not guarantee it will be more fuel efficient.. typically, the more torque the engine needs to produce, the more fuel it will need per volume of air, reducing it's fuel efficiency, and higher gears will reduce your engine speed, but increase the load on it, and it won't accelerate as fast either. TANSTAAFL.. There ain't no such thing as a free lunch
24,778
My 2013 Subaru WRX has a 5-speed manual, and I long for it to have a 6th gear when cruising on the highway. A friend has a 2012 Subaru STI with a 6-speed manual, and I noticed his car runs through the gears more quickly to achieve the same speeds. At 3300-3500 RPMs, shouldn't the WRX be able to achieve better gas mileage by keeping the same 5-speed gear ratios, while adding an additional gear to lower RPMs to 2800-3000?
2016/01/15
[ "https://mechanics.stackexchange.com/questions/24778", "https://mechanics.stackexchange.com", "https://mechanics.stackexchange.com/users/7047/" ]
**tl;dr: different gear ratios are a feature, not a bug. Some cars use more gears for acceleration, some use them for better gas mileage. You can't do both.** > > At 3300-3500 RPMs, shouldn't the WRX be able to achieve better gas mileage by keeping the same 5-speed gear ratios, while adding an additional gear to lower RPMs to 2800-3000? > > > You've exposed the classic trade off in transmissions. We want to get the spinning motion of the motor to turn into spinning motion of the wheels. Unfortunately, the engine has a maximum rotational speed (the redline is there for a reason). The gears in the transmission are really just multipliers in the rotational velocity equation. **First, a picture:** In this image, you can see that the larger gear A (being driven by the motor) is driving the smaller gear B (used to turn the wheels). *Yes, I know that there are more bits after this gear but for the sake of discussion let's forget final drives, etc.* [![An animated GIF of a low gear ratio.](https://i.stack.imgur.com/0yOKo.gif)](https://i.stack.imgur.com/0yOKo.gif) In this example, you can see that each turn of gear A results in two turns of gear B. This translates to a gear ratio of 1:2 or 0.5. If you had this gear in your car, you could cruise at very low revs on the highway (but you'd never get up a hill!). **Saying it again, in words:** A low ratio gear will turn the car tires a low number of times for each engine rotation. A high ratio will turn the car times several times per engine rotation. Thus, a high gear ratio at the top end permits a high top speed. It also means that, at highway speeds, the engine revolves less per linear meter of road. Fewer revs == less gasoline burned per second. *Note: sometimes you will about hear "short" and "tall" gears. Short gears are the low speed gears (with high ratios) and tall gears are for high speeds (with low ratios). This inversion of terminology is one of the great joys of trying to discuss transmissions.* However, a high gear ratio has a lower mechanical advantage. This means that it's harder to accelerate the vehicle (tires have to turn faster to get the car to go faster). A fuel efficient gear ratio is also not a fun gear ratio (less zip). When you really want to accelerate quickly, adding gear ratios down low (say a six speed rather than a five speed) lets you stay at a higher mechanical advantage for longer. However, if you're focused on fuel efficiency, you can also take what is effectively a five speed and put a really low gear up top for highway cruising. This will get your mpg numbers up but will be extremely non fun (you might even be below the minimum revs required to spin up the turbo). **Back to the specific cars in question:** From looking at the WRX vs STI gear ratios, it's clear that the WRX has a low ratio first and second gear so that you only have to shift once to reach 60 mph. This is purely an effort to optimize the 0-60 time (marketing. Sigh). In the STI six speed, the gear ratios of the first five gears are spaced pretty evenly between the gear ratios of the first four of the WRX. This means that the STI won't feel that slog through first and second that we five speeders have to labor through. Even the sixth gear of the STI is still a higher ratio than the fifth gear of the WRX. Cruising won't be as relaxed but you'll be better able to accelerate from 50 mph to some higher number....
If you have 20 gears, you would have to "shorten" each gear (ratio) to "match" the gear it came from and the gear it is going in. So you go through "smaller gears" faster (more gears).
24,778
My 2013 Subaru WRX has a 5-speed manual, and I long for it to have a 6th gear when cruising on the highway. A friend has a 2012 Subaru STI with a 6-speed manual, and I noticed his car runs through the gears more quickly to achieve the same speeds. At 3300-3500 RPMs, shouldn't the WRX be able to achieve better gas mileage by keeping the same 5-speed gear ratios, while adding an additional gear to lower RPMs to 2800-3000?
2016/01/15
[ "https://mechanics.stackexchange.com/questions/24778", "https://mechanics.stackexchange.com", "https://mechanics.stackexchange.com/users/7047/" ]
**tl;dr: different gear ratios are a feature, not a bug. Some cars use more gears for acceleration, some use them for better gas mileage. You can't do both.** > > At 3300-3500 RPMs, shouldn't the WRX be able to achieve better gas mileage by keeping the same 5-speed gear ratios, while adding an additional gear to lower RPMs to 2800-3000? > > > You've exposed the classic trade off in transmissions. We want to get the spinning motion of the motor to turn into spinning motion of the wheels. Unfortunately, the engine has a maximum rotational speed (the redline is there for a reason). The gears in the transmission are really just multipliers in the rotational velocity equation. **First, a picture:** In this image, you can see that the larger gear A (being driven by the motor) is driving the smaller gear B (used to turn the wheels). *Yes, I know that there are more bits after this gear but for the sake of discussion let's forget final drives, etc.* [![An animated GIF of a low gear ratio.](https://i.stack.imgur.com/0yOKo.gif)](https://i.stack.imgur.com/0yOKo.gif) In this example, you can see that each turn of gear A results in two turns of gear B. This translates to a gear ratio of 1:2 or 0.5. If you had this gear in your car, you could cruise at very low revs on the highway (but you'd never get up a hill!). **Saying it again, in words:** A low ratio gear will turn the car tires a low number of times for each engine rotation. A high ratio will turn the car times several times per engine rotation. Thus, a high gear ratio at the top end permits a high top speed. It also means that, at highway speeds, the engine revolves less per linear meter of road. Fewer revs == less gasoline burned per second. *Note: sometimes you will about hear "short" and "tall" gears. Short gears are the low speed gears (with high ratios) and tall gears are for high speeds (with low ratios). This inversion of terminology is one of the great joys of trying to discuss transmissions.* However, a high gear ratio has a lower mechanical advantage. This means that it's harder to accelerate the vehicle (tires have to turn faster to get the car to go faster). A fuel efficient gear ratio is also not a fun gear ratio (less zip). When you really want to accelerate quickly, adding gear ratios down low (say a six speed rather than a five speed) lets you stay at a higher mechanical advantage for longer. However, if you're focused on fuel efficiency, you can also take what is effectively a five speed and put a really low gear up top for highway cruising. This will get your mpg numbers up but will be extremely non fun (you might even be below the minimum revs required to spin up the turbo). **Back to the specific cars in question:** From looking at the WRX vs STI gear ratios, it's clear that the WRX has a low ratio first and second gear so that you only have to shift once to reach 60 mph. This is purely an effort to optimize the 0-60 time (marketing. Sigh). In the STI six speed, the gear ratios of the first five gears are spaced pretty evenly between the gear ratios of the first four of the WRX. This means that the STI won't feel that slog through first and second that we five speeders have to labor through. Even the sixth gear of the STI is still a higher ratio than the fifth gear of the WRX. Cruising won't be as relaxed but you'll be better able to accelerate from 50 mph to some higher number....
In most sport-oriented (and heavy towing) vehicles, the point of an extra transmission gear is to keep the engine operating between it's torque peak and HP peak. Thus, most models of vehicles that are base models will have a 5 speed manual (or 3 speed auto), while the sportier or heavy duty versions will have more gears to chose from. Many 6 speed transmissions have relatively similar 1st (perhaps a smidge lower) and 6th gear (perhaps a smidge higher) ratios in comparison to their 5 speed counterparts. If you want to go through the effort, you can change the final drive ratio or tire size to go a little faster at a given engine speed. Semi trucks have 10-18 gears because they need to be able to stay at just the perfect RPM to get max torque, and to be able to get up into the next gear (while the truck is slowing down) and still be close to perfect. Semi transmissions are usually in fact 2 transmissions in a row, and very close attention is paid to final drive ratio so that both transmissions are in a 1:1 gear at 60mph and the engine at it's peak *fuel* efficiency RPM.. Every time the power has to go through a set of gears, some is wasted as heat, and most transmissions in any gear except 4th all the power has to flow through TWO sets.. now multiplied by 2 transmissions, and you can easily lose 30% of your power (and thus fuel economy) Lastly, just because your engine isn't turning as fast does not guarantee it will be more fuel efficient.. typically, the more torque the engine needs to produce, the more fuel it will need per volume of air, reducing it's fuel efficiency, and higher gears will reduce your engine speed, but increase the load on it, and it won't accelerate as fast either. TANSTAAFL.. There ain't no such thing as a free lunch
24,778
My 2013 Subaru WRX has a 5-speed manual, and I long for it to have a 6th gear when cruising on the highway. A friend has a 2012 Subaru STI with a 6-speed manual, and I noticed his car runs through the gears more quickly to achieve the same speeds. At 3300-3500 RPMs, shouldn't the WRX be able to achieve better gas mileage by keeping the same 5-speed gear ratios, while adding an additional gear to lower RPMs to 2800-3000?
2016/01/15
[ "https://mechanics.stackexchange.com/questions/24778", "https://mechanics.stackexchange.com", "https://mechanics.stackexchange.com/users/7047/" ]
In most sport-oriented (and heavy towing) vehicles, the point of an extra transmission gear is to keep the engine operating between it's torque peak and HP peak. Thus, most models of vehicles that are base models will have a 5 speed manual (or 3 speed auto), while the sportier or heavy duty versions will have more gears to chose from. Many 6 speed transmissions have relatively similar 1st (perhaps a smidge lower) and 6th gear (perhaps a smidge higher) ratios in comparison to their 5 speed counterparts. If you want to go through the effort, you can change the final drive ratio or tire size to go a little faster at a given engine speed. Semi trucks have 10-18 gears because they need to be able to stay at just the perfect RPM to get max torque, and to be able to get up into the next gear (while the truck is slowing down) and still be close to perfect. Semi transmissions are usually in fact 2 transmissions in a row, and very close attention is paid to final drive ratio so that both transmissions are in a 1:1 gear at 60mph and the engine at it's peak *fuel* efficiency RPM.. Every time the power has to go through a set of gears, some is wasted as heat, and most transmissions in any gear except 4th all the power has to flow through TWO sets.. now multiplied by 2 transmissions, and you can easily lose 30% of your power (and thus fuel economy) Lastly, just because your engine isn't turning as fast does not guarantee it will be more fuel efficient.. typically, the more torque the engine needs to produce, the more fuel it will need per volume of air, reducing it's fuel efficiency, and higher gears will reduce your engine speed, but increase the load on it, and it won't accelerate as fast either. TANSTAAFL.. There ain't no such thing as a free lunch
If you have 20 gears, you would have to "shorten" each gear (ratio) to "match" the gear it came from and the gear it is going in. So you go through "smaller gears" faster (more gears).
49,928,575
I'm looking to design a sorting process/algorithm that shuffles items in a list, but to do so uniquely based on the hash of an input; so that when the same input--essentially a passphrase--is hashed or processed, the same exact shuffling is reproduced. This would need to have the capacity to uniquely shuffle 26^4 things (application is pairing up two lists that are each 26^4 things long, but it only needs to shuffle one of them). Can this be a thing?
2018/04/19
[ "https://Stackoverflow.com/questions/49928575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9671568/" ]
You can use the hash of your input as a seed to a random number generator that you then use to perform the shuffling. If two inputs are the same (have the same hash), then the RNG gets seeded the same way, resulting in the same shuffle.
If you have 26^4 items, there are about 10^240000 possible permutations, requiring a passphrase of at least 1 million characters (or so) to make the permutations guaranteed unique. So no, not really. But! If you just want to permute unpredictably based on the passphrase, just hash it, use the result as the seed of a PRNG, then use the PRNG to do a standard (Fisher-Yates) shuffle of the items. The result will be unique-ish, though not cryptographically strong.
49,928,575
I'm looking to design a sorting process/algorithm that shuffles items in a list, but to do so uniquely based on the hash of an input; so that when the same input--essentially a passphrase--is hashed or processed, the same exact shuffling is reproduced. This would need to have the capacity to uniquely shuffle 26^4 things (application is pairing up two lists that are each 26^4 things long, but it only needs to shuffle one of them). Can this be a thing?
2018/04/19
[ "https://Stackoverflow.com/questions/49928575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9671568/" ]
You can use the hash of your input as a seed to a random number generator that you then use to perform the shuffling. If two inputs are the same (have the same hash), then the RNG gets seeded the same way, resulting in the same shuffle.
One way to do it is to use your seed value as a permutation index. That is, given some seed value, `m`, you generate the mth permutation of those 26^4 elements. For example, the possible permutations of the numbers 1 through 3 are: ``` 123,132,213,231,312,321 ``` The fourth permutation, then, is 231. Eric Lippert did a series on generating permutations some time back. The fourth article in the series shows how to generate the mth permutation. Check it out at <https://ericlippert.com/2013/04/25/producing-permutations-part-four/> The code examples are in C#, but the explanation and code are clear enough that implementing in any other language should be straightforward. This technique will guarantee you a different ordering (permutation) for every seed, provided that the range of the seed is smaller than the total number of possible permutations (26^4)!.
4,066,472
I am studying the Cartesian product of such a graph with other graphs. I want to ask if it has a known name? [![enter image description here](https://i.stack.imgur.com/ZfbEj.png)](https://i.stack.imgur.com/ZfbEj.png) By the way, for some special graphs, is there a good website to check?
2021/03/18
[ "https://math.stackexchange.com/questions/4066472", "https://math.stackexchange.com", "https://math.stackexchange.com/users/708389/" ]
Apparently (according to [this website](https://www.graphclasses.org/smallgraphs.html#nodes6)) this graph is called "X84", or "g6: ElD?" (whatever that means). Some details about this nomenclature have been helpfully provided in [David Scholz's answer](https://math.stackexchange.com/a/4066709/16078).
There is no well established name for this particular graph. However, there is a well known graph which is similar to some extend. It is called the [Banner graph](https://mathworld.wolfram.com/BannerGraph.html) [![enter image description here](https://i.stack.imgur.com/NH9pX.png)](https://i.stack.imgur.com/NH9pX.png) It is obtained by joining a single vertex of the cycle graph $C\_4$ to a [pendant](https://mathworld.wolfram.com/PendantVertex.html) vertex. Our graph is obtained by joining two non-adjacent vertices of $C\_4$ with two pendant vertices. Some comments to the website given by Greg Martin: The string "ElD?" is the graph6 representation of your graph. This format was specified by Brendan McKay [here](https://users.cecs.anu.edu.au/%7Ebdm/data/formats.html). It is used in most computational frameworks, such as Mathematica, SageMath, etc. Using sage, we can parse this format directly into sage graph objects as follows ``` g=Graph("ElD?") g.show() ``` yielding to [![enter image description here](https://i.stack.imgur.com/LKlv8.png)](https://i.stack.imgur.com/LKlv8.png) The string "X84" is the internal name in the database [ISGCI](https://doc.sagemath.org/html/en/reference/graphs/sage/graphs/isgci.html). This can be verified using ``` t = graph_classes.smallgraphs() ``` which returns a set in which "X84" is used for internal reference only.
682,831
I had this question in the homework and i don't get why the answer is right. $B, A \rightarrow B \vDash\_{TAUT} A\ $ is not valid. If there exists a state $v$ such that $v(A) = f$ and $v(B) = t$ then both $B$ and $A \rightarrow B$ are satisfied while $A$ is not. Take for example, $A$ to be $\bot$ and $B$ to be $\top$. That was the answer for the homework. But i could take $A$ to be true and $B$ to be also true so $ A \rightarrow B $ is true. Isn't that right ?
2014/02/20
[ "https://math.stackexchange.com/questions/682831", "https://math.stackexchange.com", "https://math.stackexchange.com/users/91060/" ]
The question seems unclear to me - not the question you asked, the question they asked you ;-) I think the reasoning they are asking about is the following: * given $B$ and $A\to B$, we conclude $A$. This is an invalid deduction for the reasons given in the answer. I don't know what format you are using in your studies but for me $$B\,,\ A\to B\quad\hbox{therefore}\quad A$$ would make more sense than $$B\,,\ A\to B\quad\hbox{and}\quad A\ .$$
I'm assuming that the right symbol to be used is : $\vDash\_{TAUT}$; it means "tautologically implies" : if so, you attempted solution is not the right one. We want to prove that > > $B,A \rightarrow B \vDash\_{TAUT} A$ is not valid, i.e. $B,A \rightarrow B \nvDash\_{TAUT} A$ > > > To show this we need to find a *valuation* $v$ such that both $B$ and $A \rightarrow B$ are satisfied while $A$ is not. If we remeber the truth-functional definition of $\rightarrow$, we have that when $A$ is *false* and $B$ is *true*, then $A \rightarrow B$ is *true*. So, our valuation $v$ must be defined as : > > $v(A) = f$ and $v(B) = t$. > > > With this $v$ we have that $v(B)=v(A \rightarrow B)=t$ and $v(A)=f$, so that : > > $B,A \rightarrow B \nvDash\_{TAUT} A$. > > >
328,085
On a programming site, I noticed <https://stackoverflow.com/questions/37460404/unexplained-increasement-of-variable> a beautiful word use, "increasement." Is there a term for, or how would you refer to, that - where you take a word, and use a different "form" of it. So, you're making up a new "form" of a word which has never been seen before, but it makes sense based on variant "forms" of other words. (This is sometimes done for humorous effect; and small children sometimes do it: in the example at hand it's just plain pretty.) By the way notice I use "form" above ... perhaps it is not the best term (maybe there's another term, something like "tense" or ?) --- Further - relatedly, it occurs to me that children learning language, particularly do this (often humorously to us adults). Surely, there's a term for this when children do it, since there's plenty of academic interest in such things.
2016/05/26
[ "https://english.stackexchange.com/questions/328085", "https://english.stackexchange.com", "https://english.stackexchange.com/users/8286/" ]
Perhaps you mean the process of attaching suffixes and/or prefixes to a root word to make a whole family of related words, like *hand*, *handy*, *handiness*, *unhand*, *unhanded*, and so on. The name for that is ***[agglutination](http://www.merriam-webster.com/dictionary/agglutination)*** and languages that rely on this kind of word growth for their grammar are called *agglutinative*. The word itself is an example of Latin agglutination. > > * the formation of derivational or inflectional words by putting together constituents of which each expresses a single definite meaning. > > > (M-W)
When you make up a new word, generally, it's called a "neologism". Does that fit here? [Neologism](http://www.dictionary.com/browse/neologism): (noun) > > 1. a new word, meaning, usage, or phrase. > 2. the introduction or use of new words or new senses of existing words. > 3. a new doctrine, especially a new interpretation of sacred writings. > 4. Psychiatry. a new word, often consisting of a combination of other words, that is understood only by the speaker: occurring most often in the speech of schizophrenics. > > > (Dictionary.com)
328,085
On a programming site, I noticed <https://stackoverflow.com/questions/37460404/unexplained-increasement-of-variable> a beautiful word use, "increasement." Is there a term for, or how would you refer to, that - where you take a word, and use a different "form" of it. So, you're making up a new "form" of a word which has never been seen before, but it makes sense based on variant "forms" of other words. (This is sometimes done for humorous effect; and small children sometimes do it: in the example at hand it's just plain pretty.) By the way notice I use "form" above ... perhaps it is not the best term (maybe there's another term, something like "tense" or ?) --- Further - relatedly, it occurs to me that children learning language, particularly do this (often humorously to us adults). Surely, there's a term for this when children do it, since there's plenty of academic interest in such things.
2016/05/26
[ "https://english.stackexchange.com/questions/328085", "https://english.stackexchange.com", "https://english.stackexchange.com/users/8286/" ]
When you make up a new word, generally, it's called a "neologism". Does that fit here? [Neologism](http://www.dictionary.com/browse/neologism): (noun) > > 1. a new word, meaning, usage, or phrase. > 2. the introduction or use of new words or new senses of existing words. > 3. a new doctrine, especially a new interpretation of sacred writings. > 4. Psychiatry. a new word, often consisting of a combination of other words, that is understood only by the speaker: occurring most often in the speech of schizophrenics. > > > (Dictionary.com)
Nice answers here already, but the problem with agglutination is that it's a very unusual word that most people will be unfamiliar with. Indeed it sounds rather like the process of adding gluten to something... I would myself go for more of a comedic term which is itself agglutinated: I would call it ***Extenderization***. Everyone can relate to that term and smile at its usage ;)
328,085
On a programming site, I noticed <https://stackoverflow.com/questions/37460404/unexplained-increasement-of-variable> a beautiful word use, "increasement." Is there a term for, or how would you refer to, that - where you take a word, and use a different "form" of it. So, you're making up a new "form" of a word which has never been seen before, but it makes sense based on variant "forms" of other words. (This is sometimes done for humorous effect; and small children sometimes do it: in the example at hand it's just plain pretty.) By the way notice I use "form" above ... perhaps it is not the best term (maybe there's another term, something like "tense" or ?) --- Further - relatedly, it occurs to me that children learning language, particularly do this (often humorously to us adults). Surely, there's a term for this when children do it, since there's plenty of academic interest in such things.
2016/05/26
[ "https://english.stackexchange.com/questions/328085", "https://english.stackexchange.com", "https://english.stackexchange.com/users/8286/" ]
When you make up a new word, generally, it's called a "neologism". Does that fit here? [Neologism](http://www.dictionary.com/browse/neologism): (noun) > > 1. a new word, meaning, usage, or phrase. > 2. the introduction or use of new words or new senses of existing words. > 3. a new doctrine, especially a new interpretation of sacred writings. > 4. Psychiatry. a new word, often consisting of a combination of other words, that is understood only by the speaker: occurring most often in the speech of schizophrenics. > > > (Dictionary.com)
Cobbled together from earlier comments... > > ***Inflection***, formerly **flection** or **accidence**, in linguistics, the change in the form of a word (in English, usually the addition of endings) to mark such distinctions as tense, person, number, gender, mood, voice, and case. > > [(Encyclopædia Britannica)](http://www.britannica.com/topic/inflection) > > > ***Agglutination*** is a process in linguistic morphology derivation in which complex words are formed by stringing together morphemes without changing them in spelling or phonetics. [(Wikipedia)](https://en.wikipedia.org/wiki/Agglutination) > > > *Some people consider agglutination to be a sub-set of inflection, contrasted with fusional inflection.* > > [(reddit/linguistics)](https://www.reddit.com/r/linguistics/comments/1g30ct/whats_the_difference_between_the_terms/) > > > --- The general idea being that agglutinated words always have (meaningful) bits tacked onto them, whereas *some* inflected ones have their form altered by other means. Thus I think ***quicksilver***, for example, is an example of agglutination, whereas ***quickly*** is a simple adverb-forming inflection. I also think agglutinative is more often an attribute of certain *languages* (of which English is not considered to be one), but you inflect *words* (languages aren't usually called "inflective").
328,085
On a programming site, I noticed <https://stackoverflow.com/questions/37460404/unexplained-increasement-of-variable> a beautiful word use, "increasement." Is there a term for, or how would you refer to, that - where you take a word, and use a different "form" of it. So, you're making up a new "form" of a word which has never been seen before, but it makes sense based on variant "forms" of other words. (This is sometimes done for humorous effect; and small children sometimes do it: in the example at hand it's just plain pretty.) By the way notice I use "form" above ... perhaps it is not the best term (maybe there's another term, something like "tense" or ?) --- Further - relatedly, it occurs to me that children learning language, particularly do this (often humorously to us adults). Surely, there's a term for this when children do it, since there's plenty of academic interest in such things.
2016/05/26
[ "https://english.stackexchange.com/questions/328085", "https://english.stackexchange.com", "https://english.stackexchange.com/users/8286/" ]
Perhaps you mean the process of attaching suffixes and/or prefixes to a root word to make a whole family of related words, like *hand*, *handy*, *handiness*, *unhand*, *unhanded*, and so on. The name for that is ***[agglutination](http://www.merriam-webster.com/dictionary/agglutination)*** and languages that rely on this kind of word growth for their grammar are called *agglutinative*. The word itself is an example of Latin agglutination. > > * the formation of derivational or inflectional words by putting together constituents of which each expresses a single definite meaning. > > > (M-W)
Increasement is already a word. * <https://en.wiktionary.org/wiki/increasement> * <http://www.merriam-webster.com/dictionary/increasement> * <http://www.thefreedictionary.com/Increasement> But I would offer this [Calvin and Hobbes](https://en.wikipedia.org/wiki/Calvin_and_Hobbes) strip: ![](https://i.stack.imgur.com/RSHWo.jpg) Although in this case I suppose you're nouning a noun. **Edit:** More seriously, you might consider using the verb [suffixing](https://www.google.com/webhp?&ion=1&espv=2&ie=UTF-8#q=define%3A%20suffixing): > > append, especially as a suffix. > > >
328,085
On a programming site, I noticed <https://stackoverflow.com/questions/37460404/unexplained-increasement-of-variable> a beautiful word use, "increasement." Is there a term for, or how would you refer to, that - where you take a word, and use a different "form" of it. So, you're making up a new "form" of a word which has never been seen before, but it makes sense based on variant "forms" of other words. (This is sometimes done for humorous effect; and small children sometimes do it: in the example at hand it's just plain pretty.) By the way notice I use "form" above ... perhaps it is not the best term (maybe there's another term, something like "tense" or ?) --- Further - relatedly, it occurs to me that children learning language, particularly do this (often humorously to us adults). Surely, there's a term for this when children do it, since there's plenty of academic interest in such things.
2016/05/26
[ "https://english.stackexchange.com/questions/328085", "https://english.stackexchange.com", "https://english.stackexchange.com/users/8286/" ]
Perhaps you mean the process of attaching suffixes and/or prefixes to a root word to make a whole family of related words, like *hand*, *handy*, *handiness*, *unhand*, *unhanded*, and so on. The name for that is ***[agglutination](http://www.merriam-webster.com/dictionary/agglutination)*** and languages that rely on this kind of word growth for their grammar are called *agglutinative*. The word itself is an example of Latin agglutination. > > * the formation of derivational or inflectional words by putting together constituents of which each expresses a single definite meaning. > > > (M-W)
Nice answers here already, but the problem with agglutination is that it's a very unusual word that most people will be unfamiliar with. Indeed it sounds rather like the process of adding gluten to something... I would myself go for more of a comedic term which is itself agglutinated: I would call it ***Extenderization***. Everyone can relate to that term and smile at its usage ;)
328,085
On a programming site, I noticed <https://stackoverflow.com/questions/37460404/unexplained-increasement-of-variable> a beautiful word use, "increasement." Is there a term for, or how would you refer to, that - where you take a word, and use a different "form" of it. So, you're making up a new "form" of a word which has never been seen before, but it makes sense based on variant "forms" of other words. (This is sometimes done for humorous effect; and small children sometimes do it: in the example at hand it's just plain pretty.) By the way notice I use "form" above ... perhaps it is not the best term (maybe there's another term, something like "tense" or ?) --- Further - relatedly, it occurs to me that children learning language, particularly do this (often humorously to us adults). Surely, there's a term for this when children do it, since there's plenty of academic interest in such things.
2016/05/26
[ "https://english.stackexchange.com/questions/328085", "https://english.stackexchange.com", "https://english.stackexchange.com/users/8286/" ]
Perhaps you mean the process of attaching suffixes and/or prefixes to a root word to make a whole family of related words, like *hand*, *handy*, *handiness*, *unhand*, *unhanded*, and so on. The name for that is ***[agglutination](http://www.merriam-webster.com/dictionary/agglutination)*** and languages that rely on this kind of word growth for their grammar are called *agglutinative*. The word itself is an example of Latin agglutination. > > * the formation of derivational or inflectional words by putting together constituents of which each expresses a single definite meaning. > > > (M-W)
Cobbled together from earlier comments... > > ***Inflection***, formerly **flection** or **accidence**, in linguistics, the change in the form of a word (in English, usually the addition of endings) to mark such distinctions as tense, person, number, gender, mood, voice, and case. > > [(Encyclopædia Britannica)](http://www.britannica.com/topic/inflection) > > > ***Agglutination*** is a process in linguistic morphology derivation in which complex words are formed by stringing together morphemes without changing them in spelling or phonetics. [(Wikipedia)](https://en.wikipedia.org/wiki/Agglutination) > > > *Some people consider agglutination to be a sub-set of inflection, contrasted with fusional inflection.* > > [(reddit/linguistics)](https://www.reddit.com/r/linguistics/comments/1g30ct/whats_the_difference_between_the_terms/) > > > --- The general idea being that agglutinated words always have (meaningful) bits tacked onto them, whereas *some* inflected ones have their form altered by other means. Thus I think ***quicksilver***, for example, is an example of agglutination, whereas ***quickly*** is a simple adverb-forming inflection. I also think agglutinative is more often an attribute of certain *languages* (of which English is not considered to be one), but you inflect *words* (languages aren't usually called "inflective").
328,085
On a programming site, I noticed <https://stackoverflow.com/questions/37460404/unexplained-increasement-of-variable> a beautiful word use, "increasement." Is there a term for, or how would you refer to, that - where you take a word, and use a different "form" of it. So, you're making up a new "form" of a word which has never been seen before, but it makes sense based on variant "forms" of other words. (This is sometimes done for humorous effect; and small children sometimes do it: in the example at hand it's just plain pretty.) By the way notice I use "form" above ... perhaps it is not the best term (maybe there's another term, something like "tense" or ?) --- Further - relatedly, it occurs to me that children learning language, particularly do this (often humorously to us adults). Surely, there's a term for this when children do it, since there's plenty of academic interest in such things.
2016/05/26
[ "https://english.stackexchange.com/questions/328085", "https://english.stackexchange.com", "https://english.stackexchange.com/users/8286/" ]
Increasement is already a word. * <https://en.wiktionary.org/wiki/increasement> * <http://www.merriam-webster.com/dictionary/increasement> * <http://www.thefreedictionary.com/Increasement> But I would offer this [Calvin and Hobbes](https://en.wikipedia.org/wiki/Calvin_and_Hobbes) strip: ![](https://i.stack.imgur.com/RSHWo.jpg) Although in this case I suppose you're nouning a noun. **Edit:** More seriously, you might consider using the verb [suffixing](https://www.google.com/webhp?&ion=1&espv=2&ie=UTF-8#q=define%3A%20suffixing): > > append, especially as a suffix. > > >
Nice answers here already, but the problem with agglutination is that it's a very unusual word that most people will be unfamiliar with. Indeed it sounds rather like the process of adding gluten to something... I would myself go for more of a comedic term which is itself agglutinated: I would call it ***Extenderization***. Everyone can relate to that term and smile at its usage ;)
328,085
On a programming site, I noticed <https://stackoverflow.com/questions/37460404/unexplained-increasement-of-variable> a beautiful word use, "increasement." Is there a term for, or how would you refer to, that - where you take a word, and use a different "form" of it. So, you're making up a new "form" of a word which has never been seen before, but it makes sense based on variant "forms" of other words. (This is sometimes done for humorous effect; and small children sometimes do it: in the example at hand it's just plain pretty.) By the way notice I use "form" above ... perhaps it is not the best term (maybe there's another term, something like "tense" or ?) --- Further - relatedly, it occurs to me that children learning language, particularly do this (often humorously to us adults). Surely, there's a term for this when children do it, since there's plenty of academic interest in such things.
2016/05/26
[ "https://english.stackexchange.com/questions/328085", "https://english.stackexchange.com", "https://english.stackexchange.com/users/8286/" ]
Increasement is already a word. * <https://en.wiktionary.org/wiki/increasement> * <http://www.merriam-webster.com/dictionary/increasement> * <http://www.thefreedictionary.com/Increasement> But I would offer this [Calvin and Hobbes](https://en.wikipedia.org/wiki/Calvin_and_Hobbes) strip: ![](https://i.stack.imgur.com/RSHWo.jpg) Although in this case I suppose you're nouning a noun. **Edit:** More seriously, you might consider using the verb [suffixing](https://www.google.com/webhp?&ion=1&espv=2&ie=UTF-8#q=define%3A%20suffixing): > > append, especially as a suffix. > > >
Cobbled together from earlier comments... > > ***Inflection***, formerly **flection** or **accidence**, in linguistics, the change in the form of a word (in English, usually the addition of endings) to mark such distinctions as tense, person, number, gender, mood, voice, and case. > > [(Encyclopædia Britannica)](http://www.britannica.com/topic/inflection) > > > ***Agglutination*** is a process in linguistic morphology derivation in which complex words are formed by stringing together morphemes without changing them in spelling or phonetics. [(Wikipedia)](https://en.wikipedia.org/wiki/Agglutination) > > > *Some people consider agglutination to be a sub-set of inflection, contrasted with fusional inflection.* > > [(reddit/linguistics)](https://www.reddit.com/r/linguistics/comments/1g30ct/whats_the_difference_between_the_terms/) > > > --- The general idea being that agglutinated words always have (meaningful) bits tacked onto them, whereas *some* inflected ones have their form altered by other means. Thus I think ***quicksilver***, for example, is an example of agglutination, whereas ***quickly*** is a simple adverb-forming inflection. I also think agglutinative is more often an attribute of certain *languages* (of which English is not considered to be one), but you inflect *words* (languages aren't usually called "inflective").
328,085
On a programming site, I noticed <https://stackoverflow.com/questions/37460404/unexplained-increasement-of-variable> a beautiful word use, "increasement." Is there a term for, or how would you refer to, that - where you take a word, and use a different "form" of it. So, you're making up a new "form" of a word which has never been seen before, but it makes sense based on variant "forms" of other words. (This is sometimes done for humorous effect; and small children sometimes do it: in the example at hand it's just plain pretty.) By the way notice I use "form" above ... perhaps it is not the best term (maybe there's another term, something like "tense" or ?) --- Further - relatedly, it occurs to me that children learning language, particularly do this (often humorously to us adults). Surely, there's a term for this when children do it, since there's plenty of academic interest in such things.
2016/05/26
[ "https://english.stackexchange.com/questions/328085", "https://english.stackexchange.com", "https://english.stackexchange.com/users/8286/" ]
Cobbled together from earlier comments... > > ***Inflection***, formerly **flection** or **accidence**, in linguistics, the change in the form of a word (in English, usually the addition of endings) to mark such distinctions as tense, person, number, gender, mood, voice, and case. > > [(Encyclopædia Britannica)](http://www.britannica.com/topic/inflection) > > > ***Agglutination*** is a process in linguistic morphology derivation in which complex words are formed by stringing together morphemes without changing them in spelling or phonetics. [(Wikipedia)](https://en.wikipedia.org/wiki/Agglutination) > > > *Some people consider agglutination to be a sub-set of inflection, contrasted with fusional inflection.* > > [(reddit/linguistics)](https://www.reddit.com/r/linguistics/comments/1g30ct/whats_the_difference_between_the_terms/) > > > --- The general idea being that agglutinated words always have (meaningful) bits tacked onto them, whereas *some* inflected ones have their form altered by other means. Thus I think ***quicksilver***, for example, is an example of agglutination, whereas ***quickly*** is a simple adverb-forming inflection. I also think agglutinative is more often an attribute of certain *languages* (of which English is not considered to be one), but you inflect *words* (languages aren't usually called "inflective").
Nice answers here already, but the problem with agglutination is that it's a very unusual word that most people will be unfamiliar with. Indeed it sounds rather like the process of adding gluten to something... I would myself go for more of a comedic term which is itself agglutinated: I would call it ***Extenderization***. Everyone can relate to that term and smile at its usage ;)
74,209,759
I have a problem with my price regex which I'm trying to change. I want it to allow numbers like: * 11111,64 * 2 122,00 * 123,12 * 123 345,23 For now I have something like this, but it won't accept numbers without spaces. `'^\d{1,3}( \d{3}){0,10}[,]*[.]*([0-9]{0,2'})?$'` I tried changing `( \d{3})` to `(\s{0,1}\d{3})` but it still doesn't work :(
2022/10/26
[ "https://Stackoverflow.com/questions/74209759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20340538/" ]
i think you should add `<div class="image-conatiner"></div>` to have more control on images in your model don't leave them without any element to control them. check the code below ```css .Card_Badge { box-sizing: border-box; max-height: 350px; overflow: hidden; } .image-container{ display:flex; } ``` ```html <div class="Card_Badge"> <div class="image-container"> <img alt="Badge Background" src="https://via.placeholder.com/100" style="max-width: 100px;max-height: 146px;display: flex;z-index: 1;"> <img alt="Secured Card" src="https://via.placeholder.com/100" "> </div> </div> ```
here this should work fine, use the gap property to set how far apart you want the elements to be. ``` .Card_Badge { box-sizing: border-box; max-height: 350px; overflow: hidden; display: flex; flex-flow: row nowrap; gap: 5em; } ```
57,440,254
I have created a `Django` app which is using `Celery` for task processing. It’s working fine locally but when I pushed it to `Heroku`, I found that app cannot connect to Celery worker. I can see worker is running without any problem. ``` $ heroku ps === web (Free): gunicorn my_django_project.wsgi --log-file - (1) web.1: up 2019/08/10 11:54:19 +0530 (~ 1m ago) === worker (Free): celery -A my_django_project worker -l info (1) worker.1: up 2019/08/10 11:54:19 +0530 (~ 1m ago) ``` But when I checked the logs I found this error message ``` 2019-08-10T06:04:30.402781+00:00 app[worker.1]: [2019-08-10 06:04:30,402: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 111] Connection refused. 2019-08-10T06:04:30.402801+00:00 app[worker.1]: Trying again in 32.00 seconds... ``` Seems like app cannot connect to celery worker. **Project directory structure** ``` Project | ├── data/ ├── db.sqlite3 ├── manage.py ├── Procfile ├── README.md ├── requirements.txt ├── my_app/ │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── tasks.py │ ├── templates │ ├── tests.py │ ├── urls.py │ └── views.py ├── my_django_project/ │ ├── celery.py │ ├── __init__.py │ ├── settings.py │ ├── staticfiles │ ├── urls.py │ └── wsgi.py ├── runtime.txt └── static/ ``` **Procfile** ``` web: gunicorn my_django_project.wsgi --log-file - worker: celery -A my_django_project worker -l info ``` **celery.py** ``` from __future__ import absolute_import, unicode_literals import os from celery import Celery #set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', my_django_project.settings') app = Celery(my_django_project) # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) ``` **tasks.py** ``` from celery import shared_task @shared_task def task1(): // do stuff return results ``` [![enter image description here](https://i.stack.imgur.com/lOcL8.png)](https://i.stack.imgur.com/lOcL8.png)
2019/08/10
[ "https://Stackoverflow.com/questions/57440254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/653397/" ]
`amqp://guest:**@127.0.0.1:5672` Refers to the backend celery tries to use, you need to setup a backend either rabbitMQ, Redis or something else. [The docs](https://docs.celeryproject.org/en/latest/getting-started/first-steps-with-celery.html#choosing-a-broker)
Celery requires a solution to send and receive messages; usually this comes in the form of a separate service called a message broker. You can choose * RabbitMQ * Redis * Amazon SQS (experimental) You can test this locally before setting up in Heroku by specifying a broker in your celery config, e.g.: `app = Celery('tasks', broker='pyamqp://guest@localhost//')` For this to work, you will need to have already started up your broker locally. For redis that would be with: `pip install -U "celery[redis]"` then set the broker url to the location of the redis database (default 'redis://localhost:6379/0') the url follows this format: redis://:password@hostname:port/db\_number * then run `redis-server` * then run your celery worker * then start your django app Once you're comfortable with all that, use the Heroku add ons to select your broker of choice (there are many options, e.g. Redis Cloud). Then update your environment variables to use the add-on backend url in your heroku environment vars. This will be of a format like: `redis://p%[email protected]:PORT_NUMBER/0`
221,740
When using an exposed filter in a view, any data that doesn't meet the filter is removed from the page. Partially for SEO reasons, I'd like all the data to load (and stay in the HTML), but then the exposed filters will simply use CSS to hide the data that doesn't match the filter. Does that make sense? Is it possible?
2016/11/29
[ "https://drupal.stackexchange.com/questions/221740", "https://drupal.stackexchange.com", "https://drupal.stackexchange.com/users/17836/" ]
`getcwd` gets the current working directory, i.e. the one you're executing the script from. If you need `DRUPAL_ROOT` to refer to the root of your Drupal installation, run the script from that directory, not the one that contains your module. If you want to execute it from the module directory, fix the paths to the includes in your script.
Your code has issue in first line it-self: ``` define('DRUPAL_ROOT', getcwd()); ``` `getcwd()` as per described on [PHP.net](http://php.net/manual/en/function.getcwd.php) > > Gets the current working directory > > > Because of `getcwd()` your Drupal Root directory is set to your module directory and PHP isn't able to find `bootstrap.inc` and `database.inc`.
39,195,024
Hello should I do like this: ``` new BitmapFont().draw("Hello World!"); new BitmapFont().draw("Hello Universe!"); ``` or ``` BitmapFont font = new BitmapFont(); font.draw("Hello World!"); font.draw("Hello Universe!"); ``` Does it matter for performance?
2016/08/28
[ "https://Stackoverflow.com/questions/39195024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6700693/" ]
The first option isn't only worse, it is not an option at all. It leaks memory. If you're doing this every frame, your game will crash pretty quickly on a phone. Anything that implements Disposable absolutely must be disposed before you lose the reference, or it leaks. The second option is fine for most cases. If you have dozens of strings that have the same text on every frame, you can use BitmapFontCaches that you create from your BitmapFont (`someStringCache = new BitmapFontCache(bitmapFont);`) so the glyph arrangement for the string doesn't have to be recalculated every time you draw it. I wouldn't bother with this unless you find that your game's framerate is too low and you've narrowed the problem down to CPU.
Definitely second option is better, because the first one creates 2 objects when 1 is really needed. On small scale this does not matter, but if all Java calls were made like the first one, garbage collector would take much more time (more objects - more time GC needs) and if there was a heavy load on constuctor it would significantly slow an application. Object are in memory so the more objects you have the more memory is needed, that is why libGDX want to reuse the same Batch object everytime it is practical. It is also less readable and configurable (if you need to set something in BitmapFont it is better to do it once). You should also check for objects that implements `Disposable`, you have to dispose them manually fe. BitmapFont, Batch, Stage, Texture.
49,355,894
I have some Git-related doubt. I have done some changes from master branch and by mistake I have commited to master branch. I did: ``` git add. git commit "my changed" ``` But I could not push to the master branch due to some issues. So I have created another branch and from that branch I did push. But I was getting conflicts. So my doubts are: 1. If I created a new branch again from master whether I will have all committed changes from the master? 2. What step do I need to follow to fix this conflict? 3. What do I need to do to make my master branch as same as server? 4. If I clone the project again, will it have my committed changes or same as server? Can I do like? Clone again the master, checkout to the branch I got conflict, do: ``` git merge master ``` From there and fix the conflicts?
2018/03/19
[ "https://Stackoverflow.com/questions/49355894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7130330/" ]
1. Just hit `git log` to find if you have all commits from master if your HEAD is ahead or at same level as master which means you have all commits from master (or) If you have created a branch from master `git checkout master` `git checkout -b new-branch` then YES. 2. When you have conflicts you have to resolve using `git mergetool` Check `git status` whether you have resolved your conflicts 3. If you want to get local master reset to remote master branch `git checkout -B master origin/master` 4. If you had pushed the commit on other branch instead of master, it will be on the remote other branch not on origin/master. So when you are pushing new changes to remote custom branch, `git fetch origin master` `git checkout custom-branch` `git rebase -i origin/master` `git commit -m 'Your new feature stuff'` `git push origin custom-branch` This will only push to remote custom-branch not to master. Create a merge request for merging to remote master.
1. If i created a new branch again from master whether i will have all committed changes from the master? > > Yes > > > 2. What step i need to follow to fix this conflict? > > EIther rebase/merge your branch withh/into master and resolve the > conflicts using > > > ``` git rebase origin/master git merge origin/master ``` 3. What i need to do to make my master branch as same as server? > > Reset the branch with master using > > > ``` git reset --hard origin/master ``` 4. if i clone the project again , will it have my commiitted changes or same as server? > > Yes > > > To conclude, in order to resolve your problems on the branch currently, you should do the following ``` git checkout branchA git merge origin/master // resolve conflicts here git commit git push ```
57,199,918
(I use Java) I want to sort a sublist of objects by a property using a Collator so that is sorted by alphabetical order but ignoring accents. Problem is I have tried different things and none work. This sorts the sublists but doesn't ignore accents: ``` newList.subList(0, 5).sort(Comparator.comparing(element -> element.getValue())); ``` This is the collator I want to use: ``` Collator spCollator = Collator.getInstance(new Locale("es", "ES")); ``` I expect the output to be a sublist sorted by alphabetical order by the property which you can access with .getValue() ignoring the accents.
2019/07/25
[ "https://Stackoverflow.com/questions/57199918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11458457/" ]
Collator is also a Comparator. If the elements are String: ``` List<String> list = Arrays.asList("abc", "xyz", "bde"); Collator spCollator = Collator.getInstance(new Locale("es", "ES")); list.sort(spCollator); ``` If the elements are custom Object: ``` List<Element> list = Arrays.asList(new Element("abc"), new Element("xyz"), new Element("bde"), new Element("rew"), new Element("aER"), new Element("Tre"), new Element("ade")); list.subList(0, 4).sort(new MyElementComparator()); System.out.println(list); private static class MyElementComparator implements Comparator<Element>{ Collator spCollator = Collator.getInstance(new Locale("es", "ES")); public int compare (Element e1, Element e2){ return spCollator.compare(e1.getValue(), e2.getValue()); } } ``` Or the lambda way: ``` List<Element> list = Arrays.asList(new Element("abc"), new Element("xyz"), new Element("bde"), new Element("rew"), new Element("aER"), new Element("Tre"), new Element("ade")); Collator spCollator = Collator.getInstance(new Locale("es", "ES")); list.subList(0, 4).sort((e1, e2)-> spCollator.compare(e1.getValue(), e2.getValue())); System.out.println(list); ```
Instead of using `Comparator.comparing`, you create a lambda to first extract the value and then use the collator to compare. ``` Collator spCollator = Collator.getInstance(new Locale("es", "ES")); newList.subList(0, 5).sort((e1, e2) -> spCollator.compare(e1.getValue(), e2.getValue())); ```
2,804,659
Is it possible to programmatically find the default currency symbol for the current locale in BlackBerry?
2010/05/10
[ "https://Stackoverflow.com/questions/2804659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/631/" ]
You might have an empty line in the beginning of that php file. Maybe space before start of PHP script
See lines 60, 61, and 63, and how they come *after* all your HTML? Put them before instead.
2,804,659
Is it possible to programmatically find the default currency symbol for the current locale in BlackBerry?
2010/05/10
[ "https://Stackoverflow.com/questions/2804659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/631/" ]
Cookies and Headers must be set before any output is sent to the browser. Try moving your login script to the top of the page. You might want to also consider sanitizing your queries to prevent malicious activity.
You might have an empty line in the beginning of that php file. Maybe space before start of PHP script
2,804,659
Is it possible to programmatically find the default currency symbol for the current locale in BlackBerry?
2010/05/10
[ "https://Stackoverflow.com/questions/2804659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/631/" ]
You might have an empty line in the beginning of that php file. Maybe space before start of PHP script
When PHP says it's already sent the headers, it means that some text has already been output by the script (or the script that called it). This includes any and all error messages. When the FIRST piece of text is output by PHP it sends its headers, but not before. In order to get HTTP cookies (part of the headers) to be set, the cookies must be sent before any text is output. What you can do is enable output buffering using [`ob_start`](http://php.net/manual/en/function.ob-start.php), and [`ob_end_flush`](http://www.php.net/manual/en/function.ob-end-flush.php), and other output-control functions. What you can also do is to set the [php.ini variable](http://php.net/manual/en/ini.core.php) to automatically send the cookie header when it outputs text.
2,804,659
Is it possible to programmatically find the default currency symbol for the current locale in BlackBerry?
2010/05/10
[ "https://Stackoverflow.com/questions/2804659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/631/" ]
You might have an empty line in the beginning of that php file. Maybe space before start of PHP script
If you do not have output\_buffering enabled in your php.ini you will get this error because it will start sending the html right away. You need to edit your php.ini to enable output buffering.
2,804,659
Is it possible to programmatically find the default currency symbol for the current locale in BlackBerry?
2010/05/10
[ "https://Stackoverflow.com/questions/2804659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/631/" ]
You might have an empty line in the beginning of that php file. Maybe space before start of PHP script
Is this on Windows? Check for BOM. Open it in Notepad and save it as ANSI to see if it helps.
2,804,659
Is it possible to programmatically find the default currency symbol for the current locale in BlackBerry?
2010/05/10
[ "https://Stackoverflow.com/questions/2804659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/631/" ]
Cookies and Headers must be set before any output is sent to the browser. Try moving your login script to the top of the page. You might want to also consider sanitizing your queries to prevent malicious activity.
See lines 60, 61, and 63, and how they come *after* all your HTML? Put them before instead.
2,804,659
Is it possible to programmatically find the default currency symbol for the current locale in BlackBerry?
2010/05/10
[ "https://Stackoverflow.com/questions/2804659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/631/" ]
Cookies and Headers must be set before any output is sent to the browser. Try moving your login script to the top of the page. You might want to also consider sanitizing your queries to prevent malicious activity.
When PHP says it's already sent the headers, it means that some text has already been output by the script (or the script that called it). This includes any and all error messages. When the FIRST piece of text is output by PHP it sends its headers, but not before. In order to get HTTP cookies (part of the headers) to be set, the cookies must be sent before any text is output. What you can do is enable output buffering using [`ob_start`](http://php.net/manual/en/function.ob-start.php), and [`ob_end_flush`](http://www.php.net/manual/en/function.ob-end-flush.php), and other output-control functions. What you can also do is to set the [php.ini variable](http://php.net/manual/en/ini.core.php) to automatically send the cookie header when it outputs text.
2,804,659
Is it possible to programmatically find the default currency symbol for the current locale in BlackBerry?
2010/05/10
[ "https://Stackoverflow.com/questions/2804659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/631/" ]
Cookies and Headers must be set before any output is sent to the browser. Try moving your login script to the top of the page. You might want to also consider sanitizing your queries to prevent malicious activity.
If you do not have output\_buffering enabled in your php.ini you will get this error because it will start sending the html right away. You need to edit your php.ini to enable output buffering.
2,804,659
Is it possible to programmatically find the default currency symbol for the current locale in BlackBerry?
2010/05/10
[ "https://Stackoverflow.com/questions/2804659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/631/" ]
Cookies and Headers must be set before any output is sent to the browser. Try moving your login script to the top of the page. You might want to also consider sanitizing your queries to prevent malicious activity.
Is this on Windows? Check for BOM. Open it in Notepad and save it as ANSI to see if it helps.
276,025
Let's say I have multiple lines ***similar*** to below in a file. ``` Turbo is a cat. cats are good. cats are not dog. Coco is a black cat. cats are furry. cats are not dog. ``` now, if want to `grep` all the `^.*cat` but want to specially mention to capture till first (or nth) occurrence of the word `cat`. Desired Output: ``` Turbo is a cat Coco is a black cat *blah is a so and so cat* ``` How can I `grep` it? PS: I would love to have an answer using `grep` (or its other variants) only. PS: I don't want to grep `^.*cat.` and then do any operation to remove the **"."** . I want a generic answer.
2016/04/12
[ "https://unix.stackexchange.com/questions/276025", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/106632/" ]
`grep` only selects lines based on the regular expression specified and prints them. I think you are forced to pipe the output lines and use an additional command to do the job. Usually you would use `sed` or `awk` to do the job without `grep`, because they can both select lines and replace strings. There is a solution below using `awk`: ``` awk -v word=cat -v n=2 'BEGIN {wordlength=length(word);} {line=$0;outputline="";position=index(line,word);for (i=1;position>0 && i<=n; i++) { outputline=outputline substr(line,1,position+wordlength-1);line=substr(line,position+wordlength);position=index(line,word); } if (i!=1) {print outputline;}}' ``` You should set `word` to the string to search and the `n` to the number of occurrences wanted. The test: ``` $ awk -v word=cat -v n=2 'BEGIN {wordlength=length(word);} {line=$0;outputline="";position=index(line,word);for (i=1;position>0 && i<=n; i++) { outputline=outputline substr(line,1,position+wordlength-1);line=substr(line,position+wordlength);position=index(line,word); } if (i!=1) {print outputline;}}' file Turbo is a cat. cat Coco is a black cat. cat ```
Here's a `sed` solution (e.g. print up to and including the 2nd occurrence; replace `2` with your no.): ``` sed -n 's/cat/&\ /2 t print d :print P' infile ``` This disables autoprinting via `-n` and attempts to replace the 2nd occurrence of `cat` with `cat`+ a newline character. If the substitution is successful it branches to `:print` and `P`rints up to the newline, otherwise the line is `d`eleted. --- With `gnu sed` you could write it as a one liner (e.g. print up to and including the 5th occurrence): ``` sed -n 's/cat/&\n/5;tt;d;:t;P' infile ```
276,025
Let's say I have multiple lines ***similar*** to below in a file. ``` Turbo is a cat. cats are good. cats are not dog. Coco is a black cat. cats are furry. cats are not dog. ``` now, if want to `grep` all the `^.*cat` but want to specially mention to capture till first (or nth) occurrence of the word `cat`. Desired Output: ``` Turbo is a cat Coco is a black cat *blah is a so and so cat* ``` How can I `grep` it? PS: I would love to have an answer using `grep` (or its other variants) only. PS: I don't want to grep `^.*cat.` and then do any operation to remove the **"."** . I want a generic answer.
2016/04/12
[ "https://unix.stackexchange.com/questions/276025", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/106632/" ]
With **POSIX grep**, you can only choose between printing the whole line, or not printing the line content at all. If you want to transform the line, you need to use another tool such as sed or awk. To print up to the first occurrence of `cat`: ``` sed -n 's/cat.*/cat/' awk 'sub(/cat.*/,"")' ``` Printing up to the *N*th occurrence is more complicated. ``` sed -n 's/cat/&\ /3; T; P' awk 'gsub(/cat/,"&\n") >= 3 {split($0, a, "\n"); printf "%s%s%s\n", a[1], a[2], a[3]}' ``` With **GNU grep**, you can use the `-o` option to print only the matched part of the line. Use the `-P` option to activate Perl syntax, so that [non-greedy quantifiers](http://perldoc.perl.org/perlre.html#Quantifiers) are available. ``` grep -P -o '^(.*?cat){1}' ``` Replace the number in braces by the number *n* of the last occurrence of `cat` to be printed. While it's possible to express the same thing with extended regular expressions (`-E`), this requires a complex regexp, whose size is exponential in the size of the part to count (`cat` here).
`grep` only selects lines based on the regular expression specified and prints them. I think you are forced to pipe the output lines and use an additional command to do the job. Usually you would use `sed` or `awk` to do the job without `grep`, because they can both select lines and replace strings. There is a solution below using `awk`: ``` awk -v word=cat -v n=2 'BEGIN {wordlength=length(word);} {line=$0;outputline="";position=index(line,word);for (i=1;position>0 && i<=n; i++) { outputline=outputline substr(line,1,position+wordlength-1);line=substr(line,position+wordlength);position=index(line,word); } if (i!=1) {print outputline;}}' ``` You should set `word` to the string to search and the `n` to the number of occurrences wanted. The test: ``` $ awk -v word=cat -v n=2 'BEGIN {wordlength=length(word);} {line=$0;outputline="";position=index(line,word);for (i=1;position>0 && i<=n; i++) { outputline=outputline substr(line,1,position+wordlength-1);line=substr(line,position+wordlength);position=index(line,word); } if (i!=1) {print outputline;}}' file Turbo is a cat. cat Coco is a black cat. cat ```
276,025
Let's say I have multiple lines ***similar*** to below in a file. ``` Turbo is a cat. cats are good. cats are not dog. Coco is a black cat. cats are furry. cats are not dog. ``` now, if want to `grep` all the `^.*cat` but want to specially mention to capture till first (or nth) occurrence of the word `cat`. Desired Output: ``` Turbo is a cat Coco is a black cat *blah is a so and so cat* ``` How can I `grep` it? PS: I would love to have an answer using `grep` (or its other variants) only. PS: I don't want to grep `^.*cat.` and then do any operation to remove the **"."** . I want a generic answer.
2016/04/12
[ "https://unix.stackexchange.com/questions/276025", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/106632/" ]
With **POSIX grep**, you can only choose between printing the whole line, or not printing the line content at all. If you want to transform the line, you need to use another tool such as sed or awk. To print up to the first occurrence of `cat`: ``` sed -n 's/cat.*/cat/' awk 'sub(/cat.*/,"")' ``` Printing up to the *N*th occurrence is more complicated. ``` sed -n 's/cat/&\ /3; T; P' awk 'gsub(/cat/,"&\n") >= 3 {split($0, a, "\n"); printf "%s%s%s\n", a[1], a[2], a[3]}' ``` With **GNU grep**, you can use the `-o` option to print only the matched part of the line. Use the `-P` option to activate Perl syntax, so that [non-greedy quantifiers](http://perldoc.perl.org/perlre.html#Quantifiers) are available. ``` grep -P -o '^(.*?cat){1}' ``` Replace the number in braces by the number *n* of the last occurrence of `cat` to be printed. While it's possible to express the same thing with extended regular expressions (`-E`), this requires a complex regexp, whose size is exponential in the size of the part to count (`cat` here).
Here's a `sed` solution (e.g. print up to and including the 2nd occurrence; replace `2` with your no.): ``` sed -n 's/cat/&\ /2 t print d :print P' infile ``` This disables autoprinting via `-n` and attempts to replace the 2nd occurrence of `cat` with `cat`+ a newline character. If the substitution is successful it branches to `:print` and `P`rints up to the newline, otherwise the line is `d`eleted. --- With `gnu sed` you could write it as a one liner (e.g. print up to and including the 5th occurrence): ``` sed -n 's/cat/&\n/5;tt;d;:t;P' infile ```
4,211,470
I have a PHP page called `test.php` on which I link to a dynamic image called `image.php` as follows: ``` echo "<img src=\"image.php?ID=abc&X=123\" align=\"absmiddle\" style=\"margin:5px;\"><br>"; ``` The image file takes `ID` and `X` as GET parameters, and uses them to `include` an existing static image from my server. A header is sent telling the server to interpret the file as a jpeg. I want to prevent users from being able to pull the image by visiting `http://mydomain.com/image.php?ID=/abc&X=123`, all while allowing that image to be viewed in `test.php` and other pages on my server. How do I accomplish this? So far, I've tried many sorts of `.htaccess` mods and rewrites, of which the closest in relevance to my concerns is [the one shown on this page](http://bit.ly/aLM8jQ). Nothing has worked; please help!
2010/11/18
[ "https://Stackoverflow.com/questions/4211470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/438585/" ]
It is not possible, because what your browser does to show the image is **direct access**. There will be a lot of advices about analysing `HTTP_REFERER`, but it will be a bad decisions, since this header is optional and in several circumstances it can be cutted off by firewall, antivirus, proxy, etc.
I) Use sessions: test.php: ``` <?php session_start(); //.... $_SESSION["allow_images"]="yes"; echo "<img src=\"image.php?ID=abc&X=123\" align=\"absmiddle\" style=\"margin:5px;\"><br>"; ?> ``` image.php: ``` <?php session_start(); if(isset($_SESSION["allow_images"]) { // render image unset($_SESSION["allow_images"]); } else { // throw error/ show dummy image /etc } ?> ``` II) Second solution (not foolproof): Inside image.php ``` $ref=$_SERVER["HTTP_REFERER"]; if($ref == "http://yoursite.com/path/test.php") { // get image parameters and render image } else { // throw error or maybe render a dummy image with just few bytes }; ``` Note that HTTP\_REFERER can easily be spoofed. --- Earlier Wrong solution: Use variables in test.php ``` $allow_image="yes"; echo "<img src=\"image.php?ID=abc&X=123\" align=\"absmiddle\" style=\"margin:5px;\"><br>"; ``` And test for isset($allow\_images) in image.php before rendering. Would have worked only if image.php was included as romanusfatuus pointed out.
6,566,027
I'm trying to put a `QVBoxLayout` inside a `QScrollArea` in order for it to be scrollable vertically. However items don't seem to be added to it. I saw a suggestion that I ought to create an inner widget that the ScrollArea uses and to place the layout inside that, although it doesn't seem to have worked. My structure is supposed to look like this: ``` +------------------------------- | QScrollArea(realmScroll) | +---------------------------- | | QWidget(realmScrollInner) | | +------------------------- | | | QVBoxLayout(realmLayout) ``` And the code to do this: ``` # Irrelevant, added for context (this works) centralWidget = QWidget(self) self.container = QVBoxLayout(centralWidget) centralWidget.setLayout(self.container) self.setCentralWidget(centralWidget) # Where trouble starts self.realmScroll = QScrollArea(self.container.widget()) self.realmScroll.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.realmLayout = QVBoxLayout(self.container.widget()) self.realmScrollInner = QWidget(self.realmScroll) self.realmScrollInner.setLayout(self.realmLayout) self.realmScroll.setWidget(self.realmScrollInner) self.container.addWidget(self.realmScroll) # Doesn't add to realmLayout self.realmLayout.addWidget(QLabel("test")) ``` I'm still learning Qt (2 days in), so in-depth answers to where I'm going wrong would be appreciated. **Update**: It seems that the `addWidget(QLabel())` works right up until the `realmScrollInner` has been set as `realmScroll`'s widget. Since I'd like to add elements after the UI has been displayed I have to do this, which I'm not sure is really correct: ``` self.realmLayout.addWidget(QLabel("test")) # realmScrollInner bound to realmScroll realmScroll.setWidget(realmScrollInner) self.container.addWidget(realmScroll) # Access realmScroll's widget and then layout to add realmScroll.widget().layout().addWidget(QLabel("test")) ``` But if you remove that first call to `addWidget` before the widget has been bound (so the layout has no widgets), then bind to the ScrollArea widgets added afterwards are not displayed. Perhaps the ScrollArea needs repainting (although I don't see a method for that)? **Update 2**: Calling `repaint()` on realmScroll or its contained widget does nothing, as does calling `activate/update()` on the layout.
2011/07/03
[ "https://Stackoverflow.com/questions/6566027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2025/" ]
It turned out that I was lead down a wrong path by putting the layout as the layout of a widget. The actual way to do this is as simple as: ``` scrollarea = QScrollArea(parent.widget()) layout = QVBoxLayout(scrollarea) realmScroll.setWidget(layout.widget()) layout.addWidget(QLabel("Test")) ``` Which I'm pretty sure I tried originally, but hey it's working. *However* this adds an issue that the layout's items are shrunk vertically instead of causing the scrollarea to add a scrollbar.
Try calling ``` self.realmScroll.setWidgetResizable(True) ```
6,566,027
I'm trying to put a `QVBoxLayout` inside a `QScrollArea` in order for it to be scrollable vertically. However items don't seem to be added to it. I saw a suggestion that I ought to create an inner widget that the ScrollArea uses and to place the layout inside that, although it doesn't seem to have worked. My structure is supposed to look like this: ``` +------------------------------- | QScrollArea(realmScroll) | +---------------------------- | | QWidget(realmScrollInner) | | +------------------------- | | | QVBoxLayout(realmLayout) ``` And the code to do this: ``` # Irrelevant, added for context (this works) centralWidget = QWidget(self) self.container = QVBoxLayout(centralWidget) centralWidget.setLayout(self.container) self.setCentralWidget(centralWidget) # Where trouble starts self.realmScroll = QScrollArea(self.container.widget()) self.realmScroll.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.realmLayout = QVBoxLayout(self.container.widget()) self.realmScrollInner = QWidget(self.realmScroll) self.realmScrollInner.setLayout(self.realmLayout) self.realmScroll.setWidget(self.realmScrollInner) self.container.addWidget(self.realmScroll) # Doesn't add to realmLayout self.realmLayout.addWidget(QLabel("test")) ``` I'm still learning Qt (2 days in), so in-depth answers to where I'm going wrong would be appreciated. **Update**: It seems that the `addWidget(QLabel())` works right up until the `realmScrollInner` has been set as `realmScroll`'s widget. Since I'd like to add elements after the UI has been displayed I have to do this, which I'm not sure is really correct: ``` self.realmLayout.addWidget(QLabel("test")) # realmScrollInner bound to realmScroll realmScroll.setWidget(realmScrollInner) self.container.addWidget(realmScroll) # Access realmScroll's widget and then layout to add realmScroll.widget().layout().addWidget(QLabel("test")) ``` But if you remove that first call to `addWidget` before the widget has been bound (so the layout has no widgets), then bind to the ScrollArea widgets added afterwards are not displayed. Perhaps the ScrollArea needs repainting (although I don't see a method for that)? **Update 2**: Calling `repaint()` on realmScroll or its contained widget does nothing, as does calling `activate/update()` on the layout.
2011/07/03
[ "https://Stackoverflow.com/questions/6566027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2025/" ]
OK, I just got done fighting with this. Here's a widget that can go into a scroll area (scrollarea->setWidget) and work correctly. It contains a QVBoxLayout and a list of label/listwidget pairs, each in their own little horizontal layout, and it does pretty much what you'd want. The important thing was reading the QScrollArea docs section on Size Hints and Layouts, and finding the bit where having the sizeContraint QLayout::SetMinAndMaxSize on the layout would be necessary. ``` class MappingDisplayWidget : public QWidget { Q_OBJECT public: explicit MappingDisplayWidget(QWidget *parent = 0); void addFile(QString name); private: QVBoxLayout *m_layout; QMap<QString, QListWidget *> m_mappings; }; MappingDisplayWidget::MappingDisplayWidget(QWidget *parent) : QWidget(parent) { m_layout = new QVBoxLayout; m_layout->setSizeConstraint(QLayout::SetMinAndMaxSize); setLayout(m_layout); } void MappingDisplayWidget::addFile(QString name) { if (m_mappings.find(name) == m_mappings.end()) { QWidget *widg = new QWidget; QHBoxLayout *lay = new QHBoxLayout; widg->setLayout(lay); QLabel *nlab = new QLabel(name); lay->addWidget(nlab); QListWidget *list = new QListWidget; lay->addWidget(list); m_layout->addWidget(widg); m_mappings[name] = list; } } ``` I keep pointers to the list widgets so that I can add stuff to them later, and that works fine.
Try calling ``` self.realmScroll.setWidgetResizable(True) ```
6,566,027
I'm trying to put a `QVBoxLayout` inside a `QScrollArea` in order for it to be scrollable vertically. However items don't seem to be added to it. I saw a suggestion that I ought to create an inner widget that the ScrollArea uses and to place the layout inside that, although it doesn't seem to have worked. My structure is supposed to look like this: ``` +------------------------------- | QScrollArea(realmScroll) | +---------------------------- | | QWidget(realmScrollInner) | | +------------------------- | | | QVBoxLayout(realmLayout) ``` And the code to do this: ``` # Irrelevant, added for context (this works) centralWidget = QWidget(self) self.container = QVBoxLayout(centralWidget) centralWidget.setLayout(self.container) self.setCentralWidget(centralWidget) # Where trouble starts self.realmScroll = QScrollArea(self.container.widget()) self.realmScroll.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.realmLayout = QVBoxLayout(self.container.widget()) self.realmScrollInner = QWidget(self.realmScroll) self.realmScrollInner.setLayout(self.realmLayout) self.realmScroll.setWidget(self.realmScrollInner) self.container.addWidget(self.realmScroll) # Doesn't add to realmLayout self.realmLayout.addWidget(QLabel("test")) ``` I'm still learning Qt (2 days in), so in-depth answers to where I'm going wrong would be appreciated. **Update**: It seems that the `addWidget(QLabel())` works right up until the `realmScrollInner` has been set as `realmScroll`'s widget. Since I'd like to add elements after the UI has been displayed I have to do this, which I'm not sure is really correct: ``` self.realmLayout.addWidget(QLabel("test")) # realmScrollInner bound to realmScroll realmScroll.setWidget(realmScrollInner) self.container.addWidget(realmScroll) # Access realmScroll's widget and then layout to add realmScroll.widget().layout().addWidget(QLabel("test")) ``` But if you remove that first call to `addWidget` before the widget has been bound (so the layout has no widgets), then bind to the ScrollArea widgets added afterwards are not displayed. Perhaps the ScrollArea needs repainting (although I don't see a method for that)? **Update 2**: Calling `repaint()` on realmScroll or its contained widget does nothing, as does calling `activate/update()` on the layout.
2011/07/03
[ "https://Stackoverflow.com/questions/6566027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2025/" ]
It turned out that I was lead down a wrong path by putting the layout as the layout of a widget. The actual way to do this is as simple as: ``` scrollarea = QScrollArea(parent.widget()) layout = QVBoxLayout(scrollarea) realmScroll.setWidget(layout.widget()) layout.addWidget(QLabel("Test")) ``` Which I'm pretty sure I tried originally, but hey it's working. *However* this adds an issue that the layout's items are shrunk vertically instead of causing the scrollarea to add a scrollbar.
OK, I just got done fighting with this. Here's a widget that can go into a scroll area (scrollarea->setWidget) and work correctly. It contains a QVBoxLayout and a list of label/listwidget pairs, each in their own little horizontal layout, and it does pretty much what you'd want. The important thing was reading the QScrollArea docs section on Size Hints and Layouts, and finding the bit where having the sizeContraint QLayout::SetMinAndMaxSize on the layout would be necessary. ``` class MappingDisplayWidget : public QWidget { Q_OBJECT public: explicit MappingDisplayWidget(QWidget *parent = 0); void addFile(QString name); private: QVBoxLayout *m_layout; QMap<QString, QListWidget *> m_mappings; }; MappingDisplayWidget::MappingDisplayWidget(QWidget *parent) : QWidget(parent) { m_layout = new QVBoxLayout; m_layout->setSizeConstraint(QLayout::SetMinAndMaxSize); setLayout(m_layout); } void MappingDisplayWidget::addFile(QString name) { if (m_mappings.find(name) == m_mappings.end()) { QWidget *widg = new QWidget; QHBoxLayout *lay = new QHBoxLayout; widg->setLayout(lay); QLabel *nlab = new QLabel(name); lay->addWidget(nlab); QListWidget *list = new QListWidget; lay->addWidget(list); m_layout->addWidget(widg); m_mappings[name] = list; } } ``` I keep pointers to the list widgets so that I can add stuff to them later, and that works fine.
267,319
On the block layout page, I added the "Site Branding" block twice, once for normal use (all nodes except content type *landing page*) and once for landing page use (all nodes of content type *landing page*). I themed the block using the twig template **block--system-branding-block.html.twig**, but this modifies both blocks. Is there a way to get more specific and create a twig template for each block, or should I re-create the landing page block some other way so that I can use a different template? **EDIT:** My goal is to actually change the HTML of the block, so I can't use a pure CSS approach.
2018/08/10
[ "https://drupal.stackexchange.com/questions/267319", "https://drupal.stackexchange.com", "https://drupal.stackexchange.com/users/5147/" ]
There's a few things you can do. Here's three. 1. Consider using a pure CSS approach. If you look at the body element for your page there may well be different classes you can use to make different selectors for styling the block. Modern CSS, particularly with the availability of :before and :after pseudo selectors, is incredibly powerful and you very often don't need custom HTML to adjust styling for different cases. 2. You can also implement [hook\_theme\_suggestions\_alter](https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21theme.api.php/function/hook_theme_suggestions_alter/8.2.x) in your theme (in the file `mytheme.theme`) to supply alternative template suggestions based on the current path, for example. Following [this example](https://drupal.stackexchange.com/a/248097/13727), your code might look like: ``` function THEME_NAME_theme_suggestions_block_alter(array &$suggestions, array $variables) { $current_path = \Drupal::service('path.current')->getPath(); $result = \Drupal::service('path.alias_manager')->getAliasByPath($current_path); $path_alias = trim($result, '/'); $path_alias = str_replace('/', '-', $path_alias); $path_alias = str_replace('-', '_', $path_alias); $id = $variables['id']; $suggestions[] = 'block__path_alias__'.$path_alias; $suggestions[] = 'block__' . $id . '__path_alias__'.$path_alias; } ``` 3. Another option would be to create a second variant of the site branding block then use the option in Drupal's block system which lets you turn blocks on or off by content type.
Try this module [Block Content Machine Name](https://www.drupal.org/project/block_content_machine_name) Will provide additional template suggestion like `block--block-content--[MACHINE_NAME].html.twig`.
18,409,476
We've been trying to "componentize" our Sitecore solution as we move forward, in prep for transitioning to Page Editor usage (Woot! Finally!), but we're still practically working primarily with Page templates that may be inheritance-based composites of page specific fields, plus 1:many of these componentized templates. An example of how this looks in our solution is below -- Banner Feature Carousel and Featured Cartoon are some of these new components we're creating: ![Base templates showing components](https://i.stack.imgur.com/ylDNc.png) In the interest of trying to move away from using Sitecore.Context.Item (as I was recently reminded by [this post](http://intothecore.cassidy.dk/2013/08/the-page-template-mistake.html)) I've started filling in the Datasource template field on the sublayouts for the new components, and it seems like I've got the appropriate connections made between presentation details, the Sitecore sublayout and the .NET code file (as far as I can tell; again, we're newer to working this way). I've also tried setting up a base class for these components as per [this post by Nick Allen](http://www.sitecore.net/belgie/Community/Best-Practice-Blogs/Nick-Allen/Posts/2012/03/Introduction-to-Sitecore-Parameter-Templates.aspx), but here's where I'm running into a problem: When I execute my code, this base class is finding the component Sublayout appropriately (the whole "this.Parent as Sublayout" thing) but, when I go to interrogate the Sublayout.Datasource property, it's an empty string. Here's my code (so far) for this base class: ``` public class ComponentBase : System.Web.UI.UserControl { private Sublayout Sublayout { get { return Parent as Sublayout; } } public Item DataSourceItem { get { return Sublayout != null && !String.IsNullOrEmpty(Sublayout.DataSource) ? Sitecore.Context.Database.GetItem(Sublayout.DataSource) : Sitecore.Context.Item; } } } ``` I'm apparently missing some interplay between the Datasource Template field in the Sitecore sublayout, and how that actually translates to a datasource. Is it because these component templates are being used to compose Page templates? I was thinking that the datasource would just ultimately resolve to the Page template on which the component in question was currently being used, but perhaps that's my misunderstanding. If anyone could give me any hints of things to check or point me to any resources I might use to get further, I'd appreciate it. I've done quite a bit of asking the Googs, myself, but am just not getting anything that's helping. Thank you in advance, Sitecore friends!
2013/08/23
[ "https://Stackoverflow.com/questions/18409476", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1404101/" ]
It looks like you have configured the allowed templates for your sublayout in the steps you describe above. This basically tells Sitecore; 'allow user to select items based on these templates for this sublayout'. This alone does not set up the data source on items using the sublayout. You still need to go into the presentation details for any items using this sublayout, select the sublayout and then set its datasource property (within the content editor go to **Presentation > Details > [Sublayout] > Data Source**). My [answer to this question](https://stackoverflow.com/questions/17835166/render-child-items-with-their-own-layout-in-a-carousel-control/17836887#17836887) gives the source code needed to retrieve the datasource item and to iterate through the sitecore controls on your sublayout setting all of their `Item` propertys. **Here is the code:** ``` public class SublayoutBase : UserControl { private Item _dataSource; public Item DataSource { get { if (_dataSource == null) { if (Parent is Sublayout) { _dataSource = Sitecore.Context.Database.GetItem(((Sublayout)Parent).DataSource); } if (_dataSource == null) { _dataSource = Sitecore.Context.Item; } } return _dataSource; } } protected override void OnLoad(EventArgs e) { foreach (Control c in Controls) { SetFieldRenderers(DataSource, c); } base.OnLoad(e); } private void SetFieldRenderers(Item item, Control control) { if (item != null) { var ctrl = control as Sitecore.Web.UI.WebControl; if (ctrl != null && !string.IsNullOrEmpty(ctrl.DataSource)) { //don't set the source item if the DataSource has already been set. return; } if (control is FieldRenderer) { var fr = (FieldRenderer)control; fr.Item = item; } else if (control is Image) { var img = (Image)control; img.Item = item; } else if (control is Link) { var link = (Link)control; link.Item = item; } else if (control is Text) { var text = (Text)control; text.Item = item; } else { foreach (Control childControl in control.Controls) { SetFieldRenderers(item, childControl); } } } } } ```
When you start using sublayouts on which you will set your datasource try to use the marketplace "Sublayout Parameter Helper". When you use the class they provide as base class and have set everything up right in your Sitecore Environment you will find yourself having a "this.DatasourceItem" -> which will contain your datasource Item, or the context Item if none is given. <http://marketplace.sitecore.net/en/Modules/Sub_Layout_Parameter_Helper.aspx> To find out more on how datasource works, try searching on <http://sdn.sitecore.net>. There is alot of documentation available that should get you in the right direction. Generally it will be enough to just add a datasource in the sublayout that you can access in your sublayout. When you read a datasource from a sublayout all it will do is check if the datasource field on that sublayout is filled and will return you information regarding this datasource. So when you add a new component to a page using the page editor (for example a sublayout for a news article) and you have a datasource template defined and filled in during adding this components, you will see that when you check the presentation details on that page a sublyaout with a datasource has been added. The datasource will point to a folder in which you will find an item based on the datasource template you specified on your sublayout. You should also double check this, cause if no datasource is present on the added sublayout it will be obvious you can't access it from your code.
18,409,476
We've been trying to "componentize" our Sitecore solution as we move forward, in prep for transitioning to Page Editor usage (Woot! Finally!), but we're still practically working primarily with Page templates that may be inheritance-based composites of page specific fields, plus 1:many of these componentized templates. An example of how this looks in our solution is below -- Banner Feature Carousel and Featured Cartoon are some of these new components we're creating: ![Base templates showing components](https://i.stack.imgur.com/ylDNc.png) In the interest of trying to move away from using Sitecore.Context.Item (as I was recently reminded by [this post](http://intothecore.cassidy.dk/2013/08/the-page-template-mistake.html)) I've started filling in the Datasource template field on the sublayouts for the new components, and it seems like I've got the appropriate connections made between presentation details, the Sitecore sublayout and the .NET code file (as far as I can tell; again, we're newer to working this way). I've also tried setting up a base class for these components as per [this post by Nick Allen](http://www.sitecore.net/belgie/Community/Best-Practice-Blogs/Nick-Allen/Posts/2012/03/Introduction-to-Sitecore-Parameter-Templates.aspx), but here's where I'm running into a problem: When I execute my code, this base class is finding the component Sublayout appropriately (the whole "this.Parent as Sublayout" thing) but, when I go to interrogate the Sublayout.Datasource property, it's an empty string. Here's my code (so far) for this base class: ``` public class ComponentBase : System.Web.UI.UserControl { private Sublayout Sublayout { get { return Parent as Sublayout; } } public Item DataSourceItem { get { return Sublayout != null && !String.IsNullOrEmpty(Sublayout.DataSource) ? Sitecore.Context.Database.GetItem(Sublayout.DataSource) : Sitecore.Context.Item; } } } ``` I'm apparently missing some interplay between the Datasource Template field in the Sitecore sublayout, and how that actually translates to a datasource. Is it because these component templates are being used to compose Page templates? I was thinking that the datasource would just ultimately resolve to the Page template on which the component in question was currently being used, but perhaps that's my misunderstanding. If anyone could give me any hints of things to check or point me to any resources I might use to get further, I'd appreciate it. I've done quite a bit of asking the Googs, myself, but am just not getting anything that's helping. Thank you in advance, Sitecore friends!
2013/08/23
[ "https://Stackoverflow.com/questions/18409476", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1404101/" ]
It looks like you have configured the allowed templates for your sublayout in the steps you describe above. This basically tells Sitecore; 'allow user to select items based on these templates for this sublayout'. This alone does not set up the data source on items using the sublayout. You still need to go into the presentation details for any items using this sublayout, select the sublayout and then set its datasource property (within the content editor go to **Presentation > Details > [Sublayout] > Data Source**). My [answer to this question](https://stackoverflow.com/questions/17835166/render-child-items-with-their-own-layout-in-a-carousel-control/17836887#17836887) gives the source code needed to retrieve the datasource item and to iterate through the sitecore controls on your sublayout setting all of their `Item` propertys. **Here is the code:** ``` public class SublayoutBase : UserControl { private Item _dataSource; public Item DataSource { get { if (_dataSource == null) { if (Parent is Sublayout) { _dataSource = Sitecore.Context.Database.GetItem(((Sublayout)Parent).DataSource); } if (_dataSource == null) { _dataSource = Sitecore.Context.Item; } } return _dataSource; } } protected override void OnLoad(EventArgs e) { foreach (Control c in Controls) { SetFieldRenderers(DataSource, c); } base.OnLoad(e); } private void SetFieldRenderers(Item item, Control control) { if (item != null) { var ctrl = control as Sitecore.Web.UI.WebControl; if (ctrl != null && !string.IsNullOrEmpty(ctrl.DataSource)) { //don't set the source item if the DataSource has already been set. return; } if (control is FieldRenderer) { var fr = (FieldRenderer)control; fr.Item = item; } else if (control is Image) { var img = (Image)control; img.Item = item; } else if (control is Link) { var link = (Link)control; link.Item = item; } else if (control is Text) { var text = (Text)control; text.Item = item; } else { foreach (Control childControl in control.Controls) { SetFieldRenderers(item, childControl); } } } } } ```
If you are using Sitecore 7 update 1 you can actually now use the attributes. From the Release Notes: > > To make it easier to get the data source for a sublayout from > code-behind, the data source is now transferred to the sublayout > control in a "sc\_datasource" attribute. (320768) > > > To get the data source from code, simply refer to > this.Attributes["sc\_datasource"]; > > >
51,738,902
I am using vuejs as a drop in for some minor functionality in a Laravel app (i.e. not components) and for some reason that I'm yet to discover `v-model` is not working. Here's my base layout blade file that was generated via `php artisan make:auth`, contents mostly removed as irrelevant: **resources/views/layouts/app.blade.php** ``` <!DOCTYPE html> <html lang="{{ str_replace('_', '-', app()->getLocale()) }}"> <head> <!-- css imports etc. --> </head> <body> <div id="app"> <nav class="navbar navbar-expand-md navbar-light navbar-laravel"> <!-- nav menu --> </nav> <main class="py-4"> @yield('content') </main> </div> @stack('scripts') <---- Javascript goes here! </body> </html> ``` Here's the file where v-model is being used and not working, again, irrelevant parts have been removed: **resources/views/instructors/create.blade.php** ``` @extends('layouts.app') @section('content') <div class="container"> <div class="row justify-content-center"> <div class="col-md-8"> <div class="card"> <div class="card-body"> <div class="card-title"> <h2>vue: @{{ message }}</h2> <-- This works <div> <input type="text" v-model="message"> <-- Blank!!? </div> </div> <!-- more html --> </div> </div> </div> </div> </div> @endsection @push('scripts') <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script> var app = new Vue({ el: '#app', data: { message: 'Hello Vue!' } }); </script> @endpush ``` The input field which `v-model="message"` is bound to is completely empty, however, when outputting `message` via curly braces I can see it's value. This is what it looks like: [![enter image description here](https://i.stack.imgur.com/c9MoM.png)](https://i.stack.imgur.com/c9MoM.png) Any ideas what's going wrong? I have checked the console and Vue dev tools and no errors show up, in fact nothing shows up at all in Vue dev tools - an issue perhaps? I copy pasted these code snippets from the Vue docs introduction to make sure I wasn't doing something silly. I have tried setting the data attribute inside the Vue instance as a function returning an object but it makes no difference. I also have the code working here: <https://jsfiddle.net/eywraw8t/249625/> where the input field shows the value of `message` as I am expecting it to work. I wouldn't consider myself a Vue pro but I'm no beginner and I cannot quite figure out what's going on. Any help would be appreciated, thanks! ### Update Thanks to everyone who answered. Made a silly mistake... I forgot that there is some JS that is pulled in, in the `<head>` when running `make:auth` - this includes Vue by default. I forgot to look properly here as assumed it would be prior to `</body>`. I believe the two JS scrips were conflicting which was causing the issue. See `head` below: ``` <!DOCTYPE html> <html lang="{{ str_replace('_', '-', app()->getLocale()) }}"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- CSRF Token --> <meta name="csrf-token" content="{{ csrf_token() }}"> <title>{{ config('app.name', 'Laravel') }}</title> <!-- Scripts --> <script src="{{ asset('js/app.js') }}" defer></script> <-- Vue included here <!-- Fonts --> <link rel="dns-prefetch" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet" type="text/css"> <!-- Styles --> <link href="{{ asset('css/app.css') }}" rel="stylesheet"> </head> ``` I commented the script out and it's working fine now.
2018/08/08
[ "https://Stackoverflow.com/questions/51738902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/648247/" ]
For vue.js 2 use the following: ```html <html> <body> <div id="app"> <h1>Vue: @{{message}}</h1> <input v-model="message"> </div> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script type="text/javascript"> var app = new Vue({ el: '#app', data: { message: 'Hello Vue!' } }); </script> </body> </html> ``` For more details how to work on v-model: [Laracasts\_episodes\_2](https://laracasts.com/series/learn-vue-2-step-by-step/episodes/2)
try the following code ```html @extends('layouts.app') @section('content') <div class="container"> <div class="row justify-content-center"> <div class="col-md-8"> <div class="card"> <div class="card-body"> <div class="card-title"> <div id="app"> <template> <div> <div class="card-title"> <h2> Add Instructor </h2> <h2>vue: @{{ message }}</h2> <div> <input type="text" v-model="message"> </div> </div> </div> </template> </div> </div> <!-- more html --> </div> </div> </div> </div> </div> @endsection @push('script') <script> var app = new Vue({ el: '#app', data: { message: 'Hello Vue!' }, }); </script> @endpush ```
29,644,539
I have a button with an svg as a background. The `:hover` selector works fine but when I give it a transition, the button first gets smaller and then jumps back to the original size. How do I stop this behavior? here's my code: ```css a { width: 250px; display: block; color: rgba(0, 0, 0, .9); text-decoration: none } .prod-ueber .cta-wrapper { position: absolute; left: 310px; width: 100px; top: 45px; z-index: 5 } .info-btn, .korb-btn { width: 50px; height: 50px; background-repeat: no-repeat; background-size: 100%; float: left; transition: background .4s ease; } .info-btn { background-image: url(http://imgh.us/info-btn.svg); } .korb-btn { background-image: url(http://imgh.us/korb-btn.svg); margin-left: 12px; } .info-btn:hover, .info-btn:active, .info-btn:focus { background-image: url(http://imgh.us/info-btn_h.svg); } .korb-btn:hover, .korb-btn:active, .korb-btn:focus { background-image: url(http://imgh.us/korb-btn_h.svg); } ``` ```html <a href="#"> <div class="prod-ueber"> <img src="http://dummyimage.com/" height="290" width="426" alt="Minze" class="img-responsive"> <h3 class="Artikelname">Malve</h3> <small>Description</small> <hr> <h5 class="preis">€ 1,79</h5> <div class="cta-wrapper"> <a href="#" class="info-btn"></a> <a href="#" class="korb-btn"></a> </div> </div> <!-- produkt --> </a> ```
2015/04/15
[ "https://Stackoverflow.com/questions/29644539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4507540/" ]
You can use a workaround by adding `background-image` for the `pseudo` element ```css a { width: 250px; display: block; color: rgba(0, 0, 0, .9); text-decoration: none } .prod-ueber .cta-wrapper { position: absolute; left: 310px; width: 100px; top: 45px; z-index: 5 } .info-btn, .korb-btn { width: 50px; height: 50px; background-repeat: no-repeat; background-size: 100%; float: left; position: relative; overflow:hidden; } .info-btn { background-image: url(http://imgh.us/info-btn.svg); } .korb-btn { background-image: url(http://imgh.us/korb-btn.svg); margin-left: 12px; } .info-btn:before, .korb-btn:before { content: ''; width: 100%; height: 100%; position: absolute; background-size: 100% auto; opacity: 0; transition: .4s ease; } .info-btn:before { background-image: url(http://imgh.us/info-btn_h.svg); } .korb-btn:before { background-image: url(http://imgh.us/korb-btn_h.svg); } .info-btn:hover:before, .info-btn:active:before, .info-btn:focus:before { opacity: 1; } .korb-btn:hover:before, .korb-btn:active:before, .korb-btn:focus:before { opacity: 1; } ``` ```html <a href="#"> <div class="prod-ueber"> <img src="http://dummyimage.com/" height="290" width="426" alt="Minze" class="img-responsive"> <h3 class="Artikelname">Malve</h3> <small>Description</small> <hr> <h5 class="preis">€ 1,79</h5> <div class="cta-wrapper"> <a href="#" class="info-btn"></a> <a href="#" class="korb-btn"></a> </div> </div> </a> ```
Instead of setting the background of the image you can just set in the svg element itself. It might make you html a bit bigger but you can set the **<svg>** in a **[template](https://stackoverflow.com/questions/27954250/moving-to-svg-icons-how-to-separate-them-from-the-code/28029642#28029642).** First lets just use a svg instead of background. (svg is xhtml so you can just paste it in html) ```css #Ebene_1 circle { transition: fill .4s, stroke .4s; } #Ebene_1:hover circle { fill: #ffe; } #Ebene_1:hover path { fill: #b61910; } ``` ```html <p>We can use the svg inside our html :D</p> <svg version="1.1" id="Ebene_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="60.1px" height="60.1px" viewBox="0 0 60.1 60.1"> <circle fill="#B61910" stroke="#B61910" stroke-width="1.5" stroke-miterlimit="10" cx="30.1" cy="30.1" r="29.3" /> <path fill="#FFFFFF" d="M32.3,14c1.6,0,3.2,1.6,3.2,3.2S33.9,22,30.7,22c-1.6,0-3.2-1.6-3.2-3.2C29.2,15.6,30.7,14,32.3,14z M26,45.8c-1.6,0-3.2-1.6-1.6-6.4l1.6-7.9c0-1.6,0-1.6,0-1.6s-3.2,1.6-4.8,1.6v-1.6c4.8-3.2,9.5-4.8,11.1-4.8 c1.6,0,1.6,1.6,1.6,4.8l-1.6,7.9c0,1.6,0,1.6,0,1.6s1.6,0,3.2-1.6l1.6,1.6C32.3,44.2,27.6,45.8,26,45.8z" /> <rect x="8.2" y="14.2" fill="none" width="36.5" height="31.8" /> </svg> <p>and it wil :hover. <br> Added some transitions to.</p> ```
29,644,539
I have a button with an svg as a background. The `:hover` selector works fine but when I give it a transition, the button first gets smaller and then jumps back to the original size. How do I stop this behavior? here's my code: ```css a { width: 250px; display: block; color: rgba(0, 0, 0, .9); text-decoration: none } .prod-ueber .cta-wrapper { position: absolute; left: 310px; width: 100px; top: 45px; z-index: 5 } .info-btn, .korb-btn { width: 50px; height: 50px; background-repeat: no-repeat; background-size: 100%; float: left; transition: background .4s ease; } .info-btn { background-image: url(http://imgh.us/info-btn.svg); } .korb-btn { background-image: url(http://imgh.us/korb-btn.svg); margin-left: 12px; } .info-btn:hover, .info-btn:active, .info-btn:focus { background-image: url(http://imgh.us/info-btn_h.svg); } .korb-btn:hover, .korb-btn:active, .korb-btn:focus { background-image: url(http://imgh.us/korb-btn_h.svg); } ``` ```html <a href="#"> <div class="prod-ueber"> <img src="http://dummyimage.com/" height="290" width="426" alt="Minze" class="img-responsive"> <h3 class="Artikelname">Malve</h3> <small>Description</small> <hr> <h5 class="preis">€ 1,79</h5> <div class="cta-wrapper"> <a href="#" class="info-btn"></a> <a href="#" class="korb-btn"></a> </div> </div> <!-- produkt --> </a> ```
2015/04/15
[ "https://Stackoverflow.com/questions/29644539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4507540/" ]
You can use a workaround by adding `background-image` for the `pseudo` element ```css a { width: 250px; display: block; color: rgba(0, 0, 0, .9); text-decoration: none } .prod-ueber .cta-wrapper { position: absolute; left: 310px; width: 100px; top: 45px; z-index: 5 } .info-btn, .korb-btn { width: 50px; height: 50px; background-repeat: no-repeat; background-size: 100%; float: left; position: relative; overflow:hidden; } .info-btn { background-image: url(http://imgh.us/info-btn.svg); } .korb-btn { background-image: url(http://imgh.us/korb-btn.svg); margin-left: 12px; } .info-btn:before, .korb-btn:before { content: ''; width: 100%; height: 100%; position: absolute; background-size: 100% auto; opacity: 0; transition: .4s ease; } .info-btn:before { background-image: url(http://imgh.us/info-btn_h.svg); } .korb-btn:before { background-image: url(http://imgh.us/korb-btn_h.svg); } .info-btn:hover:before, .info-btn:active:before, .info-btn:focus:before { opacity: 1; } .korb-btn:hover:before, .korb-btn:active:before, .korb-btn:focus:before { opacity: 1; } ``` ```html <a href="#"> <div class="prod-ueber"> <img src="http://dummyimage.com/" height="290" width="426" alt="Minze" class="img-responsive"> <h3 class="Artikelname">Malve</h3> <small>Description</small> <hr> <h5 class="preis">€ 1,79</h5> <div class="cta-wrapper"> <a href="#" class="info-btn"></a> <a href="#" class="korb-btn"></a> </div> </div> </a> ```
If using a transition with a background-image the various background properties must also be explicitly declared e.g. { backgroundRepeat: 'no-repeat', backgroundSize: '30px 30px', backgroundPosition: '0px 0px' }
29,644,539
I have a button with an svg as a background. The `:hover` selector works fine but when I give it a transition, the button first gets smaller and then jumps back to the original size. How do I stop this behavior? here's my code: ```css a { width: 250px; display: block; color: rgba(0, 0, 0, .9); text-decoration: none } .prod-ueber .cta-wrapper { position: absolute; left: 310px; width: 100px; top: 45px; z-index: 5 } .info-btn, .korb-btn { width: 50px; height: 50px; background-repeat: no-repeat; background-size: 100%; float: left; transition: background .4s ease; } .info-btn { background-image: url(http://imgh.us/info-btn.svg); } .korb-btn { background-image: url(http://imgh.us/korb-btn.svg); margin-left: 12px; } .info-btn:hover, .info-btn:active, .info-btn:focus { background-image: url(http://imgh.us/info-btn_h.svg); } .korb-btn:hover, .korb-btn:active, .korb-btn:focus { background-image: url(http://imgh.us/korb-btn_h.svg); } ``` ```html <a href="#"> <div class="prod-ueber"> <img src="http://dummyimage.com/" height="290" width="426" alt="Minze" class="img-responsive"> <h3 class="Artikelname">Malve</h3> <small>Description</small> <hr> <h5 class="preis">€ 1,79</h5> <div class="cta-wrapper"> <a href="#" class="info-btn"></a> <a href="#" class="korb-btn"></a> </div> </div> <!-- produkt --> </a> ```
2015/04/15
[ "https://Stackoverflow.com/questions/29644539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4507540/" ]
Instead of setting the background of the image you can just set in the svg element itself. It might make you html a bit bigger but you can set the **<svg>** in a **[template](https://stackoverflow.com/questions/27954250/moving-to-svg-icons-how-to-separate-them-from-the-code/28029642#28029642).** First lets just use a svg instead of background. (svg is xhtml so you can just paste it in html) ```css #Ebene_1 circle { transition: fill .4s, stroke .4s; } #Ebene_1:hover circle { fill: #ffe; } #Ebene_1:hover path { fill: #b61910; } ``` ```html <p>We can use the svg inside our html :D</p> <svg version="1.1" id="Ebene_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="60.1px" height="60.1px" viewBox="0 0 60.1 60.1"> <circle fill="#B61910" stroke="#B61910" stroke-width="1.5" stroke-miterlimit="10" cx="30.1" cy="30.1" r="29.3" /> <path fill="#FFFFFF" d="M32.3,14c1.6,0,3.2,1.6,3.2,3.2S33.9,22,30.7,22c-1.6,0-3.2-1.6-3.2-3.2C29.2,15.6,30.7,14,32.3,14z M26,45.8c-1.6,0-3.2-1.6-1.6-6.4l1.6-7.9c0-1.6,0-1.6,0-1.6s-3.2,1.6-4.8,1.6v-1.6c4.8-3.2,9.5-4.8,11.1-4.8 c1.6,0,1.6,1.6,1.6,4.8l-1.6,7.9c0,1.6,0,1.6,0,1.6s1.6,0,3.2-1.6l1.6,1.6C32.3,44.2,27.6,45.8,26,45.8z" /> <rect x="8.2" y="14.2" fill="none" width="36.5" height="31.8" /> </svg> <p>and it wil :hover. <br> Added some transitions to.</p> ```
If using a transition with a background-image the various background properties must also be explicitly declared e.g. { backgroundRepeat: 'no-repeat', backgroundSize: '30px 30px', backgroundPosition: '0px 0px' }
295,538
I've tried to create a new environment using minipage, which has the same vertical space between paragraphs as would be there when not using the minipage. What I have so far is: ``` \usepackage{boxedminipage} % had to use this to get minipage \newlength{\currentparskip} \newenvironment{minipageparskip} {% \setlength{\currentparskip}{\parskip}% save the value \begin{minipage}{1.0\textwidth}% open the minipage \setlength{\parskip}{\currentparskip}% restore the value }% {\end{minipage}} \newenvironment{songverse} {% \begin{minipageparskip}{1.0\textwidth}% \begin{center}% } {% \end{center}% \end{minipageparskip}% \leavevmode \\% } ``` However, in the line, where I first use this new environment, like this: ``` \begin{songverse} ... Text ... \end{songverse} ``` I get the following error: ``` ! Missing number, treated as zero. <to be read again> } \songverse ...in {minipageparskip}{1.0\textwidth } \begin {center} l.118 \begin{songverse} ``` At first I thought it was talking about the `1.0\textwidth`, but then I saw, that I have written that everywhere, where I used `minipage`, so now I think it might not be that. I don't understand where else a number could be missing, leading to this error. The `minipageparskip` environment is actually copied from another [SE post](https://tex.stackexchange.com/a/43005/92107). Ultimately, I want to have an environment, in which no pagebreak occurs and which contains a verse of a song. How can I fix the error? **Example (`samepage` not preventing the pagebreak within songverse)** Note: using `xelatex` to compile. ``` \documentclass[12pt, a5paper]{extarticle} \usepackage[ top=20mm, bottom=20mm, left=24mm, right=24mm ]{geometry} \usepackage{fontspec} \usepackage{xunicode} \usepackage[UTF8]{ctex} % AUTOMATICAL PINYIN PHONETIC SCRIPT \newfontfamily{\DVS}{DejaVu Sans} \usepackage{xpinyin} \xpinyinsetup{ratio={.6}, hsep={.5em plus .1em}, vsep={1.1em}, multiple={\color{red}}, pysep={.2em}, footnote=false, font=\DVS} \newenvironment{songverse} {% \begin{samepage}% \begin{center}% }{% \end{center}% \end{samepage}% } \begin{document} \begin{pinyinscope} \begin{songverse} 无量心 生福报 无极限 无极限 生息息 爱相连 为何君视而不见 规矩定方圆 悟性 悟觉 悟空 心甘情愿 \end{songverse} \begin{songverse} 放下 颠倒梦想 放下云烟 放下 空欲色 放下悬念 多一物 却添了 太多危险 少一物 贪嗔痴 会少一点 \end{songverse} \begin{songverse} 若是缘 再苦味也是甜 若无缘 藏爱 在心田 尘世 藕断还丝连 回首一瞬间 种颗善因 陪你走好每一天 \end{songverse} \begin{songverse} 唯有 心无挂碍 成就大愿 唯有 心无故 妙不可言 算天算\xpinyin{地}{di4} 算尽\xpinyin{了}{liao3} 从前 算不出 生死 会在哪一天 \end{songverse} \begin{songverse} 勿生恨 点化虚空的眼 勿生怨 欢喜 不遥远 缠绕 欲望的思念 善恶一瞬间 心怀忏悔 陪你走好每一天 \end{songverse} \begin{songverse} 再牢的谎言 却逃不过天眼 明日之前 心流离更远 浮云霎那间 障眼 人心渐离间 集苦连连 不断的出现 \end{songverse} \begin{songverse} 无量心 生福报 无极限 无极限 生息息 爱相连 凡人却视而不见 规矩定方圆 悟性 悟觉 悟空 心甘情愿 \end{songverse} \begin{songverse} 简简单单 陪你走好每一天 \end{songverse} \end{pinyinscope} \end{document} ```
2016/02/23
[ "https://tex.stackexchange.com/questions/295538", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/92107/" ]
Your `minipageparskip` environment does not expect an argument. I adjusted your definition, that the argument is passed through. ``` \newenvironment{minipageparskip}[1] {% \setlength{\currentparskip}{\parskip}% save the value \begin{minipage}{#1}% open the minipage \setlength{\parskip}{\currentparskip}% restore the value }% {\end{minipage}} ``` --- **Edit:** But why do you even nest these two environments? I think it would be much easier to just use *one* environment. ``` \documentclass{article} \newlength{\currentparskip} \newenvironment{songverse} {% \setlength{\currentparskip}{\parskip}% save the value \begin{minipage}{1.0\textwidth}% \setlength{\parskip}{\currentparskip}% restore the value \begin{center}% }{% \end{center}% \end{minipage}% \leavevmode \\% } \begin{document} \begin{songverse} ... Text ... \end{songverse} \end{document} ```
You can also use a `tabular` to provide an unbreakable block. It doesn't suffer from the same [`\baseline` issues that `\parbox` and `minipage` have](https://tex.stackexchange.com/q/34971/5764). [![enter image description here](https://i.stack.imgur.com/X4No5.png)](https://i.stack.imgur.com/X4No5.png) ``` \documentclass{article} \usepackage[nopar]{lipsum}% Just for this example \newlength{\currentparskip} \newenvironment{songverse} {% \setlength{\currentparskip}{\parskip}% Save current \parskip \par%\vspace{\baselineskip}% Add possible separation \noindent\begin{tabular}[t]{@{} p{\textwidth} @{}}% \centering \setlength{\parskip}{\currentparskip}% Restore current \parskip } {% \end{tabular}% \par%\vspace{\baselineskip}% Add possible vertical separation } \begin{document} \setlength{\parskip}{10pt} \lipsum[1] \lipsum[2] \newpage \begin{songverse} \lipsum[1] \lipsum[2] \end{songverse} \end{document} ```
41,474,237
I have 2 columns ***SKU\_new*** and **order\_ID** on #temp table that match with **SKU** and **ID** column of orders table i am using *inner join* but it keeps executing and does not show any result. my query is ``` SELECT t.SKU_new, t.ID_Order INTO #caseone FROM dbo.Order_No AS n JOIN dbo.Orders AS o ON n.Order_No = o.Order_No JOIN #Temp AS t ON (t.ID_Order = o.ID or t.SKU_new = o.SKU); ```
2017/01/04
[ "https://Stackoverflow.com/questions/41474237", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7352050/" ]
> > When i type cast bf.a to int it gives the desired output (7). But when > i dont type cast it, it gives no output and gives no errors. Why is it > so? > > > The character (number 7) was written to the console. Character 7 is the [bell character](https://en.wikipedia.org/wiki/Bell_character). --- So you can't see it, but you can hear it. Or rather I could hear the notification sound on Windows 10 when I ran the program. The same output is generated with: ``` cout << '\a'; ``` --- The bell is part of a group of characters that can be referenced with [escape sequences](http://en.cppreference.com/w/cpp/language/escape). --- Note that in this case the use of a `char` bitfield is not guaranteed by the standard. See [here](https://stackoverflow.com/q/3971085/1460794) for a question regarding the use of `char` bitfields.
Char type bitfield is not supported. Bitfield declaration supports only 4 identifiers, * unsigned int * signed int * int * bool [Source](http://en.cppreference.com/w/c/language/bit_field)
41,474,237
I have 2 columns ***SKU\_new*** and **order\_ID** on #temp table that match with **SKU** and **ID** column of orders table i am using *inner join* but it keeps executing and does not show any result. my query is ``` SELECT t.SKU_new, t.ID_Order INTO #caseone FROM dbo.Order_No AS n JOIN dbo.Orders AS o ON n.Order_No = o.Order_No JOIN #Temp AS t ON (t.ID_Order = o.ID or t.SKU_new = o.SKU); ```
2017/01/04
[ "https://Stackoverflow.com/questions/41474237", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7352050/" ]
You are printing the character who's value is 7. Others have pointed out that this is a special character that is usually not displayed. Cast your value to `int` or another non-char integer type to display the value, rather than the character. Go look at [the ascii table](http://www.asciitable.com/) and you'll see character 7 is BEL (bell). ``` #include <iostream> using namespace std; struct bitfield { unsigned char a : 3, b : 3; }; int main() { bitfield bf; bf.a = 7; cout << (int)bf.a; // Added (int) here char c; cin >> c; return 0; } ``` Edit 1: Since `bf.a` is only 3 bits, it cannot be set to any displayable character values. If you increase it's size, you can display characters. Setting it to 46 gives the period character. ``` #include <iostream> using namespace std; struct bitfield { unsigned char a : 6, b : 2; }; int main() { bitfield bf; bf.a = 46; cout << bf.a; char c; cin >> c; return 0; } ``` Edit 2: See [This answer](https://stackoverflow.com/a/41474349/7359094) about using bitfields and `char`.
Char type bitfield is not supported. Bitfield declaration supports only 4 identifiers, * unsigned int * signed int * int * bool [Source](http://en.cppreference.com/w/c/language/bit_field)
35,491,390
I've got a PowerShell script on PowerShell v4.0 (Windows 7 x64 SP1) that creates a pretty complex DataTable. I wanted to be able to place that DataTable code anywhere pretty easily, so I decided to wrap it in a simple function, like so: ``` function Get-UserDataTable { $DataTable = New-Object -TypeName System.Data.DataTable -ArgumentList 'User'; $NewColumn = $DataTable.Columns.Add('Id',[System.Int32]); $NewColumn.AllowDBNull = $false; $NewColumn.Unique = $true; $NewColumn = $DataTable.Columns.Add('FirstName',[System.String]); $NewColumn.MaxLength = 64; $NewColumn = $DataTable.Columns.Add('MiddleName',[System.String]); $NewColumn.MaxLength = 64; $NewColumn = $DataTable.Columns.Add('LastName',[System.String]); $NewColumn.MaxLength = 64; return $DataTable; } ``` However, that code always returns a null object. I tried `Write-Output $DataTable`, `return $DataTable.Copy()`, and `$DataTable`, but the function is still always null. So, I thought I might try adding some rows. I can always clear the DataTable, and it'd still be less coding this way: ``` function Get-UserDataTable2 { $DataTable = New-Object -TypeName System.Data.DataTable -ArgumentList 'User'; $NewColumn = $DataTable.Columns.Add('Id',[System.Int32]); $NewColumn.AllowDBNull = $false; $NewColumn.Unique = $true; $NewColumn = $DataTable.Columns.Add('FirstName',[System.String]); $NewColumn.MaxLength = 64; $NewColumn = $DataTable.Columns.Add('MiddleName',[System.String]); $NewColumn.MaxLength = 64; $NewColumn = $DataTable.Columns.Add('LastName',[System.String]); $NewColumn.MaxLength = 64; $NewRow = $DataTable.NewRow(); $NewRow.Id = 1; $NewRow.FirstName = 'Test'; $NewRow.MiddleName = ''; $NewRow.LastName = 'User'; $DataTable.Rows.Add($NewRow); $NewRow = $DataTable.NewRow(); $NewRow.Id = 2; $NewRow.FirstName = 'Other'; $NewRow.MiddleName = 'Test'; $NewRow.LastName = 'User'; $DataTable.Rows.Add($NewRow); return $DataTable; } ``` Nope. This function returns a `[System.Object[]]` containing individual `[System.Data.DataRow]`. An object array of DataRows. How can I return a DataTable from a function in PowerShell?
2016/02/18
[ "https://Stackoverflow.com/questions/35491390", "https://Stackoverflow.com", "https://Stackoverflow.com/users/696808/" ]
As the link in PerSerAl's comment suggests, the issue is caused because DataTable isn't an enumerable data type. To force it to be enumerable, you can use the unary comma operator to put it into an array as a single element. Arrays *are* enumerable. ``` function Get-UserDataTable { $DataTable = New-Object -TypeName System.Data.DataTable -ArgumentList 'User'; $NewColumn = $DataTable.Columns.Add('Id',[System.Int32]); $NewColumn.AllowDBNull = $false; $NewColumn.Unique = $true; $NewColumn = $DataTable.Columns.Add('FirstName',[System.String]); $NewColumn.MaxLength = 64; $NewColumn = $DataTable.Columns.Add('MiddleName',[System.String]); $NewColumn.MaxLength = 64; $NewColumn = $DataTable.Columns.Add('LastName',[System.String]); $NewColumn.MaxLength = 64; return ,$DataTable; } ```
> > This question seem like a [duplicate for this one](https://stackoverflow.com/questions/39495766/how-to-return-specific-data-type-from-powershell-function-i-e-datatable), but you may want to look at the more elaborative info on [that answer & below](https://stackoverflow.com/questions/39495766/how-to-return-specific-data-type-from-powershell-function-i-e-datatable#answer-39496461). > > >
260,118
I have a Postgres 10 database which is the model for an MVC app. On it many (200,000) LOBS get saved, eventually processed, and stored or deleted depending on some conditions. I have two problems. 1. The first is about disk space management, i.e. I want that my tablespace occupies only a portion of disk that I'll allow to it, and when the maximum allowed storage is reached, the application has to stop inserting LOBS. AFAIK there are no ways to set quota on tablespaces, so if the application continues inserting it fills up the whole disk space, not only the one I've chosen to occupy. So in order to avoid problems I've set up a disk quota at the OS level, but this is a rough solution. Is there any better way to manage this problem? 2. The second problem is about unused space release. AFAIK, if I delete some LOBS, the `pg_largeobject` size is exactly the same, so I have to do a vacuum full to release the unused space of it. But for doing this how much additional space do I need? Reading somewhere it seems that I need at list the table size free disk space, so if it's 100 GB, I need to have another 100 GB in order to perform vacuum. Is it true? I've got a baffling experience on that. I had deleted 100,000 records, tried to vacuum full, and I got a "no disk space" error. I deleted another 120,000 records chunk (but the table is not empty), retried the vacuum full and this time worked. Can you help me shedding light on this matter?
2020/02/20
[ "https://dba.stackexchange.com/questions/260118", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/201608/" ]
System Dynamic Management Views ------------------------------- You might want to dive into the **[Execution Related Dynamic Management Views and Functions (Transact-SQL)](https://learn.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/execution-related-dynamic-management-views-and-functions-transact-sql?view=sql-server-ver15)** that reside in a SQL Server instance. These views and functions do contains some information related to performance. The suggested views and functions are a sub-set of the **[System Dynamic Management Views](https://learn.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/system-dynamic-management-views?view=sql-server-ver15)** which contain various other sub-sets of views and functions, which may or may not be what you are looking for. ### Further sub-sets * [Database Related Dynamic Management Views (Transact-SQL)](https://learn.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/database-related-dynamic-management-views-transact-sql?view=sql-server-ver15) * [Index Related Dynamic Management Views and Functions (Transact-SQL)](https://learn.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/index-related-dynamic-management-views-and-functions-transact-sql?view=sql-server-ver15) * [I O Related Dynamic Management Views and Functions (Transact-SQL)](https://learn.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/i-o-related-dynamic-management-views-and-functions-transact-sql?view=sql-server-ver15) * [Memory-Optimized Table Dynamic Management Views (Transact-SQL)](https://learn.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/memory-optimized-table-dynamic-management-views-transact-sql?view=sql-server-ver15) * [Transaction Related Dynamic Management Views and Functions (Transact-SQL)](https://learn.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/transaction-related-dynamic-management-views-and-functions-transact-sql?view=sql-server-ver15) * ... *(Just to name a few)* > > **Note** > > Most of these views are recycled after an instance restart. You will have to dump the information to static tables in a (e.g.) Admin database if you want to retain historical data. > > > Built-In Reports ---------------- If you right-click on a database and move your mouse pointer into the reports, then you might find can occasional jewel of information: [![Picture showing the context menu on a database, when selecting the item Reports, then the sub-menu Standard Reports and then the sub-menu displaying the various options.](https://i.stack.imgur.com/nuAI6.png)](https://i.stack.imgur.com/nuAI6.png) Creating a Baseline for SQL Server ---------------------------------- There is an extensive Q&A on DBA.SE with the title [Creating SQL Server Performance Baseline Monitoring](https://dba.stackexchange.com/q/111258/15356) which show you how you could baseline a SQL Server instance. The article references other material. And then you could start reading Erin Stellato's article [5 Reasons You Must Start Capturing Baseline Data](https://www.sqlservercentral.com/steps/5-reasons-you-must-start-capturing-baseline-data) for an interesting start into SQL Server "baselining". Answering Your Question ----------------------- > > So.. I was wondering, is there a way for me to generate any report for the historical performance of a MS SQL database? > > > There are indeed a couple of ways with the **Management Views and Functions** and **Standard Reports**. For a deep dive you are going to either build something yourself or purchase a third-party tool.
Not out of the box, no. SQL Server does have a default trace, but the range of events captured is quite small <https://www.databasejournal.com/features/mssql/a-few-cool-things-you-can-identify-using-the-default-trace.html> and not much history is kept. Extended Events are the server-side replacement for SQL Profiler, but there is a bit of a learning curve and you kind of already need to know what you are interested in. A third party monitoring tool might be an option - maybe a free trial or demo version? If not, you could roll your own using PerfMon. SQL Server exposes a lot of counters which will give you stats on executions, locks, CPU, IO and so on, see <https://www.sqlservercentral.com/articles/using-perfmon-and-pal-to-diagnose-sql-issues> . It won't give you information about individual SQL statements though. Newer versions of SQL Server have a feature called the Query Store, which has similarities to Oracle's Active Session History. HTH
260,118
I have a Postgres 10 database which is the model for an MVC app. On it many (200,000) LOBS get saved, eventually processed, and stored or deleted depending on some conditions. I have two problems. 1. The first is about disk space management, i.e. I want that my tablespace occupies only a portion of disk that I'll allow to it, and when the maximum allowed storage is reached, the application has to stop inserting LOBS. AFAIK there are no ways to set quota on tablespaces, so if the application continues inserting it fills up the whole disk space, not only the one I've chosen to occupy. So in order to avoid problems I've set up a disk quota at the OS level, but this is a rough solution. Is there any better way to manage this problem? 2. The second problem is about unused space release. AFAIK, if I delete some LOBS, the `pg_largeobject` size is exactly the same, so I have to do a vacuum full to release the unused space of it. But for doing this how much additional space do I need? Reading somewhere it seems that I need at list the table size free disk space, so if it's 100 GB, I need to have another 100 GB in order to perform vacuum. Is it true? I've got a baffling experience on that. I had deleted 100,000 records, tried to vacuum full, and I got a "no disk space" error. I deleted another 120,000 records chunk (but the table is not empty), retried the vacuum full and this time worked. Can you help me shedding light on this matter?
2020/02/20
[ "https://dba.stackexchange.com/questions/260118", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/201608/" ]
I use Brent Ozar's [First Responder Kit PowerBI Dashboard](https://www.brentozar.com/first-aid/first-responder-kit-power-bi-dashboard/). You install some procs, create a table to store the data and then schedule a job to populate the data. You can drill down into performance of specific queries and lots of other cool stuff.
Not out of the box, no. SQL Server does have a default trace, but the range of events captured is quite small <https://www.databasejournal.com/features/mssql/a-few-cool-things-you-can-identify-using-the-default-trace.html> and not much history is kept. Extended Events are the server-side replacement for SQL Profiler, but there is a bit of a learning curve and you kind of already need to know what you are interested in. A third party monitoring tool might be an option - maybe a free trial or demo version? If not, you could roll your own using PerfMon. SQL Server exposes a lot of counters which will give you stats on executions, locks, CPU, IO and so on, see <https://www.sqlservercentral.com/articles/using-perfmon-and-pal-to-diagnose-sql-issues> . It won't give you information about individual SQL statements though. Newer versions of SQL Server have a feature called the Query Store, which has similarities to Oracle's Active Session History. HTH
260,118
I have a Postgres 10 database which is the model for an MVC app. On it many (200,000) LOBS get saved, eventually processed, and stored or deleted depending on some conditions. I have two problems. 1. The first is about disk space management, i.e. I want that my tablespace occupies only a portion of disk that I'll allow to it, and when the maximum allowed storage is reached, the application has to stop inserting LOBS. AFAIK there are no ways to set quota on tablespaces, so if the application continues inserting it fills up the whole disk space, not only the one I've chosen to occupy. So in order to avoid problems I've set up a disk quota at the OS level, but this is a rough solution. Is there any better way to manage this problem? 2. The second problem is about unused space release. AFAIK, if I delete some LOBS, the `pg_largeobject` size is exactly the same, so I have to do a vacuum full to release the unused space of it. But for doing this how much additional space do I need? Reading somewhere it seems that I need at list the table size free disk space, so if it's 100 GB, I need to have another 100 GB in order to perform vacuum. Is it true? I've got a baffling experience on that. I had deleted 100,000 records, tried to vacuum full, and I got a "no disk space" error. I deleted another 120,000 records chunk (but the table is not empty), retried the vacuum full and this time worked. Can you help me shedding light on this matter?
2020/02/20
[ "https://dba.stackexchange.com/questions/260118", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/201608/" ]
As for built-in features, older versions of SQL Server have the [Management Data Warehouse](https://learn.microsoft.com/en-us/sql/relational-databases/data-collection/management-data-warehouse?view=sql-server-ver15), which will collect performance data and store it in a separate database, optionally on a separate server. Newer versions add the [Query Store](https://learn.microsoft.com/en-us/sql/relational-databases/performance/monitoring-performance-by-using-the-query-store?view=sql-server-ver15) which will automatically record query plans and stats, as well as query wait stats. And newer versions track [wait stats at the session level](https://learn.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-exec-session-wait-stats-transact-sql?view=sql-server-ver15).
Not out of the box, no. SQL Server does have a default trace, but the range of events captured is quite small <https://www.databasejournal.com/features/mssql/a-few-cool-things-you-can-identify-using-the-default-trace.html> and not much history is kept. Extended Events are the server-side replacement for SQL Profiler, but there is a bit of a learning curve and you kind of already need to know what you are interested in. A third party monitoring tool might be an option - maybe a free trial or demo version? If not, you could roll your own using PerfMon. SQL Server exposes a lot of counters which will give you stats on executions, locks, CPU, IO and so on, see <https://www.sqlservercentral.com/articles/using-perfmon-and-pal-to-diagnose-sql-issues> . It won't give you information about individual SQL statements though. Newer versions of SQL Server have a feature called the Query Store, which has similarities to Oracle's Active Session History. HTH
177,082
When I say > > My friends and I went snowboarding. > > > somebody said to me there is a grammar mistake in my sentence but I could not figure out what it is. What is the grammar mistake in the sentence? Should it be > > I and my friends went snowboarding. > > >
2018/08/23
[ "https://ell.stackexchange.com/questions/177082", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/11631/" ]
Your sentence is entirely correct. I'm not sure why they thought it was incorrect, but I'll explain why you're correct, and then guess what *their* mistake may have been. When we use two subjects together, we should be able to use either one by itself. > > My friends went snowboarding. > > > I went snowboarding. > > > Both of these work fine, so there is no mistake there. Further, it is traditional to place "I" as the last person in a list of subjects (probably to be humble). "I and my friends", while not grammatically wrong, is generally considered to be incorrect. Next, we use the verb "go" for (almost) any activity that is made with [verb]-ing. "Go shopping", "go swimming", "go skiing", etc. You used "go" (or here the past tense, "went"), so that's correct. The only thing that could possibly make your sentence wrong is if it was for the wrong time. For example: > > I went snowboarding next week. > > > This is wrong (assuming you don't have a time machine), but I really don't think you made that mistake. So why did they say it was wrong? Well, there are two possibilities I can think of. First, they may have been thinking that you should use the verb "do" or "play" instead of "go". That's wrong. "Go" is the correct word. Second, they may have been making a common mistake (even among native speakers). Many people say "My friends and me went snowboarding." This is not correct, because it doesn't pass the test I mentioned in the beginning. > > My friends went snowboarding. > > > This is correct, but... > > Me went snowboarding. > > > ...is not correct. Therefore, it should be I, not me. Hope that helps!
Generally speaking.. > > My friends and I went snowboarding > > > ..would be considered good "proper" English and is grammatically correct. However, in general conversation people will say.. > > Me and my friends went snowboarding > > > ..which is *perfectly acceptable* in all but the most polite of circumstances - by which I mean - meeting the queen etc. ( "The Queen"?? :) ) If someone picks you up on using the second form then they are probably either.. * Joking * President of the Correct English Society (fictitious) * In need of a stick removing from their a\*\* **But** > > I and my friends went snowboarding > > > ..is not correct, and just sounds "wrong" to a native speaker. It should either be **me and my friends** *or* **my friends and I** (see above).
177,082
When I say > > My friends and I went snowboarding. > > > somebody said to me there is a grammar mistake in my sentence but I could not figure out what it is. What is the grammar mistake in the sentence? Should it be > > I and my friends went snowboarding. > > >
2018/08/23
[ "https://ell.stackexchange.com/questions/177082", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/11631/" ]
It is possible your friend had your sentence confused with a similar grammar error that you did NOT make. It is incorrect to say "John gave apples to Ann and I" Same reason: You can say "John gave apples to Ann" but you cannot say "John gave apples to I"
"me and my friends" is a fixed construction, which works well as subject in this sentence, allowing the object form "me". "I and my friends" is not. One could argue that "my friends and me" is a totally acceptable construction too, but in this sentence, "me" would be followed by the verb, which makes it sound much too close to "me went skiing..", which is by most considered grammatically very wrong.
177,082
When I say > > My friends and I went snowboarding. > > > somebody said to me there is a grammar mistake in my sentence but I could not figure out what it is. What is the grammar mistake in the sentence? Should it be > > I and my friends went snowboarding. > > >
2018/08/23
[ "https://ell.stackexchange.com/questions/177082", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/11631/" ]
Your sentence is entirely correct. I'm not sure why they thought it was incorrect, but I'll explain why you're correct, and then guess what *their* mistake may have been. When we use two subjects together, we should be able to use either one by itself. > > My friends went snowboarding. > > > I went snowboarding. > > > Both of these work fine, so there is no mistake there. Further, it is traditional to place "I" as the last person in a list of subjects (probably to be humble). "I and my friends", while not grammatically wrong, is generally considered to be incorrect. Next, we use the verb "go" for (almost) any activity that is made with [verb]-ing. "Go shopping", "go swimming", "go skiing", etc. You used "go" (or here the past tense, "went"), so that's correct. The only thing that could possibly make your sentence wrong is if it was for the wrong time. For example: > > I went snowboarding next week. > > > This is wrong (assuming you don't have a time machine), but I really don't think you made that mistake. So why did they say it was wrong? Well, there are two possibilities I can think of. First, they may have been thinking that you should use the verb "do" or "play" instead of "go". That's wrong. "Go" is the correct word. Second, they may have been making a common mistake (even among native speakers). Many people say "My friends and me went snowboarding." This is not correct, because it doesn't pass the test I mentioned in the beginning. > > My friends went snowboarding. > > > This is correct, but... > > Me went snowboarding. > > > ...is not correct. Therefore, it should be I, not me. Hope that helps!
> > My friends and I went snowboarding > > > There's nothing wrong with the sentence; it's perfect. How come somebody says that your sentence is not correct? Maybe he likes to use object pronouns when they are cojoined with other nouns/subject pronouns as many people tend to do so in informal speaking and writing. In this case, the sentence will be: > > My friends and me went snowboarding. > > > Or maybe he likes to begin the sentence with "I" as follows: > > I and my friends went snowboardig. > > > This sentence is also OK grammatically, but your sentence is more polite and common. Another reason may be that he prefers the following sentence as presented by J.R: I went snowboarding with my friends. This sentence like yours also sounds easy on the ear.
177,082
When I say > > My friends and I went snowboarding. > > > somebody said to me there is a grammar mistake in my sentence but I could not figure out what it is. What is the grammar mistake in the sentence? Should it be > > I and my friends went snowboarding. > > >
2018/08/23
[ "https://ell.stackexchange.com/questions/177082", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/11631/" ]
> > My friends and I went snowboarding > > > There's nothing wrong with the sentence; it's perfect. How come somebody says that your sentence is not correct? Maybe he likes to use object pronouns when they are cojoined with other nouns/subject pronouns as many people tend to do so in informal speaking and writing. In this case, the sentence will be: > > My friends and me went snowboarding. > > > Or maybe he likes to begin the sentence with "I" as follows: > > I and my friends went snowboardig. > > > This sentence is also OK grammatically, but your sentence is more polite and common. Another reason may be that he prefers the following sentence as presented by J.R: I went snowboarding with my friends. This sentence like yours also sounds easy on the ear.
"me and my friends" is a fixed construction, which works well as subject in this sentence, allowing the object form "me". "I and my friends" is not. One could argue that "my friends and me" is a totally acceptable construction too, but in this sentence, "me" would be followed by the verb, which makes it sound much too close to "me went skiing..", which is by most considered grammatically very wrong.