qid
int64
1
74.6M
question
stringlengths
45
24.2k
date
stringlengths
10
10
metadata
stringlengths
101
178
response_j
stringlengths
32
23.2k
response_k
stringlengths
21
13.2k
30,707,256
I am implementing instamojo payment method into my website. Can I use a localhost URL as Webhook URL in order to test the process?
2015/06/08
['https://Stackoverflow.com/questions/30707256', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4290253/']
I'm from Instamojo. You can't use a local URL. This is because a webhook request is a POST request that is made from our server. Therefore, the only URLs that we can make these requests to would be URLs that are publicly available. For testing purposes, I would recommend using [RequestBin](https://requestbin.com/). You can create a new bin and paste the URL for that bin in the webhook URL field of your Instamojo link. This will give you a link that is accessible by our server and you can inspect the POST requests to this link by appending `?inspect` at the end of the URL.
We can't use localhost or as Webhook URL.If it is used the following error will show "Domain name should not be "localhost" or "127.0.0.1" ". So it must be a live URL.
30,707,256
I am implementing instamojo payment method into my website. Can I use a localhost URL as Webhook URL in order to test the process?
2015/06/08
['https://Stackoverflow.com/questions/30707256', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4290253/']
It is possible to forward Instamojo's webhooks to your local machine using tools like `localtunnel`. * `npm` is required to install localtunnel. [[How to install node and npm]](https://docs.npmjs.com/getting-started/installing-node) * Install [localtunnel](https://localtunnel.me/) Suppose you are running your local server at port 8000, in a new terminal window, execute this: * `lt --port 8000` It will show you output like: * `your url is: https://whawgpctcs.localtunnel.me` This is a *temporary* webhook URL that will forward every HTTPS request sent to `https://whawgpctcs.localtunnel.me` to your local server running on port `8000`. * Paste this temporary url into Instamojo's webhook field and continue testing. * **Remember to remove the temporary webhook URL from Instamojo once you are done testing** The temporary webhook URL is valid as long as the `lt --port 8000` command (and your Internet connection) is active.
We can't use localhost or as Webhook URL.If it is used the following error will show "Domain name should not be "localhost" or "127.0.0.1" ". So it must be a live URL.
30,707,256
I am implementing instamojo payment method into my website. Can I use a localhost URL as Webhook URL in order to test the process?
2015/06/08
['https://Stackoverflow.com/questions/30707256', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4290253/']
We can't use localhost or as Webhook URL.If it is used the following error will show "Domain name should not be "localhost" or "127.0.0.1" ". So it must be a live URL.
You cannot use the localhost URL as a webhook URL in order to test the process. But you can simply bypass it, open hosts file from `C:\Windows\System32\Drivers\etc\hosts` At the end of the line write ``` 127.0.0.1 yourname.com ``` And access localhost using yourname.com. Just change localhost/your-location url with yourname.com/your-location in the PHP file.
30,707,256
I am implementing instamojo payment method into my website. Can I use a localhost URL as Webhook URL in order to test the process?
2015/06/08
['https://Stackoverflow.com/questions/30707256', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4290253/']
I'm from Instamojo. You can't use a local URL. This is because a webhook request is a POST request that is made from our server. Therefore, the only URLs that we can make these requests to would be URLs that are publicly available. For testing purposes, I would recommend using [RequestBin](https://requestbin.com/). You can create a new bin and paste the URL for that bin in the webhook URL field of your Instamojo link. This will give you a link that is accessible by our server and you can inspect the POST requests to this link by appending `?inspect` at the end of the URL.
It is possible to forward Instamojo's webhooks to your local machine using tools like `localtunnel`. * `npm` is required to install localtunnel. [[How to install node and npm]](https://docs.npmjs.com/getting-started/installing-node) * Install [localtunnel](https://localtunnel.me/) Suppose you are running your local server at port 8000, in a new terminal window, execute this: * `lt --port 8000` It will show you output like: * `your url is: https://whawgpctcs.localtunnel.me` This is a *temporary* webhook URL that will forward every HTTPS request sent to `https://whawgpctcs.localtunnel.me` to your local server running on port `8000`. * Paste this temporary url into Instamojo's webhook field and continue testing. * **Remember to remove the temporary webhook URL from Instamojo once you are done testing** The temporary webhook URL is valid as long as the `lt --port 8000` command (and your Internet connection) is active.
30,707,256
I am implementing instamojo payment method into my website. Can I use a localhost URL as Webhook URL in order to test the process?
2015/06/08
['https://Stackoverflow.com/questions/30707256', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4290253/']
I'm from Instamojo. You can't use a local URL. This is because a webhook request is a POST request that is made from our server. Therefore, the only URLs that we can make these requests to would be URLs that are publicly available. For testing purposes, I would recommend using [RequestBin](https://requestbin.com/). You can create a new bin and paste the URL for that bin in the webhook URL field of your Instamojo link. This will give you a link that is accessible by our server and you can inspect the POST requests to this link by appending `?inspect` at the end of the URL.
You cannot use the localhost URL as a webhook URL in order to test the process. But you can simply bypass it, open hosts file from `C:\Windows\System32\Drivers\etc\hosts` At the end of the line write ``` 127.0.0.1 yourname.com ``` And access localhost using yourname.com. Just change localhost/your-location url with yourname.com/your-location in the PHP file.
30,707,256
I am implementing instamojo payment method into my website. Can I use a localhost URL as Webhook URL in order to test the process?
2015/06/08
['https://Stackoverflow.com/questions/30707256', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4290253/']
It is possible to forward Instamojo's webhooks to your local machine using tools like `localtunnel`. * `npm` is required to install localtunnel. [[How to install node and npm]](https://docs.npmjs.com/getting-started/installing-node) * Install [localtunnel](https://localtunnel.me/) Suppose you are running your local server at port 8000, in a new terminal window, execute this: * `lt --port 8000` It will show you output like: * `your url is: https://whawgpctcs.localtunnel.me` This is a *temporary* webhook URL that will forward every HTTPS request sent to `https://whawgpctcs.localtunnel.me` to your local server running on port `8000`. * Paste this temporary url into Instamojo's webhook field and continue testing. * **Remember to remove the temporary webhook URL from Instamojo once you are done testing** The temporary webhook URL is valid as long as the `lt --port 8000` command (and your Internet connection) is active.
You cannot use the localhost URL as a webhook URL in order to test the process. But you can simply bypass it, open hosts file from `C:\Windows\System32\Drivers\etc\hosts` At the end of the line write ``` 127.0.0.1 yourname.com ``` And access localhost using yourname.com. Just change localhost/your-location url with yourname.com/your-location in the PHP file.
6,624,921
Hi i have a question a tryaing to create Amount calculator in jQuery, AJAX and jQuery UI. But i have a problem, i get all importat values from slider, select box. Bud i really don't know how can a get this value to global. I get value only in each function but when i want get this value out of function this value in variable does not exist. ``` $(function() { //1st slider for get amount $("#amount").slider({ range: "min", value: 0, min: 0, max: 10000, slide: function (e, ui) { $("#amount_show").val(ui.value); amount = ui.value; } }); $("#amount_show").val($("#amount").slider("value")); //2nd slider for get values years $("#years").slider({ range: "min", value:1, min:1, max:20, step:1, slide: function (e, ui) { $("#years_show").val(ui.value); years = ui.value; } }); $("#years_show").val($("#years").slider("value")); //AJAX for loading values from xml $.get("irate.xml", function(xml) { $(xml).find('country').each(function() { var select = $('#country'), id = $(this).attr('id'), name = $(this).find('name').text(), irate = $(this).find('irate').text(), currency = $(this).find('currency').text(); select.append("<option value='"+irate+"'>"+name+"</option>"); }); }); //get irate value from dropbox $("#country").change(function() { var irate_select = ""; $("#country option:selected").each(function () { irate_select += $(this).val() + " "; }); irate = irate_select; }); }); ``` I need calculate with amount, years and irate. Thank for your advice.
2011/07/08
['https://Stackoverflow.com/questions/6624921', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/896953/']
declare the variable outside of your function. ex. ``` var amount; $(function... ```
AndyL's answer should be correct. If you declare the variables you need available in another function outside of your function, and then set their values in one function, they should be available with those values to another function. ``` // outside your function!! var amount, years, irate; // in your function somewhere!! amount = someCalculation(); years = someOtherCalculation(); ``` These values will be available in every other function because they are declared as members of the global namespace.
6,624,921
Hi i have a question a tryaing to create Amount calculator in jQuery, AJAX and jQuery UI. But i have a problem, i get all importat values from slider, select box. Bud i really don't know how can a get this value to global. I get value only in each function but when i want get this value out of function this value in variable does not exist. ``` $(function() { //1st slider for get amount $("#amount").slider({ range: "min", value: 0, min: 0, max: 10000, slide: function (e, ui) { $("#amount_show").val(ui.value); amount = ui.value; } }); $("#amount_show").val($("#amount").slider("value")); //2nd slider for get values years $("#years").slider({ range: "min", value:1, min:1, max:20, step:1, slide: function (e, ui) { $("#years_show").val(ui.value); years = ui.value; } }); $("#years_show").val($("#years").slider("value")); //AJAX for loading values from xml $.get("irate.xml", function(xml) { $(xml).find('country').each(function() { var select = $('#country'), id = $(this).attr('id'), name = $(this).find('name').text(), irate = $(this).find('irate').text(), currency = $(this).find('currency').text(); select.append("<option value='"+irate+"'>"+name+"</option>"); }); }); //get irate value from dropbox $("#country").change(function() { var irate_select = ""; $("#country option:selected").each(function () { irate_select += $(this).val() + " "; }); irate = irate_select; }); }); ``` I need calculate with amount, years and irate. Thank for your advice.
2011/07/08
['https://Stackoverflow.com/questions/6624921', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/896953/']
declare the variable outside of your function. ex. ``` var amount; $(function... ```
Try using jquery's data() object; ``` $(function(){ ... slide: function (e, ui) { $("#amount_show").val(ui.value); amount = ui.value; // Add to data() object here $('#amount').data('amount',amount); } // reference it elsewhere in your script like such: console.log($('#amount').data('amount')); ```
6,624,921
Hi i have a question a tryaing to create Amount calculator in jQuery, AJAX and jQuery UI. But i have a problem, i get all importat values from slider, select box. Bud i really don't know how can a get this value to global. I get value only in each function but when i want get this value out of function this value in variable does not exist. ``` $(function() { //1st slider for get amount $("#amount").slider({ range: "min", value: 0, min: 0, max: 10000, slide: function (e, ui) { $("#amount_show").val(ui.value); amount = ui.value; } }); $("#amount_show").val($("#amount").slider("value")); //2nd slider for get values years $("#years").slider({ range: "min", value:1, min:1, max:20, step:1, slide: function (e, ui) { $("#years_show").val(ui.value); years = ui.value; } }); $("#years_show").val($("#years").slider("value")); //AJAX for loading values from xml $.get("irate.xml", function(xml) { $(xml).find('country').each(function() { var select = $('#country'), id = $(this).attr('id'), name = $(this).find('name').text(), irate = $(this).find('irate').text(), currency = $(this).find('currency').text(); select.append("<option value='"+irate+"'>"+name+"</option>"); }); }); //get irate value from dropbox $("#country").change(function() { var irate_select = ""; $("#country option:selected").each(function () { irate_select += $(this).val() + " "; }); irate = irate_select; }); }); ``` I need calculate with amount, years and irate. Thank for your advice.
2011/07/08
['https://Stackoverflow.com/questions/6624921', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/896953/']
declare the variable outside of your function. ex. ``` var amount; $(function... ```
a global variable should work, however, Shouldn't you want to change your 'calculator' if they change the values of something? pretend this is the html for the calculated amount: ``` <input type="text" id="amount" style="border:0; color:#f6931f; font-weight:bold;" /> ``` then you will need something like this code in document.ready(): ``` //if the slider changes, then update the calculated value $( "#years,#amount" ).bind( "slidechange", function(event, ui) { myCalculator(); }); // if the ?country? drop down changes, update the calculated value $().change(function(event){ myCalculator(); }); function myCalculator(){ var years = $('#years').slider("value"); var amount = $('#amount').slider("value"); var country = $('#country').val(); $('#amount').val("something") }; ```
6,624,921
Hi i have a question a tryaing to create Amount calculator in jQuery, AJAX and jQuery UI. But i have a problem, i get all importat values from slider, select box. Bud i really don't know how can a get this value to global. I get value only in each function but when i want get this value out of function this value in variable does not exist. ``` $(function() { //1st slider for get amount $("#amount").slider({ range: "min", value: 0, min: 0, max: 10000, slide: function (e, ui) { $("#amount_show").val(ui.value); amount = ui.value; } }); $("#amount_show").val($("#amount").slider("value")); //2nd slider for get values years $("#years").slider({ range: "min", value:1, min:1, max:20, step:1, slide: function (e, ui) { $("#years_show").val(ui.value); years = ui.value; } }); $("#years_show").val($("#years").slider("value")); //AJAX for loading values from xml $.get("irate.xml", function(xml) { $(xml).find('country').each(function() { var select = $('#country'), id = $(this).attr('id'), name = $(this).find('name').text(), irate = $(this).find('irate').text(), currency = $(this).find('currency').text(); select.append("<option value='"+irate+"'>"+name+"</option>"); }); }); //get irate value from dropbox $("#country").change(function() { var irate_select = ""; $("#country option:selected").each(function () { irate_select += $(this).val() + " "; }); irate = irate_select; }); }); ``` I need calculate with amount, years and irate. Thank for your advice.
2011/07/08
['https://Stackoverflow.com/questions/6624921', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/896953/']
AndyL's answer should be correct. If you declare the variables you need available in another function outside of your function, and then set their values in one function, they should be available with those values to another function. ``` // outside your function!! var amount, years, irate; // in your function somewhere!! amount = someCalculation(); years = someOtherCalculation(); ``` These values will be available in every other function because they are declared as members of the global namespace.
Try using jquery's data() object; ``` $(function(){ ... slide: function (e, ui) { $("#amount_show").val(ui.value); amount = ui.value; // Add to data() object here $('#amount').data('amount',amount); } // reference it elsewhere in your script like such: console.log($('#amount').data('amount')); ```
6,624,921
Hi i have a question a tryaing to create Amount calculator in jQuery, AJAX and jQuery UI. But i have a problem, i get all importat values from slider, select box. Bud i really don't know how can a get this value to global. I get value only in each function but when i want get this value out of function this value in variable does not exist. ``` $(function() { //1st slider for get amount $("#amount").slider({ range: "min", value: 0, min: 0, max: 10000, slide: function (e, ui) { $("#amount_show").val(ui.value); amount = ui.value; } }); $("#amount_show").val($("#amount").slider("value")); //2nd slider for get values years $("#years").slider({ range: "min", value:1, min:1, max:20, step:1, slide: function (e, ui) { $("#years_show").val(ui.value); years = ui.value; } }); $("#years_show").val($("#years").slider("value")); //AJAX for loading values from xml $.get("irate.xml", function(xml) { $(xml).find('country').each(function() { var select = $('#country'), id = $(this).attr('id'), name = $(this).find('name').text(), irate = $(this).find('irate').text(), currency = $(this).find('currency').text(); select.append("<option value='"+irate+"'>"+name+"</option>"); }); }); //get irate value from dropbox $("#country").change(function() { var irate_select = ""; $("#country option:selected").each(function () { irate_select += $(this).val() + " "; }); irate = irate_select; }); }); ``` I need calculate with amount, years and irate. Thank for your advice.
2011/07/08
['https://Stackoverflow.com/questions/6624921', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/896953/']
AndyL's answer should be correct. If you declare the variables you need available in another function outside of your function, and then set their values in one function, they should be available with those values to another function. ``` // outside your function!! var amount, years, irate; // in your function somewhere!! amount = someCalculation(); years = someOtherCalculation(); ``` These values will be available in every other function because they are declared as members of the global namespace.
a global variable should work, however, Shouldn't you want to change your 'calculator' if they change the values of something? pretend this is the html for the calculated amount: ``` <input type="text" id="amount" style="border:0; color:#f6931f; font-weight:bold;" /> ``` then you will need something like this code in document.ready(): ``` //if the slider changes, then update the calculated value $( "#years,#amount" ).bind( "slidechange", function(event, ui) { myCalculator(); }); // if the ?country? drop down changes, update the calculated value $().change(function(event){ myCalculator(); }); function myCalculator(){ var years = $('#years').slider("value"); var amount = $('#amount').slider("value"); var country = $('#country').val(); $('#amount').val("something") }; ```
69,712,966
I have been struggling with creating a legend in my ggplot for some time now, and I cannot find any answer that works. This is the stripped down version of my ggplot: ``` ggplot() + geom_smooth(data = mydf1, aes(x, predicted, linetype = 1), method = "lm", linetype = 1, colour = "black") + geom_smooth(data = mydf2, aes(x, predicted, linetype = 2), method = "lm", linetype = 2, colour = "black") + geom_smooth(data = mydf3, aes(x, predicted, linetype = 3), method = "lm", linetype = 3, colour = "black") + theme_classic() ``` [![enter image description here](https://i.stack.imgur.com/u84MR.png)](https://i.stack.imgur.com/u84MR.png) As you can notice, I am taking data from different dataframes (mydf1, mydf2, mydf3). Now I want to manually add a legend that specifies that the solid line is "Group 1", the longdashed line is "Group 2", and the dotted linetype is "Group 3". However, whatever I try, no legend appears in my ggplot. I included linetype within the aes(), tried everything I could think of regarding scale\_linetype\_manual(), and I've been looking around to find solutions, but no legend pops up. Am I missing something obvious? I just need a small legend to the side stating what the different linetypes mean. My data is the following: ``` mydf1 <- data.frame(x = c(seq(-1,1, 0.2)), predicted = c(-0.27066438, -0.23568714, -0.20070991, -0.16573267, -0.13075543, -0.09577819, -0.06080095, -0.02582371, 0.00915353, 0.04413077, 0.07910801)) mydf2 <- data.frame(x = c(seq(-1,1, 0.2)), predicted = c(-0.39806988, -0.34348641, -0.28890295, -0.23431948, -0.17973602, -0.12515255, -0.07056909, -0.01598562, 0.03859784, 0.09318131, 0.14776477)) mydf3 <- data.frame(x = c(seq(-1,1, 0.2)), predicted = c(-0.25520076, -0.22917917, -0.20315758, -0.17713600, -0.15111441, -0.12509282, -0.09907123, -0.07304964, -0.04702806, -0.02100647, 0.00501512)) ``` Although any practical solution would be helpful, I am not neccesarily looking to combine the dataframes into a single one and redo the ggplot. Thanks!
2021/10/25
['https://Stackoverflow.com/questions/69712966', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13339640/']
Bring the line linetype inside aes() and use lab() to give title for the legend. ``` ggplot() + geom_smooth(data = mydf1, aes(x, predicted, linetype = "Group 1"), method = "lm", colour = "black") + geom_smooth(data = mydf2, aes(x, predicted, linetype = "Group 2"), method = "lm", colour = "black") + geom_smooth(data = mydf3, aes(x, predicted, linetype = "Group 3"), method = "lm", colour = "black") + labs(linetype="Group") + theme_classic() ``` [![enter image description here](https://i.stack.imgur.com/vg054.png)](https://i.stack.imgur.com/vg054.png)
Here is an alternative way using `bind_rows`: ``` library(dplyr) library(ggplot2) bind_rows(mydf1, mydf2, mydf3) %>% mutate(group = as.integer(gl(n(), 11, n()))) %>% ggplot(aes(x, predicted, linetype=factor(group)))+ geom_smooth(color="black", method = "lm", se=F) + scale_linetype_discrete(name="group", breaks=c(1, 2, 3), labels = c("group1", "group2", "group3"))+ theme_classic() ``` [![enter image description here](https://i.stack.imgur.com/qSVzf.png)](https://i.stack.imgur.com/qSVzf.png)
15,501,034
I try to load a codeigniter view in iframe as, `<iframe src="<?php $this->load->view('lists');?/>"></iframe>` But the page could not load. With out i frame its working. How do i load this view in iframe ?
2013/03/19
['https://Stackoverflow.com/questions/15501034', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1939388/']
You can't assign plain html to iframe elements src attribute. You should have a controller that render your html and then set src attribute to that controller. ``` <iframe src="<?php echo base_url( 'controller_that_render_list_html' ) ?>"></iframe> ```
This is because the iframe is on another page? you haven't specified the controller function on that page so it doesn't recognize the view. i think you have to put the controller date from your view into the function for the view you have your iframe in, so lik this. ``` function list_view() { //functions for your listview } function viewforiframe() { //function for you view where the iframe is located + //functions for your listview } ``` NOTE: the answer Deon gave is also a thing to look at. without a good link you could never see the view.
15,501,034
I try to load a codeigniter view in iframe as, `<iframe src="<?php $this->load->view('lists');?/>"></iframe>` But the page could not load. With out i frame its working. How do i load this view in iframe ?
2013/03/19
['https://Stackoverflow.com/questions/15501034', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1939388/']
create a function in your controller ``` //project.php function view_list() { $this->load->view('lists'); } ``` and call in the view page like this ``` <iframe src="<?php echo site_url('project/view_list');?>">> </iframe> ```
This is because the iframe is on another page? you haven't specified the controller function on that page so it doesn't recognize the view. i think you have to put the controller date from your view into the function for the view you have your iframe in, so lik this. ``` function list_view() { //functions for your listview } function viewforiframe() { //function for you view where the iframe is located + //functions for your listview } ``` NOTE: the answer Deon gave is also a thing to look at. without a good link you could never see the view.
15,501,034
I try to load a codeigniter view in iframe as, `<iframe src="<?php $this->load->view('lists');?/>"></iframe>` But the page could not load. With out i frame its working. How do i load this view in iframe ?
2013/03/19
['https://Stackoverflow.com/questions/15501034', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1939388/']
I wanted to tile a site with several views, each in their own iframe, this is what I did: The controller, **book.php** ``` <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Book extends CI_Controller { public function index(){ $this->shell(); } public function shell(){ $data['title'] = "Home"; $data['frames'] = array( "book/events" ,"book/sales" ,"book/purchases" ,"book/cashflows" ); $this->load->view("shell", $data); } public function events(){ $this->load->view("events"); } public function sales(){ $this->load->view("sales"); } public function purchases(){ $this->load->view("purchases"); } public function cashflows(){ $this->load->view("cashflows"); } } ``` The view **shell.php** contains a foreach statement letting me pass in tiles dynamically. Note how the url's to each site are written in the controller above ^^ (eg. "book/events"). ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title><?php echo $title ?></title> </head> <body> <?php foreach ($frames as $frame):?> <iframe src="<?php echo $frame?>"></iframe> <?php endforeach;?> <div class="footer"> Page rendered in <strong>{elapsed_time}</strong> seconds</p> </div> </body> </html> ``` Then each tile is simply it's own site, like so: ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Events</title> </head> <body> <div class="header">Events</div> <div class="content"> Bla bla bla you have no money</div> <div class="footer"> Page rendered in <strong>{elapsed_time}</strong> seconds</p> </div> </body> </html> ```
This is because the iframe is on another page? you haven't specified the controller function on that page so it doesn't recognize the view. i think you have to put the controller date from your view into the function for the view you have your iframe in, so lik this. ``` function list_view() { //functions for your listview } function viewforiframe() { //function for you view where the iframe is located + //functions for your listview } ``` NOTE: the answer Deon gave is also a thing to look at. without a good link you could never see the view.
15,501,034
I try to load a codeigniter view in iframe as, `<iframe src="<?php $this->load->view('lists');?/>"></iframe>` But the page could not load. With out i frame its working. How do i load this view in iframe ?
2013/03/19
['https://Stackoverflow.com/questions/15501034', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1939388/']
create a function in your controller ``` //project.php function view_list() { $this->load->view('lists'); } ``` and call in the view page like this ``` <iframe src="<?php echo site_url('project/view_list');?>">> </iframe> ```
You can't assign plain html to iframe elements src attribute. You should have a controller that render your html and then set src attribute to that controller. ``` <iframe src="<?php echo base_url( 'controller_that_render_list_html' ) ?>"></iframe> ```
15,501,034
I try to load a codeigniter view in iframe as, `<iframe src="<?php $this->load->view('lists');?/>"></iframe>` But the page could not load. With out i frame its working. How do i load this view in iframe ?
2013/03/19
['https://Stackoverflow.com/questions/15501034', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1939388/']
create a function in your controller ``` //project.php function view_list() { $this->load->view('lists'); } ``` and call in the view page like this ``` <iframe src="<?php echo site_url('project/view_list');?>">> </iframe> ```
I wanted to tile a site with several views, each in their own iframe, this is what I did: The controller, **book.php** ``` <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Book extends CI_Controller { public function index(){ $this->shell(); } public function shell(){ $data['title'] = "Home"; $data['frames'] = array( "book/events" ,"book/sales" ,"book/purchases" ,"book/cashflows" ); $this->load->view("shell", $data); } public function events(){ $this->load->view("events"); } public function sales(){ $this->load->view("sales"); } public function purchases(){ $this->load->view("purchases"); } public function cashflows(){ $this->load->view("cashflows"); } } ``` The view **shell.php** contains a foreach statement letting me pass in tiles dynamically. Note how the url's to each site are written in the controller above ^^ (eg. "book/events"). ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title><?php echo $title ?></title> </head> <body> <?php foreach ($frames as $frame):?> <iframe src="<?php echo $frame?>"></iframe> <?php endforeach;?> <div class="footer"> Page rendered in <strong>{elapsed_time}</strong> seconds</p> </div> </body> </html> ``` Then each tile is simply it's own site, like so: ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Events</title> </head> <body> <div class="header">Events</div> <div class="content"> Bla bla bla you have no money</div> <div class="footer"> Page rendered in <strong>{elapsed_time}</strong> seconds</p> </div> </body> </html> ```
4,381,225
I have a database called RankHistory that is populated daily with each user's username and rank for the day (rank as in 1,2,3,...). I keep logs going back 90 days for every user, but my user base has grown to the point that the MySQL database holding these logs is now in excess of 20 million rows. This data is recorded solely for the use of generating a graph showing how a user's rank has changed for the past 90 days. Is there a better way of doing this than having this massive database that will keep growing forever?
2010/12/07
['https://Stackoverflow.com/questions/4381225', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/115182/']
How great is the need for historic data in this case? My first thought would be to truncate data older than a certain threshold, or move it to an archive table that doesn't require as frequent or fast access as your current data. You also mention keeping 90 days of data per user, but the data is only used to show a graph of changes to rank over the past 30 days. Is the extra 60 days' data used to look at changes over previous periods? If it isn't strictly necessary to keep that data (or at least not keep it in your primary data store, as per my first suggestion), you'd neatly cut the quantity of your data by two-thirds. Do we have the full picture, though? If you have a daily record per user, and keep 90 days on hand, you must have on the order of a quarter-million users if you've generated over twenty million records. Is that so? **Update:** Based on the comments below, here are my thoughts: If you have hundreds of thousands of users, and must keep a piece of data for each of them, every day for 90 days, then you will eventually have millions of pieces of data - there's no simple way around that. What you can look into is *minimizing* that data. If all you need to present is a calculated rank per user per day, and assuming that rank is simply a numeric position for the given user among all users (an integer between 1 - 200000, for example), storing twenty million such records should not put unreasonable strain on your database resources. So, what precisely is your concern? Sheer data size (i.e. hard-disk space consumed) should be relatively manageable under the scenario above. You should be able to handle performance via indexes, to a certain point, beyond which the data truncation and partitioning concepts mentioned can come into play (keep blocks of users in different tables or databases, for example, though that's not an ideal design...) Another possibility is, though the specifics are somewhat beyond my realm of expertise, you seem to have an ideal candidate for an [OLAP cube](http://training.inet.com/OLAP/Cubes.htm), here: you have a fact (rank) that you want to view in the context of two dimensions (user and date). There are tools out there for managing this sort of scenario efficiently, even on very large datasets.
Could you run an automated task like a cron job that checks the database every day or week and deletes entries that are more than 90 days old?
4,381,225
I have a database called RankHistory that is populated daily with each user's username and rank for the day (rank as in 1,2,3,...). I keep logs going back 90 days for every user, but my user base has grown to the point that the MySQL database holding these logs is now in excess of 20 million rows. This data is recorded solely for the use of generating a graph showing how a user's rank has changed for the past 90 days. Is there a better way of doing this than having this massive database that will keep growing forever?
2010/12/07
['https://Stackoverflow.com/questions/4381225', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/115182/']
How great is the need for historic data in this case? My first thought would be to truncate data older than a certain threshold, or move it to an archive table that doesn't require as frequent or fast access as your current data. You also mention keeping 90 days of data per user, but the data is only used to show a graph of changes to rank over the past 30 days. Is the extra 60 days' data used to look at changes over previous periods? If it isn't strictly necessary to keep that data (or at least not keep it in your primary data store, as per my first suggestion), you'd neatly cut the quantity of your data by two-thirds. Do we have the full picture, though? If you have a daily record per user, and keep 90 days on hand, you must have on the order of a quarter-million users if you've generated over twenty million records. Is that so? **Update:** Based on the comments below, here are my thoughts: If you have hundreds of thousands of users, and must keep a piece of data for each of them, every day for 90 days, then you will eventually have millions of pieces of data - there's no simple way around that. What you can look into is *minimizing* that data. If all you need to present is a calculated rank per user per day, and assuming that rank is simply a numeric position for the given user among all users (an integer between 1 - 200000, for example), storing twenty million such records should not put unreasonable strain on your database resources. So, what precisely is your concern? Sheer data size (i.e. hard-disk space consumed) should be relatively manageable under the scenario above. You should be able to handle performance via indexes, to a certain point, beyond which the data truncation and partitioning concepts mentioned can come into play (keep blocks of users in different tables or databases, for example, though that's not an ideal design...) Another possibility is, though the specifics are somewhat beyond my realm of expertise, you seem to have an ideal candidate for an [OLAP cube](http://training.inet.com/OLAP/Cubes.htm), here: you have a fact (rank) that you want to view in the context of two dimensions (user and date). There are tools out there for managing this sort of scenario efficiently, even on very large datasets.
Another option, do can you create some "roll-up" aggregate per user based on whatever the criteria is... counts, sales, whatever and it is all stored based on employee + date of activity. Then you could have your pre-aggregated rollups in a much smaller table for however long in history you need. Triggers, or nightly procedures can run a query for the day and append the results to the daily summary. Then your queries and graphs can go against that without dealing with performance issues. This would also help ease moving such records to a historical database archive. -- uh... oops... that's what it sounded like you WERE doing and STILL had 20 million+ records... is that correct? That would mean you're dealing with about 220,000+ users??? 20,000,000 records / 90 days = about 222,222 users EDIT -- from feedback. Having 222k+ users, I would seriously consider that importance it is for "Ranking" when you have someone in the 222,222nd place. I would pair the daily ranking down to say the top 1,000. Again, I don't know the importance, but if someone doesn't make the top 1,000 does it really matter???
127,322
In the context of testing using hardhat... **The scenario:** My `token` is transfering from `owner` to `receiverContract`. I want to check that receiverContract emitted a `Received` event. The transaction looks like this and is initiated by the owner. ```js const tx = await token.transferFrom( owner.address, // <- From this wallet receiverContract.address, // <- To this contract tokenId, { from: owner.address, } ); ``` How can I check if receiverContract emitted a "Received" event? Alternatively, if someone can solve this problem with `@openzeppelin/test-helpers` `expectEvent.inTransaction()` that works too. Edit: The receiver contract code emits an event when it receives something. So we can assume it emits. I just need to write a test for it. I'm not interested in testing for the `Transfer` event on the token itself.
2022/05/02
['https://ethereum.stackexchange.com/questions/127322', 'https://ethereum.stackexchange.com', 'https://ethereum.stackexchange.com/users/68369/']
I figured out how to do it. Each contract can be viewed via `console.log(receiverContract)`... so I eventually navigated to the event object inside the contract. Here is a snippet of the contract when logged... ```js { interface: Interface { fragments: [ [ConstructorFragment], [EventFragment], [FunctionFragment] ], _abiCoder: AbiCoder { coerceFunc: null }, functions: { 'onERC721Received(address,address,uint256,bytes)': [FunctionFragment] }, errors: {}, events: { // <- This is what we're looking for 'Received(address,address,uint256,bytes,uint256)': [EventFragment { name: 'Received', anonymous: false, inputs: [ [ParamType], [ParamType], [ParamType], [ParamType], [ParamType] ], type: 'event', _isFragment: true }], // ... } ``` Running `console.log(receiverContract.interface.events)` gives you this nested object ```js 'Received(address,address,uint256,bytes,uint256)', EventFragment { name: 'Received', // <- This is the event name anonymous: false, inputs: [ [ParamType], [ParamType], [ParamType], [ParamType], [ParamType] ], type: 'event', _isFragment: true } ``` So in order to look for and test that the event emitted, this works ```js expect( Object.entries(receiverContract.interface.events).some( ([k, v]: any) => v.name === "Received" ) ).to.be.equal(true); ```
Since there's no interaction with the receiving contract, it will not emit anything. Transaction is sent to the token, which emits `Transfer` event once it changes records of its ledger. You can watch the token for `Transfer` event, or read the transaction receipt, decode the log and check for that event.
127,322
In the context of testing using hardhat... **The scenario:** My `token` is transfering from `owner` to `receiverContract`. I want to check that receiverContract emitted a `Received` event. The transaction looks like this and is initiated by the owner. ```js const tx = await token.transferFrom( owner.address, // <- From this wallet receiverContract.address, // <- To this contract tokenId, { from: owner.address, } ); ``` How can I check if receiverContract emitted a "Received" event? Alternatively, if someone can solve this problem with `@openzeppelin/test-helpers` `expectEvent.inTransaction()` that works too. Edit: The receiver contract code emits an event when it receives something. So we can assume it emits. I just need to write a test for it. I'm not interested in testing for the `Transfer` event on the token itself.
2022/05/02
['https://ethereum.stackexchange.com/questions/127322', 'https://ethereum.stackexchange.com', 'https://ethereum.stackexchange.com/users/68369/']
I figured out how to do it. Each contract can be viewed via `console.log(receiverContract)`... so I eventually navigated to the event object inside the contract. Here is a snippet of the contract when logged... ```js { interface: Interface { fragments: [ [ConstructorFragment], [EventFragment], [FunctionFragment] ], _abiCoder: AbiCoder { coerceFunc: null }, functions: { 'onERC721Received(address,address,uint256,bytes)': [FunctionFragment] }, errors: {}, events: { // <- This is what we're looking for 'Received(address,address,uint256,bytes,uint256)': [EventFragment { name: 'Received', anonymous: false, inputs: [ [ParamType], [ParamType], [ParamType], [ParamType], [ParamType] ], type: 'event', _isFragment: true }], // ... } ``` Running `console.log(receiverContract.interface.events)` gives you this nested object ```js 'Received(address,address,uint256,bytes,uint256)', EventFragment { name: 'Received', // <- This is the event name anonymous: false, inputs: [ [ParamType], [ParamType], [ParamType], [ParamType], [ParamType] ], type: 'event', _isFragment: true } ``` So in order to look for and test that the event emitted, this works ```js expect( Object.entries(receiverContract.interface.events).some( ([k, v]: any) => v.name === "Received" ) ).to.be.equal(true); ```
The ERC20 contract transaction is sent to the token contract itself, and not to the receiving contract, hence there cannot be any event emitted from the receiving contract. A receiving contract can emit any event only if it has been configured in either the `receive()` or `fallback()` method. That too, while sending `msg.value` to it i.e. ETH, BNB, etc. (the receiving contract's chain's native crypto). If you just want to make sure that the receiving contract has received the tokens, you can check the `Transfer` event emitted by the ERC20 token contract. You want suggestions on `@openzeppelin/test-helpers`, I've not used it but you can use the `expectEvent()` function to check it. Something like (NOT TESTED): ``` const tx = await token.transferFrom( owner.address, // <- From this wallet receiverContract.address, // <- To this contract tokenId, { from: owner.address, } ); expectEvent(tx, 'Transfer', { from: owner.address, // <- From this wallet to: receiverContract.address, // <- To this contract value: tokenId, }); ```
23,404
When widening a road, why does construction seem to inevitably include a "smoothing" out of the curves on the road, essentially making it more straight? I've seen this personally on roads where I travel, and you can even catch a glimpse on Google satellite imagery of roads that are in the widening process: Google overlays a "ghost" lane to show where the new lanes of the road will be. It's faint, but you can see an example here on a road near Flowery Branch, GA: [![enter image description here](https://i.stack.imgur.com/xO3WZ.png)](https://i.stack.imgur.com/xO3WZ.png) Is this the engineers' way of correcting previous mistakes, or a response to devleopment that's sprung up around the road since its initial construction, or safety reasons? Or something else entirely?
2018/08/22
['https://engineering.stackexchange.com/questions/23404', 'https://engineering.stackexchange.com', 'https://engineering.stackexchange.com/users/17255/']
A wider road will have faster average traffic speeds, because faster vehicles will be hindered less by slow ones, with more lanes available for overtaking. So longer visibility distances are needed for safety, and hence more gradual curves and more gradual changes of gradient (no "hidden spots" over the brow of a hill, etc). Note, for most "fast" roads traffic speeds are not limited at all by the radius of the curves, except perhaps in very severe weather conditions (snow and ice, standing rainwater, etc). Aside from breaking the law and the hazards posed by other vehicles, there would be no problem in driving a modern vehicle along the road way above the legal speed limit.
I am familiar with this effect; with careful observation you can count at least three rounds of road-straightening on highway 17 between the cities of San Jose and Santa Cruz in California. The first road was built over 100 years ago and carried horse-drawn wagons. At the time, moving large volumes of earth and rock was more expensive than surfacing the road and so it followed sharp curves in the mountainsides instead of being extensively built on fill from nearby road cuts. Then came automobiles and more and faster traffic, and when widening the original stage road the sharpest turns were rounded off to carry faster vehicles and cut-and-fill was used so the mountain contours didn't have to be closely followed. At each step in this decades-long process, the cost of earthmoving fell and the cost of pavement rose, and so it became economical to use more and more cut-and-fill in conjunction with straighter and straighter road paths. The stage road is now a 4-lane freeway which still has a few somewhat sharp turns in it but much of it is built by cut-and-fill and can be traversed at 50 to 60 MPH.
4,627,682
This is an extremely elementary question but I want to make sure I understand this right. If someone adds two numbers in their mind and tells us the sum, it is impossible to prove mathematically what two numbers they chose (in most cases). The number of distinct ways to add two numbers to form say, an integer $n$, is something like $ceil((N+1)/2)$ ([here](https://math.stackexchange.com/questions/3034937/how-many-ways-can-a-number-be-written-as-a-sum-of-two-non-negative-integers)). This shows us that there is more than one way, for any number from 2 and beyond. I think I am thinking about a function mapping each pair of elements to its sum, and observing that it is not injective. I am just trying to understand why. As integers are sort of the conceptual basis for the concept of a group (I think), is the fact that different elements can combine to form the same element a result of "closure", in that, when we look at the Cayley table of a group, we will see each element of the group exactly once? So is it a necessary condition on any group that the function (x, y) -> (x + y) can not be bijective? Or is there any relationship between groups cycles and elements having unique composition? Maybe I am completely off-track here but I am trying to ask the fundamental question of why addition is not reversible and what kind of related structure does on the other hand have that property. What deep difference in structure or properties do they have, allowing this?
2023/01/28
['https://math.stackexchange.com/questions/4627682', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/990260/']
If you want 4, 1+3 and 2+2 to be separate elements of your collection, then you should also be able to involve these elements in sums separately. so 5+4, 5+(1+3), and 5+(2+2) should all be different elements of your structure as well. Consider the set of expressions built up out of base elements via binary sums, with the trivial operation of addition being "add parentheses and stick a + sign between". So addition takes 5 and 4 as inputs and outputs 5+4 and addition takes 5 and 1+3 as inputs and outputs 5+(1+3). This is a reasonable operation, but it's not associative (we view 5+(1+3) and (5+1)+3 as different expressions) and it doesn't have inverses, so it's not a group. If you want a group, the operation on the one element group is bijective.
Multiplication of prime numbers is reversible, in the sense that any positive integer is expressible as a product of primes in just one way (not counting changing order...). (The computational difficulty of reversing the operation, that is, of *factoring* versus multiplying, is the basis of the RSA cryptosystem and other things...)
21,922,305
I have read that the `role` attribute was added to [Bootstrap](http://getbootstrap.com/) for accessibility, and I would like to know how `<form role="form">` helps accessibility. See <http://getbootstrap.com/css/#forms-example> for an example of this specific usage. *I [searched Bootstrap's repo for "role"](https://github.com/twbs/bootstrap/search?q=role) to no avail.* My issue is that the information seems redundant. The notion that the element is a *form* is already expressed by the HTML tag itself (`<form>`), so what does it help if we also add that the element is playing the `role` of `form`? It would make sense to add `role="..."` if `role` was going to be different than `form` (I don't know what - but let's pretend); as it stands (especially without concrete reasoning / use case examples), it is puzzling at best.
2014/02/20
['https://Stackoverflow.com/questions/21922305', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/664833/']
If you add a `role="form"` to a form, a screen reader sees it as a region on a webpage. That means that a user can easily jump to the form with his/her region quick navigation keys (for example, in JAWS 15 you use *R* for this). And also, your user will be able to easily find where the form starts and ends because screen readers mark start and end of regions.
Semantically speaking, a form by default is, well, a form. However, not all accessibility applications(screen readers, etc) are designed the same and some can use elements (even the form element) with the `role=form` attribute differently even if they understand that the parent form element will have the same semantic meaning with or without the `role=form` attribute.
21,922,305
I have read that the `role` attribute was added to [Bootstrap](http://getbootstrap.com/) for accessibility, and I would like to know how `<form role="form">` helps accessibility. See <http://getbootstrap.com/css/#forms-example> for an example of this specific usage. *I [searched Bootstrap's repo for "role"](https://github.com/twbs/bootstrap/search?q=role) to no avail.* My issue is that the information seems redundant. The notion that the element is a *form* is already expressed by the HTML tag itself (`<form>`), so what does it help if we also add that the element is playing the `role` of `form`? It would make sense to add `role="..."` if `role` was going to be different than `form` (I don't know what - but let's pretend); as it stands (especially without concrete reasoning / use case examples), it is puzzling at best.
2014/02/20
['https://Stackoverflow.com/questions/21922305', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/664833/']
If you add a `role="form"` to a form, a screen reader sees it as a region on a webpage. That means that a user can easily jump to the form with his/her region quick navigation keys (for example, in JAWS 15 you use *R* for this). And also, your user will be able to easily find where the form starts and ends because screen readers mark start and end of regions.
I'd like to point out that the article @user664833 mentioned in a [comment](https://stackoverflow.com/questions/21922305/how-does-role-form-help-accessibility#comment33241849_21922985) states that **`role="form"` shouldn't go on `<form>` elements**, but rather on a `<div>` or some other element which does not semantically indicate that it contains form elements. **The `<form>` element** is probably already **handled properly** by modern screen readers. [Quote (link):](https://www.paciellogroup.com/blog/2013/02/using-wai-aria-landmarks-2013/#tablex) > > Recommend using [`role="form"`] on a semantically neutral element such as a `<div>` not on a `<form>` element, as the element already has **default role semantics exposed**. > > >
21,922,305
I have read that the `role` attribute was added to [Bootstrap](http://getbootstrap.com/) for accessibility, and I would like to know how `<form role="form">` helps accessibility. See <http://getbootstrap.com/css/#forms-example> for an example of this specific usage. *I [searched Bootstrap's repo for "role"](https://github.com/twbs/bootstrap/search?q=role) to no avail.* My issue is that the information seems redundant. The notion that the element is a *form* is already expressed by the HTML tag itself (`<form>`), so what does it help if we also add that the element is playing the `role` of `form`? It would make sense to add `role="..."` if `role` was going to be different than `form` (I don't know what - but let's pretend); as it stands (especially without concrete reasoning / use case examples), it is puzzling at best.
2014/02/20
['https://Stackoverflow.com/questions/21922305', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/664833/']
If you add a `role="form"` to a form, a screen reader sees it as a region on a webpage. That means that a user can easily jump to the form with his/her region quick navigation keys (for example, in JAWS 15 you use *R* for this). And also, your user will be able to easily find where the form starts and ends because screen readers mark start and end of regions.
In fact, the ARIA 1.1 W3C recommendation states clearly one should not change the host language semantics in section 1.4 ([source](https://www.w3.org/TR/wai-aria-1.1/#co-evolution)): > > "It is not appropriate to create objects with style and script when > the host language provides a semantic element for that type of object. > While WAI-ARIA can improve the accessibility of these objects, > accessibility is best provided by allowing the user agent to handle > the object natively." > > > So, writing `<form role='form'>` is not only redundant but against the recommendation.
21,922,305
I have read that the `role` attribute was added to [Bootstrap](http://getbootstrap.com/) for accessibility, and I would like to know how `<form role="form">` helps accessibility. See <http://getbootstrap.com/css/#forms-example> for an example of this specific usage. *I [searched Bootstrap's repo for "role"](https://github.com/twbs/bootstrap/search?q=role) to no avail.* My issue is that the information seems redundant. The notion that the element is a *form* is already expressed by the HTML tag itself (`<form>`), so what does it help if we also add that the element is playing the `role` of `form`? It would make sense to add `role="..."` if `role` was going to be different than `form` (I don't know what - but let's pretend); as it stands (especially without concrete reasoning / use case examples), it is puzzling at best.
2014/02/20
['https://Stackoverflow.com/questions/21922305', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/664833/']
I'd like to point out that the article @user664833 mentioned in a [comment](https://stackoverflow.com/questions/21922305/how-does-role-form-help-accessibility#comment33241849_21922985) states that **`role="form"` shouldn't go on `<form>` elements**, but rather on a `<div>` or some other element which does not semantically indicate that it contains form elements. **The `<form>` element** is probably already **handled properly** by modern screen readers. [Quote (link):](https://www.paciellogroup.com/blog/2013/02/using-wai-aria-landmarks-2013/#tablex) > > Recommend using [`role="form"`] on a semantically neutral element such as a `<div>` not on a `<form>` element, as the element already has **default role semantics exposed**. > > >
Semantically speaking, a form by default is, well, a form. However, not all accessibility applications(screen readers, etc) are designed the same and some can use elements (even the form element) with the `role=form` attribute differently even if they understand that the parent form element will have the same semantic meaning with or without the `role=form` attribute.
21,922,305
I have read that the `role` attribute was added to [Bootstrap](http://getbootstrap.com/) for accessibility, and I would like to know how `<form role="form">` helps accessibility. See <http://getbootstrap.com/css/#forms-example> for an example of this specific usage. *I [searched Bootstrap's repo for "role"](https://github.com/twbs/bootstrap/search?q=role) to no avail.* My issue is that the information seems redundant. The notion that the element is a *form* is already expressed by the HTML tag itself (`<form>`), so what does it help if we also add that the element is playing the `role` of `form`? It would make sense to add `role="..."` if `role` was going to be different than `form` (I don't know what - but let's pretend); as it stands (especially without concrete reasoning / use case examples), it is puzzling at best.
2014/02/20
['https://Stackoverflow.com/questions/21922305', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/664833/']
In fact, the ARIA 1.1 W3C recommendation states clearly one should not change the host language semantics in section 1.4 ([source](https://www.w3.org/TR/wai-aria-1.1/#co-evolution)): > > "It is not appropriate to create objects with style and script when > the host language provides a semantic element for that type of object. > While WAI-ARIA can improve the accessibility of these objects, > accessibility is best provided by allowing the user agent to handle > the object natively." > > > So, writing `<form role='form'>` is not only redundant but against the recommendation.
Semantically speaking, a form by default is, well, a form. However, not all accessibility applications(screen readers, etc) are designed the same and some can use elements (even the form element) with the `role=form` attribute differently even if they understand that the parent form element will have the same semantic meaning with or without the `role=form` attribute.
27,997
Suppose I have a tesselation, e.g. the Stanford bunny: ``` bunny = Import["http://graphics.stanford.edu/~mdfisher/Data/Meshes/bunny.obj", "OBJ"] ``` ![Stanford bunny](https://i.stack.imgur.com/lOysk.png) I'd like to be able to click on one of the vertices of the tessellation and either get its coordinates, or even better, its index in the `GraphicsComplex`. Is there a way to do this?
2013/07/03
['https://mathematica.stackexchange.com/questions/27997', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/1010/']
The following works pretty well, I think. The problem is choosing the point that is nearest the mouse click. `MousePosition["Graphics3DBoxIntercepts"]` returns the coordinates of the two points of the bounding box below the mouse click, which I think of as determining a line. The function `projCoords` converts the points in the bunny to "coordinates" that are the distance from the line determined by these points divided by 10 and the distance of the projection of the vector from the front mouse-click intercept to the point on the bunny. The "divide by 10" factor makes the distance from the line dominant. Sometimes a point behind the surface may be chosen, especially in non-convex regions where there are not many points in front that are close to the line. If 10 is made much smaller, then a point close to the front box intercept but far from the line may be chosen. The point and the index in the `GraphicsComplex` are shown in the plot label. ``` bunny = Import["http://graphics.stanford.edu/~mdfisher/Data/Meshes/bunny.obj", "OBJ"]; projCoords[{v1_, v2_}] := (* #/10 emphasizes distance from line of sight *) Function[{u}, Norm /@ ({#/10, u - v1 - #} &@Projection[u - v1, v2 - v1])] DynamicModule[{img = bunny, pts0, clicked = {}, mp = {}}, Cases[img, GraphicsComplex[pts_, ___] :> (pts0 = pts), Infinity, 1]; EventHandler[ MouseAppearance[ Show[img, Graphics3D[{Red, PointSize[Large], Dynamic@If[VectorQ[clicked, NumericQ], {Point[clicked], Blue, Line[mp]}, {}]}], Boxed -> True, Axes -> True, AxesLabel -> {x, y, z}, PlotLabel -> Dynamic[{clicked, Position[pts0, clicked]}], AbsoluteOptions[img, PlotRange], SphericalRegion -> True], "Arrow"], {"MouseClicked" :> ({clicked} = Nearest[(projCoords[mp = MousePosition["Graphics3DBoxIntercepts"]] /@ pts0) -> pts0, {0, 0}])}, PassEventsDown -> True] ] ``` ![Bunny with selected point](https://i.stack.imgur.com/3ewJE.png) The option `PassEventsDown -> True` allows the bunny to be rotated. **Edit**: Added `PlotRange` control and a `MouseAppearance` that makes it easier to pinpoint a vertex.
Perhaps you can use something like this: I took the points in the `GraphisComplex` and made an additional set of `Point`s representing the vertices in `Yellow`. The points are extracted and then put back by means of a replacement rule: ``` data = ExampleData[{"Geometry3D", "StanfordBunny"}, "VertexData"]; bunny = ListSurfacePlot3D[data, MaxPlotPoints -> 50, Boxed -> False, Axes -> None, Mesh -> False, PlotStyle -> Brown]; Print@Show[ bunny /. g_GraphicsComplex :> GraphicsComplex[g[[1]], Join[g[[2]], {Opacity[0.5], Yellow, PointSize[.01], Tooltip[Point[#], #] & /@ Range[Length[g[[1]]]]}]], ImageSize -> 500 ] ``` ![bunny](https://i.stack.imgur.com/DLadx.png) You can still use the mouse to drag and rotate the object, but when you hover over a vertex (which sticks out of the surface as a yellow object), the index of that point in the `GraphicsComplex` is displayed as a `Tooltip`. I thought this is better than making the vertices clickable because that interferes with the 3D rotation. The extra `Print` in front of the `Show` is needed in order to suppress a warning triggered by the large size of the `Graphics3D` output. **Edit** If you want something that respons to mouse clicks in a useful way, it's straightforward to combine the above approach with [another answer](https://mathematica.stackexchange.com/a/16927/245) where I showed a way to convert `Tooltip` into `Button` objects. If you then use the `toolSpoolRule` from that answer, you can get a *permanent record* of the vertices that you have clicked, in the form of a `List` on the `Clipboard` which can be pasted anywhere you want. Here I repeat the only additional definition we need: ``` toolSpoolRule = Tooltip[t__] :> Button[Tooltip[t], CopyToClipboard[ First@Append[ Cases[NotebookGet[ClipboardNotebook[]], TooltipBox[x_, "\"Clicked Points\"", ___] :> Tooltip[Append[ToExpression[x], Last[{t}]], "Clicked Points"], Infinity], Tooltip[{Last[{t}]}, "Clicked Points"]]]]; ``` Now replace the plot command by the following: ``` Print[ Show[bunny /. g_GraphicsComplex :> GraphicsComplex[g[[1]], Join[g[[2]], {Opacity[0.5], Yellow, PointSize[.01], Tooltip[Point[#], #] & /@ Range[Length[g[[1]]]]}]], ImageSize -> 500] /. toolSpoolRule ] ``` You get visually the same output, but when you see a `Tooltip` appearing near a vertex that you hover on, you can now click the mouse to *add the vertex index to the clipboard*. When you're done, press the paste keys and you get a list of the clicked vertices.
68,397,282
Regardless of the JSON object structure (simple or complex) what would be the ideal method to extract all urls from the following object into an array to iterate over in Javascript? ``` { "url": "https://example.com:443/-/media/images/site/info", "data": [ { "id": "da56fac6-6907-4055-96b8-f8427d4c64fd", "title": "AAAA 2021", "time": "", "dateStart": "2021-03-01T08:00:00Z", "dateEnd": "2021-12-31T15:00:00Z", "address": "", "geo": { "longitude": "", "latitude": "", "mapExternalLink": "" }, "price": "Free Admission", "masonryImage": "https://example.com:443/-/media/images/site/siteimages/tcsm2021/fullwidthbanner/tcsmfullwidthicecream.ashx", "image": "https://example.com:443/-/media/images/site/siteimages/tcsm2021/fullwidthbanner/tcsmfullwidthicecream.ashx", "showDateInfo": false, "showDateInfoOnListings": false, "showTimeInfo": false, "showTimeInfoOnListings": false, "tags": [ { "key": "Lifestyle", "name": "Lifestyle" } ], "partnerName": "", "sort_data": { "recommended": 0, "recent": 3, "partner": 0, "popular": 0 } } ] } ``` I would like to get the results in an array such as: ``` [ https://example.com:443/-/media/images/site/info,https://example.com:443/-/media/images/site/siteimages/tcsm2021/fullwidthbanner/tcsmfullwidthicecream.ashx, https://example.com:443/-/media/images/site/siteimages/tcsm2021/fullwidthbanner/tcsmfullwidthicecream.ashx ] ``` I gather that i would need to apply some regex to extract the urls but not sure how to treat the json object as string for regex processing?
2021/07/15
['https://Stackoverflow.com/questions/68397282', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/358649/']
I think the better and easier way is to stringfy given json into string and solve it by regex. But still if you need to solve it by recursive, try the codes below: ``` const obj = { url: "https://example.com:443/-/media/images/site/info", data: [ { id: "da56fac6-6907-4055-96b8-f8427d4c64fd", title: "AAAA 2021", time: "", dateStart: "2021-03-01T08:00:00Z", dateEnd: "2021-12-31T15:00:00Z", address: "", geo: { longitude: "", latitude: "", mapExternalLink: "", }, price: "Free Admission", masonryImage: "https://example.com:443/-/media/images/site/siteimages/tcsm2021/fullwidthbanner/tcsmfullwidthicecream.ashx", image: "https://tw.yahoo.com", showDateInfo: false, showDateInfoOnListings: false, showTimeInfo: false, showTimeInfoOnListings: false, tags: [ { key: "Lifestyle", name: "Lifestyle", link: "https://www.google.com", }, ], partnerName: "", sort_data: { recommended: 0, recent: 3, partner: 0, popular: 0, anotherObj: { link: "https://www.github.com", }, }, }, ], }; function getUrl(obj) { const ary = []; helper(obj, ary); return ary; } function helper(item, ary) { if (typeof item === "string" && isUrl(item)) { ary.push(item); return; } else if (typeof item === "object") { for (const k in item) { helper(item[k], ary); } return; } return null; } function isUrl(str) { if (typeof str !== "string") return false; return /http|https/.test(str); } console.log(getUrl(obj)); ``` But if you use this solution you need to transfer your json into js object
i'd agree to use a JSON parser, but if you want to do it with a regular expression, you might try this ```js console.log(JSON.stringify({ "url": "https://example.com:443/-/media/images/site/info", "data": [{ "id": "da56fac6-6907-4055-96b8-f8427d4c64fd", "title": "AAAA 2021", "time": "", "dateStart": "2021-03-01T08:00:00Z", "dateEnd": "2021-12-31T15:00:00Z", "address": "", "geo": { "longitude": "", "latitude": "", "mapExternalLink": "" }, "price": "Free Admission", "masonryImage": "https://example.com:443/-/media/images/site/siteimages/tcsm2021/fullwidthbanner/tcsmfullwidthicecream.ashx", "image": "https://example.com:443/-/media/images/site/siteimages/tcsm2021/fullwidthbanner/tcsmfullwidthicecream.ashx", "showDateInfo": false, "showDateInfoOnListings": false, "showTimeInfo": false, "showTimeInfoOnListings": false, "tags": [{ "key": "Lifestyle", "name": "Lifestyle" }], "partnerName": "", "sort_data": { "recommended": 0, "recent": 3, "partner": 0, "popular": 0 } }] }).match(/(?<=")https?:\/\/[^\"]+/g)); ``` `(?<=")https?:\/\/[^\"]+` basically finds patterns that start with a protocol scheme (http:// or https:// preceded by a `"` character) followed by anything that is *not* `"`
50,848,178
I tried to make a odd/even 'calculator' in python and it keeps popping up errors. Here's the code: ``` def odd_even(): print("Welcome to Odd/Even") num = input("Pick a number: ") num2 = num/2 if num2 == int: print("This number is even") else: print("This number is odd") ``` Id like to know whats causing the errors and solutions to them
2018/06/14
['https://Stackoverflow.com/questions/50848178', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9394239/']
There is an error in the line: `num = input("Pick a number: ")` Because input method always returns a `String`,so you should convert it into int to performs the `integer` operation The currect code is: ``` num =int( input("Pick a number: ")) ```
you can't do math with strings convert it to int ``` try: num = int(input("Pick a number: ")) except ValueError: print('This is not a number!') return ```
52,041,232
Here is my problem, I would like to map a dictionary in a DataFrame but I cannot find a way to do that when the dictionary has several keys. Note that these keys are present in different columns in the DataFrame. Here is an example: this is the dataframe I have at the begining, df: ``` Index key 0 10 k1 1 12 k2 2 3 k1 3 34 k3 ``` here is the dictionary I have, d: ``` {('k1', 10):v1,('k1', 3):v2,('k2', 12):v3,('k3', 34):v4} ``` I would like to have at the end, df: ``` Index key value 0 10 k1 v1 1 12 k2 v2 2 3 k1 v3 3 34 k3 v4 ``` is there a way to do that the same way that you can do that when you have a one key dictionary : > > df["value"] = df["key"].map(d) > > > thank you in advance.
2018/08/27
['https://Stackoverflow.com/questions/52041232', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10028348/']
It is explained in the [Java Language Specification](https://docs.oracle.com/javase/specs/jls/se10/html/jls-11.html#jls-11.2.3) (emphasis in bold): > > It is a compile-time error if a `catch` clause *can catch* checked exception class E1 and it is not the case that the `try` block corresponding to the `catch` clause *can throw* a checked exception class that is a subclass or superclass of E1, **unless E1 is `Exception` or a superclass of `Exception`.** > > > I guess the rationale behind this is that: `MyException` is indeed a checked exception. However, unchecked exceptions also extend `Exception` (transitive inheritance from `RuntimeException`), so having a `catch` include the `Exception` class is excluded from the exception analysis done by the compiler.
Exception extends from `RuntimeException` will considered as uncheched exception, so it's ok: ``` class MyException extends RuntimeException { } try { ... } catch (MyException e) { } ``` Your exception extends from `Throwable`, so it is cheched exception. Since the compiler noticed that it is never thrown, so the compile fails.
30,365,008
Hi guys i'm doing some automations scripts with Watir and trying to create a ruby class to make it better but i'm having this error: > > examen.rb:6:in 'enterEmail': undefined method 'text\_field' for # (NoMethodError) > > > This is part of my conflictive code: ``` require 'watir-webdriver' class LoginPage def enterEmail (email) text_field(:user, :id => 'user_email').set email end end ``` The problem that i see is: i did not define the 'text\_field()' method in my class just because is a Watir method... Anyone knows how can i use the watir method in the classes that i create?
2015/05/21
['https://Stackoverflow.com/questions/30365008', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3247357/']
`text_field` is an instance method of The `Watir::Browser` class. If you want to use it, you have to call it on an instance of that class. ``` class LoginPage def initialize() @b = Watir::Browser.new end def enterEmail (email) @b.text_field(:user, :id => 'user_email').set email end end ```
Indeed, your class does not have any `text_field` method. This method is a defined on `Watir::Browser` instance. In your example, haven't created one. ``` class LoginPage def initialize @browser = Watir::Browser.new @browser.goto "http://example.com" end def enterEmail (email) @browser.text_field(:user, :id => 'user_email').set email end end ```
30,365,008
Hi guys i'm doing some automations scripts with Watir and trying to create a ruby class to make it better but i'm having this error: > > examen.rb:6:in 'enterEmail': undefined method 'text\_field' for # (NoMethodError) > > > This is part of my conflictive code: ``` require 'watir-webdriver' class LoginPage def enterEmail (email) text_field(:user, :id => 'user_email').set email end end ``` The problem that i see is: i did not define the 'text\_field()' method in my class just because is a Watir method... Anyone knows how can i use the watir method in the classes that i create?
2015/05/21
['https://Stackoverflow.com/questions/30365008', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3247357/']
`text_field` is an instance method of The `Watir::Browser` class. If you want to use it, you have to call it on an instance of that class. ``` class LoginPage def initialize() @b = Watir::Browser.new end def enterEmail (email) @b.text_field(:user, :id => 'user_email').set email end end ```
Both Yossi and Martin have correct answers. But because you're defining a `LoginPage` class, you should probably look into the [page-object](http://github.com/cheezy/page-object) gem. This lets you define a `text_field` almost identical to the code you already have. Your class would look like: ``` class LoginPage include PageObject text_field(:user, :id => 'user_email') def enter_email(email) self.user = email end end ``` And you'd execute it like: ``` login = LoginPage.new(browser) login.enter_email("my_email@example.com") ```
9,324,563
Consider the following registry export: ```none Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\WinSock2\Parameters\Protocol_Catalog9\Catalog_Entries\000000000001] ;... "ProtocolName"="@%SystemRoot%\\System32\\wshtcpip.dll,-60100" ``` The intention here appears to be for someone to load the DLL in question, and use some form of API retrieve the actual name. But I don't know what that API is :/ I'd like to avoid loading the DLL into my address space (and thus call `DLL_PROCESS_ATTACH`) if at all possible; can't really trust third party DLLs to be trustworthy.
2012/02/17
['https://Stackoverflow.com/questions/9324563', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/82320/']
[`RegLoadMUIString`](http://msdn.microsoft.com/en-us/library/windows/desktop/ms724890.aspx) will do the necessary for you. Note however, that it was introduced in Vista so won't help if you need to support XP. If you want to avoid code in the DLL running whilst you extract resources, use [`LoadLibraryEx`](http://msdn.microsoft.com/en-us/library/windows/desktop/ms684179.aspx) passing `LOAD_LIBRARY_AS_IMAGE_RESOURCE | LOAD_LIBRARY_AS_DATAFILE`, or possibly `LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE`. Once you have done that, you can call [`LoadString`](http://msdn.microsoft.com/en-us/library/windows/desktop/ms647486.aspx) to extract the MUI value.
This is going to help: ``` HMODULE hModule = LoadLibrary(_T("wshtcpip.dll")); // LoadLibraryEx is even better TCHAR pszValue[1024] = { 0 }; INT nResult = LoadString(hModule, 60100, pszValue, _countof(pszValue)); ``` `LoadString` will take care of downloading resource from MUI, if needed. LoadString uses thread locale, which you might want to override prior to the call. Also: [Loading Language Resources](http://msdn.microsoft.com/en-us/library/windows/desktop/dd318708%28v=vs.85%29.aspx) on MSDN.
8,609,546
I'm using maven and the maven-javadoc-plugin with the umlgraph-doclet to create javadoc for my project. The part from my pom: ``` <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-site-plugin</artifactId> <inherited>false</inherited> <configuration> <reportPlugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> <version>2.8</version> <configuration> <show>public</show> <quiet>true</quiet> <doclet>org.umlgraph.doclet.UmlGraphDoc</doclet> <docletArtifact> <groupId>org.umlgraph</groupId> <artifactId>doclet</artifactId> <version>5.1</version> </docletArtifact> <useStandardDocletOptions>true</useStandardDocletOptions> <additionalparam> -inferrel -inferdep -quiet -hide java.* -hide org.eclipse.* -collpackages java.util.* -postfixpackage -nodefontsize 9 -nodefontpackagesize 7 -attributes -types -visibility -operations -constructors -enumerations -enumconstants -views </additionalparam> </configuration> <reportSets> <reportSet> <reports> <report>aggregate</report> </reports> </reportSet> </reportSets> </plugin> </reportPlugins> </configuration> </plugin> </plugins> </build> ``` The images are generated and look fine, when building the javadoc with jdk1.6 they get automatically integrated into all javadoc pages. But when building with jdk1.7, the images still get created but are not inside the javadoc pages. Even when using the v5.4 from the official website, the javadoc is imageless. And the debug output of maven also don't give any clue. On top of that, there is no way of contacting one of the UmlGraph devs by mail. Can anyone give me some advice here, or have some ideas how to fix that?
2011/12/22
['https://Stackoverflow.com/questions/8609546', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1094486/']
UmlGraphDoc version 5.4, altering javadocs Warning, could not find a line that matches the pattern '/H2' The HTML is simply different. Java7 JavaDocs START OF CLASS DATA h2 title="blah blah Java6 JavaDocs START OF CLASS DATA H2 You can decompile and modify UmlGraphDoc.java
I have the same problem. My guess is that it's this bug: <https://issues.jboss.org/browse/APIVIZ-10>
8,609,546
I'm using maven and the maven-javadoc-plugin with the umlgraph-doclet to create javadoc for my project. The part from my pom: ``` <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-site-plugin</artifactId> <inherited>false</inherited> <configuration> <reportPlugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> <version>2.8</version> <configuration> <show>public</show> <quiet>true</quiet> <doclet>org.umlgraph.doclet.UmlGraphDoc</doclet> <docletArtifact> <groupId>org.umlgraph</groupId> <artifactId>doclet</artifactId> <version>5.1</version> </docletArtifact> <useStandardDocletOptions>true</useStandardDocletOptions> <additionalparam> -inferrel -inferdep -quiet -hide java.* -hide org.eclipse.* -collpackages java.util.* -postfixpackage -nodefontsize 9 -nodefontpackagesize 7 -attributes -types -visibility -operations -constructors -enumerations -enumconstants -views </additionalparam> </configuration> <reportSets> <reportSet> <reports> <report>aggregate</report> </reports> </reportSet> </reportSets> </plugin> </reportPlugins> </configuration> </plugin> </plugins> </build> ``` The images are generated and look fine, when building the javadoc with jdk1.6 they get automatically integrated into all javadoc pages. But when building with jdk1.7, the images still get created but are not inside the javadoc pages. Even when using the v5.4 from the official website, the javadoc is imageless. And the debug output of maven also don't give any clue. On top of that, there is no way of contacting one of the UmlGraph devs by mail. Can anyone give me some advice here, or have some ideas how to fix that?
2011/12/22
['https://Stackoverflow.com/questions/8609546', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1094486/']
I checked the possibilities, and the situation is following:. * relevant bug in the UmlGraph has been already fixed: <https://github.com/dspinellis/UMLGraph/pull/8> * problem is however that no stable version of UmlGraph has been released yet that would include the fix However good news is that there exists snapshot repository containing the fix: <https://oss.sonatype.org/content/repositories/snapshots/org/umlgraph/umlgraph/5.5.8-SNAPSHOT/> Therefor you need to get the jar file to your local repository (depending on your infrastructure setup): * either by adding reffered repository to your environment * or by importing to your local repo (<http://maven.apache.org/guides/mini/guide-3rd-party-jars-local.html>) afterwards update: ``` <doclet>org.umlgraph.doclet.UmlGraphDoc</doclet> <docletArtifact> <groupId>org.umlgraph</groupId> <artifactId>doclet</artifactId> <version>5.1</version> </docletArtifact> ``` to the following (naming convention has been changed): ``` <doclet>org.umlgraph.doclet.UmlGraphDoc</doclet> <docletArtifact> <groupId>org.umlgraph</groupId> <artifactId>umlgraph</artifactId> <version>5.5.8-SNAPSHOT</version> </docletArtifact> ```
I have the same problem. My guess is that it's this bug: <https://issues.jboss.org/browse/APIVIZ-10>
8,609,546
I'm using maven and the maven-javadoc-plugin with the umlgraph-doclet to create javadoc for my project. The part from my pom: ``` <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-site-plugin</artifactId> <inherited>false</inherited> <configuration> <reportPlugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> <version>2.8</version> <configuration> <show>public</show> <quiet>true</quiet> <doclet>org.umlgraph.doclet.UmlGraphDoc</doclet> <docletArtifact> <groupId>org.umlgraph</groupId> <artifactId>doclet</artifactId> <version>5.1</version> </docletArtifact> <useStandardDocletOptions>true</useStandardDocletOptions> <additionalparam> -inferrel -inferdep -quiet -hide java.* -hide org.eclipse.* -collpackages java.util.* -postfixpackage -nodefontsize 9 -nodefontpackagesize 7 -attributes -types -visibility -operations -constructors -enumerations -enumconstants -views </additionalparam> </configuration> <reportSets> <reportSet> <reports> <report>aggregate</report> </reports> </reportSet> </reportSets> </plugin> </reportPlugins> </configuration> </plugin> </plugins> </build> ``` The images are generated and look fine, when building the javadoc with jdk1.6 they get automatically integrated into all javadoc pages. But when building with jdk1.7, the images still get created but are not inside the javadoc pages. Even when using the v5.4 from the official website, the javadoc is imageless. And the debug output of maven also don't give any clue. On top of that, there is no way of contacting one of the UmlGraph devs by mail. Can anyone give me some advice here, or have some ideas how to fix that?
2011/12/22
['https://Stackoverflow.com/questions/8609546', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1094486/']
Update: version 5.6.6 is now on maven central. I built with JDK 7 and diagrams look ok. ``` <plugin> <artifactId>maven-javadoc-plugin</artifactId> <version>2.7</version> <configuration> <aggregate>true</aggregate> <show>private</show> <doclet>org.umlgraph.doclet.UmlGraphDoc</doclet> <docletArtifact> <groupId>org.umlgraph</groupId> <artifactId>umlgraph</artifactId> <version>5.6.6</version> </docletArtifact> </configuration> </plugin> ```
I have the same problem. My guess is that it's this bug: <https://issues.jboss.org/browse/APIVIZ-10>
8,609,546
I'm using maven and the maven-javadoc-plugin with the umlgraph-doclet to create javadoc for my project. The part from my pom: ``` <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-site-plugin</artifactId> <inherited>false</inherited> <configuration> <reportPlugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> <version>2.8</version> <configuration> <show>public</show> <quiet>true</quiet> <doclet>org.umlgraph.doclet.UmlGraphDoc</doclet> <docletArtifact> <groupId>org.umlgraph</groupId> <artifactId>doclet</artifactId> <version>5.1</version> </docletArtifact> <useStandardDocletOptions>true</useStandardDocletOptions> <additionalparam> -inferrel -inferdep -quiet -hide java.* -hide org.eclipse.* -collpackages java.util.* -postfixpackage -nodefontsize 9 -nodefontpackagesize 7 -attributes -types -visibility -operations -constructors -enumerations -enumconstants -views </additionalparam> </configuration> <reportSets> <reportSet> <reports> <report>aggregate</report> </reports> </reportSet> </reportSets> </plugin> </reportPlugins> </configuration> </plugin> </plugins> </build> ``` The images are generated and look fine, when building the javadoc with jdk1.6 they get automatically integrated into all javadoc pages. But when building with jdk1.7, the images still get created but are not inside the javadoc pages. Even when using the v5.4 from the official website, the javadoc is imageless. And the debug output of maven also don't give any clue. On top of that, there is no way of contacting one of the UmlGraph devs by mail. Can anyone give me some advice here, or have some ideas how to fix that?
2011/12/22
['https://Stackoverflow.com/questions/8609546', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1094486/']
I checked the possibilities, and the situation is following:. * relevant bug in the UmlGraph has been already fixed: <https://github.com/dspinellis/UMLGraph/pull/8> * problem is however that no stable version of UmlGraph has been released yet that would include the fix However good news is that there exists snapshot repository containing the fix: <https://oss.sonatype.org/content/repositories/snapshots/org/umlgraph/umlgraph/5.5.8-SNAPSHOT/> Therefor you need to get the jar file to your local repository (depending on your infrastructure setup): * either by adding reffered repository to your environment * or by importing to your local repo (<http://maven.apache.org/guides/mini/guide-3rd-party-jars-local.html>) afterwards update: ``` <doclet>org.umlgraph.doclet.UmlGraphDoc</doclet> <docletArtifact> <groupId>org.umlgraph</groupId> <artifactId>doclet</artifactId> <version>5.1</version> </docletArtifact> ``` to the following (naming convention has been changed): ``` <doclet>org.umlgraph.doclet.UmlGraphDoc</doclet> <docletArtifact> <groupId>org.umlgraph</groupId> <artifactId>umlgraph</artifactId> <version>5.5.8-SNAPSHOT</version> </docletArtifact> ```
UmlGraphDoc version 5.4, altering javadocs Warning, could not find a line that matches the pattern '/H2' The HTML is simply different. Java7 JavaDocs START OF CLASS DATA h2 title="blah blah Java6 JavaDocs START OF CLASS DATA H2 You can decompile and modify UmlGraphDoc.java
8,609,546
I'm using maven and the maven-javadoc-plugin with the umlgraph-doclet to create javadoc for my project. The part from my pom: ``` <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-site-plugin</artifactId> <inherited>false</inherited> <configuration> <reportPlugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> <version>2.8</version> <configuration> <show>public</show> <quiet>true</quiet> <doclet>org.umlgraph.doclet.UmlGraphDoc</doclet> <docletArtifact> <groupId>org.umlgraph</groupId> <artifactId>doclet</artifactId> <version>5.1</version> </docletArtifact> <useStandardDocletOptions>true</useStandardDocletOptions> <additionalparam> -inferrel -inferdep -quiet -hide java.* -hide org.eclipse.* -collpackages java.util.* -postfixpackage -nodefontsize 9 -nodefontpackagesize 7 -attributes -types -visibility -operations -constructors -enumerations -enumconstants -views </additionalparam> </configuration> <reportSets> <reportSet> <reports> <report>aggregate</report> </reports> </reportSet> </reportSets> </plugin> </reportPlugins> </configuration> </plugin> </plugins> </build> ``` The images are generated and look fine, when building the javadoc with jdk1.6 they get automatically integrated into all javadoc pages. But when building with jdk1.7, the images still get created but are not inside the javadoc pages. Even when using the v5.4 from the official website, the javadoc is imageless. And the debug output of maven also don't give any clue. On top of that, there is no way of contacting one of the UmlGraph devs by mail. Can anyone give me some advice here, or have some ideas how to fix that?
2011/12/22
['https://Stackoverflow.com/questions/8609546', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1094486/']
Update: version 5.6.6 is now on maven central. I built with JDK 7 and diagrams look ok. ``` <plugin> <artifactId>maven-javadoc-plugin</artifactId> <version>2.7</version> <configuration> <aggregate>true</aggregate> <show>private</show> <doclet>org.umlgraph.doclet.UmlGraphDoc</doclet> <docletArtifact> <groupId>org.umlgraph</groupId> <artifactId>umlgraph</artifactId> <version>5.6.6</version> </docletArtifact> </configuration> </plugin> ```
UmlGraphDoc version 5.4, altering javadocs Warning, could not find a line that matches the pattern '/H2' The HTML is simply different. Java7 JavaDocs START OF CLASS DATA h2 title="blah blah Java6 JavaDocs START OF CLASS DATA H2 You can decompile and modify UmlGraphDoc.java
5,808,172
I am currently working on my final thesis.I have a small problem.I need to pass a HTML block which is a string block to a javascript function.I have to do this from code behind.I have tried it so much I doesnt seem as it is going to work.Here is the code in code-behind: ``` string htmlFlightDetailsJavaScript ; ``` In the string there are few div and tables which have class propeties. something like div class="bla" ``` ClientScriptManager cs = Page.ClientScript; StringBuilder csText = new StringBuilder(); csText.Append("fill("+htmlFlightDetailsJavaScript+");"); cs.RegisterStartupScript(this.GetType(), "alert", csText.ToString(), true); ``` Here is my javascript function: ``` function fill(b) { alert(b); } ``` Note that my javascript function is on the ~.aspx. I have tried to pass the string without classes which are in the div and the table in string and it is working.But when I try to pass it with the classes,it does not work.Can anyone help me? Thank you very much
2011/04/27
['https://Stackoverflow.com/questions/5808172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/727788/']
You can use the [ClientScriptManager.RegisterStartupScript](http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.registerstartupscript.aspx) method.
I'd take a step back and examine whether the entire HTML block is really so dynamic that it needs to be passed into the function as a parameter. The easier way would be to have the HTML element emitted as part of the page, then augment that from your function. ie. show or hide it. If your scenario still requires you to pass the HTML as a parameter, you'll need to [HTML encode](http://msdn.microsoft.com/en-us/library/w3te6wfz.aspx) the entire string on the server side, and then [Unencode](https://stackoverflow.com/questions/1219860/javascript-jquery-html-encoding) in JS.
5,808,172
I am currently working on my final thesis.I have a small problem.I need to pass a HTML block which is a string block to a javascript function.I have to do this from code behind.I have tried it so much I doesnt seem as it is going to work.Here is the code in code-behind: ``` string htmlFlightDetailsJavaScript ; ``` In the string there are few div and tables which have class propeties. something like div class="bla" ``` ClientScriptManager cs = Page.ClientScript; StringBuilder csText = new StringBuilder(); csText.Append("fill("+htmlFlightDetailsJavaScript+");"); cs.RegisterStartupScript(this.GetType(), "alert", csText.ToString(), true); ``` Here is my javascript function: ``` function fill(b) { alert(b); } ``` Note that my javascript function is on the ~.aspx. I have tried to pass the string without classes which are in the div and the table in string and it is working.But when I try to pass it with the classes,it does not work.Can anyone help me? Thank you very much
2011/04/27
['https://Stackoverflow.com/questions/5808172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/727788/']
If the classes in `htmlFlightDetailsJavaScript` are in the form `div class="bla"` you likely have to escape the quotes in the string or use single quotes, e.g. `div class='bla'`.
I'd take a step back and examine whether the entire HTML block is really so dynamic that it needs to be passed into the function as a parameter. The easier way would be to have the HTML element emitted as part of the page, then augment that from your function. ie. show or hide it. If your scenario still requires you to pass the HTML as a parameter, you'll need to [HTML encode](http://msdn.microsoft.com/en-us/library/w3te6wfz.aspx) the entire string on the server side, and then [Unencode](https://stackoverflow.com/questions/1219860/javascript-jquery-html-encoding) in JS.
5,808,172
I am currently working on my final thesis.I have a small problem.I need to pass a HTML block which is a string block to a javascript function.I have to do this from code behind.I have tried it so much I doesnt seem as it is going to work.Here is the code in code-behind: ``` string htmlFlightDetailsJavaScript ; ``` In the string there are few div and tables which have class propeties. something like div class="bla" ``` ClientScriptManager cs = Page.ClientScript; StringBuilder csText = new StringBuilder(); csText.Append("fill("+htmlFlightDetailsJavaScript+");"); cs.RegisterStartupScript(this.GetType(), "alert", csText.ToString(), true); ``` Here is my javascript function: ``` function fill(b) { alert(b); } ``` Note that my javascript function is on the ~.aspx. I have tried to pass the string without classes which are in the div and the table in string and it is working.But when I try to pass it with the classes,it does not work.Can anyone help me? Thank you very much
2011/04/27
['https://Stackoverflow.com/questions/5808172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/727788/']
**This sounds like invalid Javascript is being generated**. This hypothesis can be verified with inspecting the *actual* Javascript transmitted and verifying the entire result, in context, for correctness. That is, imagine that this invalid Javascript was generated: ``` alert("<div class="I just broke JS" ...>") ``` **To fix this, ensure the strings literals inserted into the Javascript are valid.** For instance, the above might be written (using the following code) as: ``` RegisterClientScriptBlock(JsEncoder.Format(@"alert(""{0}"");", theInput)) ``` ...and it won't break because the string is escaped before. (Take a look at this output and compare: the inserted literal will be still valid Javascript, even with quotes or other characters in the `theInput`. As an added bonus, `</script>` to break the code either ;-) This code is "free to use, modify, sell, whatever". YMMV. ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace sbcjc.sei { public class JsEncoder { static Regex EncodeLiteralRegex; // Format a bunch of literals. public static string Format (string format, params object[] items) { return string.Format(format, items.Select(item => EncodeString("" + item)).ToArray()); } // Given a string, return a string suitable for safe // use within a Javascript literal inside a <script> block. // This approach errs on the side of "ugly" escaping. public static string EncodeString (string value) { if (EncodeLiteralRegex == null) { // initial accept "space to ~" in ASCII then reject quotes // and some XML chars (this avoids `</script>`, `<![CDATA[..]]>>`, and XML vs HTML issues) // "/" is not allowed because it requires an escape in JSON var accepted = Enumerable.Range(32, 127 - 32) .Except(new int[] { '"', '\'', '\\', '&', '<', '>', '/' }); // pattern matches everything but accepted EncodeLiteralRegex = new Regex("[^" + string.Join("", accepted.Select(c => @"\x" + c.ToString("x2")).ToArray()) + "]"); } return EncodeLiteralRegex.Replace(value ?? "", (match) => { var ch = (int)match.Value[0]; // only matches a character at a time return ch <= 127 ? @"\x" + ch.ToString("x2") // not JSON : @"\u" + ch.ToString("x4"); }); } } } ``` Happy coding.
I guess you can accomplish much faster if you use an ajax call and a partial control (user control) or write the content yourself. 1) The user control will render your html data. 2) The page code behind will receive the ajax call and call the method thal will render the partial control or write. 3) The method will write on Response.Output stream and end the Response (Response.End()) 4) The javascript will handle the response and show the result. (using jQuery) ``` // main.js jQuery.ajax({ type: 'POST', data: { isajax: true, ajaxcall: 'MyMethod' }, dataType: 'html', success: function (data, textStatus, jqXHR) { alert(data); } }); // CodeBehind protected void Page_Load(object sender, EventArgs e) { if (Request.HttpMethod == "POST" && Request["isajax"] == "true") { this.AjaxCall(Request); } } private void AjaxCall(HttpRequest request) { switch (request["ajaxcall"]) { case "MyMethod": this.MyMethod(request); break; default: break; } } private void MyMethod(HttpRequest request) { Response.ContentType = "text/html"; Response.Write("YOUR CONTENT GOES HERE."); // Or, render a User Control Response.End(); } ``` P.S.: You can use a Generic Handler if you wish to. Just add the url option to jQuery ajax method. Let me know if it helps.
5,808,172
I am currently working on my final thesis.I have a small problem.I need to pass a HTML block which is a string block to a javascript function.I have to do this from code behind.I have tried it so much I doesnt seem as it is going to work.Here is the code in code-behind: ``` string htmlFlightDetailsJavaScript ; ``` In the string there are few div and tables which have class propeties. something like div class="bla" ``` ClientScriptManager cs = Page.ClientScript; StringBuilder csText = new StringBuilder(); csText.Append("fill("+htmlFlightDetailsJavaScript+");"); cs.RegisterStartupScript(this.GetType(), "alert", csText.ToString(), true); ``` Here is my javascript function: ``` function fill(b) { alert(b); } ``` Note that my javascript function is on the ~.aspx. I have tried to pass the string without classes which are in the div and the table in string and it is working.But when I try to pass it with the classes,it does not work.Can anyone help me? Thank you very much
2011/04/27
['https://Stackoverflow.com/questions/5808172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/727788/']
**This sounds like invalid Javascript is being generated**. This hypothesis can be verified with inspecting the *actual* Javascript transmitted and verifying the entire result, in context, for correctness. That is, imagine that this invalid Javascript was generated: ``` alert("<div class="I just broke JS" ...>") ``` **To fix this, ensure the strings literals inserted into the Javascript are valid.** For instance, the above might be written (using the following code) as: ``` RegisterClientScriptBlock(JsEncoder.Format(@"alert(""{0}"");", theInput)) ``` ...and it won't break because the string is escaped before. (Take a look at this output and compare: the inserted literal will be still valid Javascript, even with quotes or other characters in the `theInput`. As an added bonus, `</script>` to break the code either ;-) This code is "free to use, modify, sell, whatever". YMMV. ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace sbcjc.sei { public class JsEncoder { static Regex EncodeLiteralRegex; // Format a bunch of literals. public static string Format (string format, params object[] items) { return string.Format(format, items.Select(item => EncodeString("" + item)).ToArray()); } // Given a string, return a string suitable for safe // use within a Javascript literal inside a <script> block. // This approach errs on the side of "ugly" escaping. public static string EncodeString (string value) { if (EncodeLiteralRegex == null) { // initial accept "space to ~" in ASCII then reject quotes // and some XML chars (this avoids `</script>`, `<![CDATA[..]]>>`, and XML vs HTML issues) // "/" is not allowed because it requires an escape in JSON var accepted = Enumerable.Range(32, 127 - 32) .Except(new int[] { '"', '\'', '\\', '&', '<', '>', '/' }); // pattern matches everything but accepted EncodeLiteralRegex = new Regex("[^" + string.Join("", accepted.Select(c => @"\x" + c.ToString("x2")).ToArray()) + "]"); } return EncodeLiteralRegex.Replace(value ?? "", (match) => { var ch = (int)match.Value[0]; // only matches a character at a time return ch <= 127 ? @"\x" + ch.ToString("x2") // not JSON : @"\u" + ch.ToString("x4"); }); } } } ``` Happy coding.
Use the RegisterClientScriptBlock() method and make sure to escape your quotes in your HTML. "<div class=\"blah\">"
5,808,172
I am currently working on my final thesis.I have a small problem.I need to pass a HTML block which is a string block to a javascript function.I have to do this from code behind.I have tried it so much I doesnt seem as it is going to work.Here is the code in code-behind: ``` string htmlFlightDetailsJavaScript ; ``` In the string there are few div and tables which have class propeties. something like div class="bla" ``` ClientScriptManager cs = Page.ClientScript; StringBuilder csText = new StringBuilder(); csText.Append("fill("+htmlFlightDetailsJavaScript+");"); cs.RegisterStartupScript(this.GetType(), "alert", csText.ToString(), true); ``` Here is my javascript function: ``` function fill(b) { alert(b); } ``` Note that my javascript function is on the ~.aspx. I have tried to pass the string without classes which are in the div and the table in string and it is working.But when I try to pass it with the classes,it does not work.Can anyone help me? Thank you very much
2011/04/27
['https://Stackoverflow.com/questions/5808172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/727788/']
**This sounds like invalid Javascript is being generated**. This hypothesis can be verified with inspecting the *actual* Javascript transmitted and verifying the entire result, in context, for correctness. That is, imagine that this invalid Javascript was generated: ``` alert("<div class="I just broke JS" ...>") ``` **To fix this, ensure the strings literals inserted into the Javascript are valid.** For instance, the above might be written (using the following code) as: ``` RegisterClientScriptBlock(JsEncoder.Format(@"alert(""{0}"");", theInput)) ``` ...and it won't break because the string is escaped before. (Take a look at this output and compare: the inserted literal will be still valid Javascript, even with quotes or other characters in the `theInput`. As an added bonus, `</script>` to break the code either ;-) This code is "free to use, modify, sell, whatever". YMMV. ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace sbcjc.sei { public class JsEncoder { static Regex EncodeLiteralRegex; // Format a bunch of literals. public static string Format (string format, params object[] items) { return string.Format(format, items.Select(item => EncodeString("" + item)).ToArray()); } // Given a string, return a string suitable for safe // use within a Javascript literal inside a <script> block. // This approach errs on the side of "ugly" escaping. public static string EncodeString (string value) { if (EncodeLiteralRegex == null) { // initial accept "space to ~" in ASCII then reject quotes // and some XML chars (this avoids `</script>`, `<![CDATA[..]]>>`, and XML vs HTML issues) // "/" is not allowed because it requires an escape in JSON var accepted = Enumerable.Range(32, 127 - 32) .Except(new int[] { '"', '\'', '\\', '&', '<', '>', '/' }); // pattern matches everything but accepted EncodeLiteralRegex = new Regex("[^" + string.Join("", accepted.Select(c => @"\x" + c.ToString("x2")).ToArray()) + "]"); } return EncodeLiteralRegex.Replace(value ?? "", (match) => { var ch = (int)match.Value[0]; // only matches a character at a time return ch <= 127 ? @"\x" + ch.ToString("x2") // not JSON : @"\u" + ch.ToString("x4"); }); } } } ``` Happy coding.
I'd take a step back and examine whether the entire HTML block is really so dynamic that it needs to be passed into the function as a parameter. The easier way would be to have the HTML element emitted as part of the page, then augment that from your function. ie. show or hide it. If your scenario still requires you to pass the HTML as a parameter, you'll need to [HTML encode](http://msdn.microsoft.com/en-us/library/w3te6wfz.aspx) the entire string on the server side, and then [Unencode](https://stackoverflow.com/questions/1219860/javascript-jquery-html-encoding) in JS.
5,808,172
I am currently working on my final thesis.I have a small problem.I need to pass a HTML block which is a string block to a javascript function.I have to do this from code behind.I have tried it so much I doesnt seem as it is going to work.Here is the code in code-behind: ``` string htmlFlightDetailsJavaScript ; ``` In the string there are few div and tables which have class propeties. something like div class="bla" ``` ClientScriptManager cs = Page.ClientScript; StringBuilder csText = new StringBuilder(); csText.Append("fill("+htmlFlightDetailsJavaScript+");"); cs.RegisterStartupScript(this.GetType(), "alert", csText.ToString(), true); ``` Here is my javascript function: ``` function fill(b) { alert(b); } ``` Note that my javascript function is on the ~.aspx. I have tried to pass the string without classes which are in the div and the table in string and it is working.But when I try to pass it with the classes,it does not work.Can anyone help me? Thank you very much
2011/04/27
['https://Stackoverflow.com/questions/5808172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/727788/']
Use the RegisterClientScriptBlock() method and make sure to escape your quotes in your HTML. "<div class=\"blah\">"
I guess you can accomplish much faster if you use an ajax call and a partial control (user control) or write the content yourself. 1) The user control will render your html data. 2) The page code behind will receive the ajax call and call the method thal will render the partial control or write. 3) The method will write on Response.Output stream and end the Response (Response.End()) 4) The javascript will handle the response and show the result. (using jQuery) ``` // main.js jQuery.ajax({ type: 'POST', data: { isajax: true, ajaxcall: 'MyMethod' }, dataType: 'html', success: function (data, textStatus, jqXHR) { alert(data); } }); // CodeBehind protected void Page_Load(object sender, EventArgs e) { if (Request.HttpMethod == "POST" && Request["isajax"] == "true") { this.AjaxCall(Request); } } private void AjaxCall(HttpRequest request) { switch (request["ajaxcall"]) { case "MyMethod": this.MyMethod(request); break; default: break; } } private void MyMethod(HttpRequest request) { Response.ContentType = "text/html"; Response.Write("YOUR CONTENT GOES HERE."); // Or, render a User Control Response.End(); } ``` P.S.: You can use a Generic Handler if you wish to. Just add the url option to jQuery ajax method. Let me know if it helps.
5,808,172
I am currently working on my final thesis.I have a small problem.I need to pass a HTML block which is a string block to a javascript function.I have to do this from code behind.I have tried it so much I doesnt seem as it is going to work.Here is the code in code-behind: ``` string htmlFlightDetailsJavaScript ; ``` In the string there are few div and tables which have class propeties. something like div class="bla" ``` ClientScriptManager cs = Page.ClientScript; StringBuilder csText = new StringBuilder(); csText.Append("fill("+htmlFlightDetailsJavaScript+");"); cs.RegisterStartupScript(this.GetType(), "alert", csText.ToString(), true); ``` Here is my javascript function: ``` function fill(b) { alert(b); } ``` Note that my javascript function is on the ~.aspx. I have tried to pass the string without classes which are in the div and the table in string and it is working.But when I try to pass it with the classes,it does not work.Can anyone help me? Thank you very much
2011/04/27
['https://Stackoverflow.com/questions/5808172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/727788/']
You can use the [ClientScriptManager.RegisterStartupScript](http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.registerstartupscript.aspx) method.
I guess you can accomplish much faster if you use an ajax call and a partial control (user control) or write the content yourself. 1) The user control will render your html data. 2) The page code behind will receive the ajax call and call the method thal will render the partial control or write. 3) The method will write on Response.Output stream and end the Response (Response.End()) 4) The javascript will handle the response and show the result. (using jQuery) ``` // main.js jQuery.ajax({ type: 'POST', data: { isajax: true, ajaxcall: 'MyMethod' }, dataType: 'html', success: function (data, textStatus, jqXHR) { alert(data); } }); // CodeBehind protected void Page_Load(object sender, EventArgs e) { if (Request.HttpMethod == "POST" && Request["isajax"] == "true") { this.AjaxCall(Request); } } private void AjaxCall(HttpRequest request) { switch (request["ajaxcall"]) { case "MyMethod": this.MyMethod(request); break; default: break; } } private void MyMethod(HttpRequest request) { Response.ContentType = "text/html"; Response.Write("YOUR CONTENT GOES HERE."); // Or, render a User Control Response.End(); } ``` P.S.: You can use a Generic Handler if you wish to. Just add the url option to jQuery ajax method. Let me know if it helps.
5,808,172
I am currently working on my final thesis.I have a small problem.I need to pass a HTML block which is a string block to a javascript function.I have to do this from code behind.I have tried it so much I doesnt seem as it is going to work.Here is the code in code-behind: ``` string htmlFlightDetailsJavaScript ; ``` In the string there are few div and tables which have class propeties. something like div class="bla" ``` ClientScriptManager cs = Page.ClientScript; StringBuilder csText = new StringBuilder(); csText.Append("fill("+htmlFlightDetailsJavaScript+");"); cs.RegisterStartupScript(this.GetType(), "alert", csText.ToString(), true); ``` Here is my javascript function: ``` function fill(b) { alert(b); } ``` Note that my javascript function is on the ~.aspx. I have tried to pass the string without classes which are in the div and the table in string and it is working.But when I try to pass it with the classes,it does not work.Can anyone help me? Thank you very much
2011/04/27
['https://Stackoverflow.com/questions/5808172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/727788/']
**This sounds like invalid Javascript is being generated**. This hypothesis can be verified with inspecting the *actual* Javascript transmitted and verifying the entire result, in context, for correctness. That is, imagine that this invalid Javascript was generated: ``` alert("<div class="I just broke JS" ...>") ``` **To fix this, ensure the strings literals inserted into the Javascript are valid.** For instance, the above might be written (using the following code) as: ``` RegisterClientScriptBlock(JsEncoder.Format(@"alert(""{0}"");", theInput)) ``` ...and it won't break because the string is escaped before. (Take a look at this output and compare: the inserted literal will be still valid Javascript, even with quotes or other characters in the `theInput`. As an added bonus, `</script>` to break the code either ;-) This code is "free to use, modify, sell, whatever". YMMV. ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace sbcjc.sei { public class JsEncoder { static Regex EncodeLiteralRegex; // Format a bunch of literals. public static string Format (string format, params object[] items) { return string.Format(format, items.Select(item => EncodeString("" + item)).ToArray()); } // Given a string, return a string suitable for safe // use within a Javascript literal inside a <script> block. // This approach errs on the side of "ugly" escaping. public static string EncodeString (string value) { if (EncodeLiteralRegex == null) { // initial accept "space to ~" in ASCII then reject quotes // and some XML chars (this avoids `</script>`, `<![CDATA[..]]>>`, and XML vs HTML issues) // "/" is not allowed because it requires an escape in JSON var accepted = Enumerable.Range(32, 127 - 32) .Except(new int[] { '"', '\'', '\\', '&', '<', '>', '/' }); // pattern matches everything but accepted EncodeLiteralRegex = new Regex("[^" + string.Join("", accepted.Select(c => @"\x" + c.ToString("x2")).ToArray()) + "]"); } return EncodeLiteralRegex.Replace(value ?? "", (match) => { var ch = (int)match.Value[0]; // only matches a character at a time return ch <= 127 ? @"\x" + ch.ToString("x2") // not JSON : @"\u" + ch.ToString("x4"); }); } } } ``` Happy coding.
You can use the [ClientScriptManager.RegisterStartupScript](http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.registerstartupscript.aspx) method.
5,808,172
I am currently working on my final thesis.I have a small problem.I need to pass a HTML block which is a string block to a javascript function.I have to do this from code behind.I have tried it so much I doesnt seem as it is going to work.Here is the code in code-behind: ``` string htmlFlightDetailsJavaScript ; ``` In the string there are few div and tables which have class propeties. something like div class="bla" ``` ClientScriptManager cs = Page.ClientScript; StringBuilder csText = new StringBuilder(); csText.Append("fill("+htmlFlightDetailsJavaScript+");"); cs.RegisterStartupScript(this.GetType(), "alert", csText.ToString(), true); ``` Here is my javascript function: ``` function fill(b) { alert(b); } ``` Note that my javascript function is on the ~.aspx. I have tried to pass the string without classes which are in the div and the table in string and it is working.But when I try to pass it with the classes,it does not work.Can anyone help me? Thank you very much
2011/04/27
['https://Stackoverflow.com/questions/5808172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/727788/']
**This sounds like invalid Javascript is being generated**. This hypothesis can be verified with inspecting the *actual* Javascript transmitted and verifying the entire result, in context, for correctness. That is, imagine that this invalid Javascript was generated: ``` alert("<div class="I just broke JS" ...>") ``` **To fix this, ensure the strings literals inserted into the Javascript are valid.** For instance, the above might be written (using the following code) as: ``` RegisterClientScriptBlock(JsEncoder.Format(@"alert(""{0}"");", theInput)) ``` ...and it won't break because the string is escaped before. (Take a look at this output and compare: the inserted literal will be still valid Javascript, even with quotes or other characters in the `theInput`. As an added bonus, `</script>` to break the code either ;-) This code is "free to use, modify, sell, whatever". YMMV. ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace sbcjc.sei { public class JsEncoder { static Regex EncodeLiteralRegex; // Format a bunch of literals. public static string Format (string format, params object[] items) { return string.Format(format, items.Select(item => EncodeString("" + item)).ToArray()); } // Given a string, return a string suitable for safe // use within a Javascript literal inside a <script> block. // This approach errs on the side of "ugly" escaping. public static string EncodeString (string value) { if (EncodeLiteralRegex == null) { // initial accept "space to ~" in ASCII then reject quotes // and some XML chars (this avoids `</script>`, `<![CDATA[..]]>>`, and XML vs HTML issues) // "/" is not allowed because it requires an escape in JSON var accepted = Enumerable.Range(32, 127 - 32) .Except(new int[] { '"', '\'', '\\', '&', '<', '>', '/' }); // pattern matches everything but accepted EncodeLiteralRegex = new Regex("[^" + string.Join("", accepted.Select(c => @"\x" + c.ToString("x2")).ToArray()) + "]"); } return EncodeLiteralRegex.Replace(value ?? "", (match) => { var ch = (int)match.Value[0]; // only matches a character at a time return ch <= 127 ? @"\x" + ch.ToString("x2") // not JSON : @"\u" + ch.ToString("x4"); }); } } } ``` Happy coding.
If the classes in `htmlFlightDetailsJavaScript` are in the form `div class="bla"` you likely have to escape the quotes in the string or use single quotes, e.g. `div class='bla'`.
5,808,172
I am currently working on my final thesis.I have a small problem.I need to pass a HTML block which is a string block to a javascript function.I have to do this from code behind.I have tried it so much I doesnt seem as it is going to work.Here is the code in code-behind: ``` string htmlFlightDetailsJavaScript ; ``` In the string there are few div and tables which have class propeties. something like div class="bla" ``` ClientScriptManager cs = Page.ClientScript; StringBuilder csText = new StringBuilder(); csText.Append("fill("+htmlFlightDetailsJavaScript+");"); cs.RegisterStartupScript(this.GetType(), "alert", csText.ToString(), true); ``` Here is my javascript function: ``` function fill(b) { alert(b); } ``` Note that my javascript function is on the ~.aspx. I have tried to pass the string without classes which are in the div and the table in string and it is working.But when I try to pass it with the classes,it does not work.Can anyone help me? Thank you very much
2011/04/27
['https://Stackoverflow.com/questions/5808172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/727788/']
If the classes in `htmlFlightDetailsJavaScript` are in the form `div class="bla"` you likely have to escape the quotes in the string or use single quotes, e.g. `div class='bla'`.
I guess you can accomplish much faster if you use an ajax call and a partial control (user control) or write the content yourself. 1) The user control will render your html data. 2) The page code behind will receive the ajax call and call the method thal will render the partial control or write. 3) The method will write on Response.Output stream and end the Response (Response.End()) 4) The javascript will handle the response and show the result. (using jQuery) ``` // main.js jQuery.ajax({ type: 'POST', data: { isajax: true, ajaxcall: 'MyMethod' }, dataType: 'html', success: function (data, textStatus, jqXHR) { alert(data); } }); // CodeBehind protected void Page_Load(object sender, EventArgs e) { if (Request.HttpMethod == "POST" && Request["isajax"] == "true") { this.AjaxCall(Request); } } private void AjaxCall(HttpRequest request) { switch (request["ajaxcall"]) { case "MyMethod": this.MyMethod(request); break; default: break; } } private void MyMethod(HttpRequest request) { Response.ContentType = "text/html"; Response.Write("YOUR CONTENT GOES HERE."); // Or, render a User Control Response.End(); } ``` P.S.: You can use a Generic Handler if you wish to. Just add the url option to jQuery ajax method. Let me know if it helps.
18,881,883
I need to take two parameters in my spring controller. <http://mydomain.com/myapp/getDetails?Id=13&subId=431> I have controller which will return Json for this request. ``` @RequestMapping(value = "/getDetails", method = RequestMethod.GET,params = "id,subId", produces="application/json") @ResponseBody public MyBean getsubIds(@RequestParam String id, @RequestParam String subId) { return MyBean } ``` I am getting 400 for when i tried to invoke the URL. Any thoughts on this? I was able to get it with one parameter.
2013/09/18
['https://Stackoverflow.com/questions/18881883', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1322144/']
Try specifying which parameter in the query string should match the parameter in the method like so: ``` public MyBean getsubIds(@RequestParam("id") String id, @RequestParam("subId") String subId) { ``` If the code is being compiled without the parameter names, Spring can have trouble figuring out which is which.
As for me it works (by calling: <http://www.example.com/getDetails?id=10&subId=15>): ``` @RequestMapping(value = "/getDetails", method = RequestMethod.GET, produces="application/json") @ResponseBody public MyBean getsubIds(@RequestParam("id") String id, @RequestParam("subId") String subId) { return new MyBean(); } ``` P.S. Assuming you have class MyBean.
26,682
My band is working with a somewhat pricey mastering engineer and we are wanting to keep the price down. For a price we're comfortable with, he will either provide us with hi-res masters (24bit, 48khz - the recording quality), or with CD-quality masters + DDP file (16bit-44.1khz). My gut is to get the hi-res masters, buy [Triumph](http://www.audiofile-engineering.com/triumph/) for $79, and do the conversion and create the DDP file myself. However, the engineer said he does a separate mastering pass for each quality he does. My question is: what might necessitate a different mastering pass for the CD-quality version? What benefit might there be to getting the mastering engineer to do the CD-quality version instead of just converting it myself from the hi-res version?
2014/01/31
['https://sound.stackexchange.com/questions/26682', 'https://sound.stackexchange.com', 'https://sound.stackexchange.com/users/7283/']
Dither, Noise Shaping, and Bit Quantization. These are the reasons for the separate mastering passes. All of which do not need to be considered when mixing/bouncing the audio in the native digital format it was converted to (24bit/48khz). Also, it sounds like he will provide you with individual "HiRes" native files OR Will downsample for you and create a DDP file. (Which is a FINAL Copy including play order and silence between songs that you can usually upload directly to a CD cuplication service.) If you are not making CDs or distributing digitally only (itunes?). You have no use for a ddp file. Although u may have use for the MEs tools and know how when it comes to downsampling. EDIT: I suppose it is possible for the ME to EQ specifically for the lower quality (not likely!) to produce better translation at the format? Also he may handle level peaks differently when downsampling. IF it were me, Id take the native hi res master and be about my business. Ive also been an audio engineer for years tho.
For going from 24 bit to 16 bit is relativity simple since it is evenly divisible, however you will still want to apply a dither to make up for the way the originally analog signal loses resolution. This allows simulating a wider set of distinct values than 16 bits would normally allow in exchange for some minimal noise. A great link about this was included by Takuya in the comments below. With 48khz sampling, you can accurately capture waveforms of up to 24khz frequency. There may be some weird harmonic issues that occur during the conversion, but they would be outside the human hearing range. It isn't truly a lossless experience since it isn't evenly divisible, but it shouldn't cause major issues either.
168,731
I'm just starting WoW for the first time... My question: Is the storyline and quests that I'm doing the same as what players did when the game started (in 2002 or whatever)? Or have events happened in the game that have progressed the entire timeline/story of the game for new players?
2014/05/20
['https://gaming.stackexchange.com/questions/168731', 'https://gaming.stackexchange.com', 'https://gaming.stackexchange.com/users/76989/']
Each continent roughly corresponds to an expansion e.g. an arc in the timeline. * Outlands: Burning Crusade (2007). It is unmodified. * Northrend: Wrath of the Lich King (2008). It is unmodified. * Eastern Kingdoms and Kalimdor: Cataclysm (2010). This expansion completely replaces the quests and map from the classic version of the game. The classic story arc is no longer available on the main servers. Thrall is no longer warchief, Garrosh is. * Pandaria: Mists of Pandaria (2012). It is unmodified except for the Vale of Eternal Blossoms, which was destroyed. You can't go back to the original Vale. Also, the legendary cape questline is removed from the game. * Draenor: Warlords of Draenor (2014). The legendary ring questline is removed from the game. * Broken Isles: Legion (2016). Weapon artifacts still have stats and can be leveled up, but they no longer have abilities. Legendary items, besides your weapon artifact, are disabled. * Kul Tiras and Zandalar: Battle for Azeroth (2018). Azerite armor, the Heart of Azeroth, the legendary cloak all seem to still be in the game - expect none of these to be useful in shadowlands. Corrupted gear is no longer attainable and corruption effects are deactivated. You can play in all of the above content to get to level 50. You can start any or all of the expansions, switch expansions at any time, switch back. Whatever you want to do. For levels 50-60, you'll play in the new Shadowlands (2021) content. There is one more bit of content to mention: * Original Eastern Kingdoms and original Kalimdor: Classic (aka Vanilla) (2004). There is a separate installer/server for this content. You can create a separate character to play this content.
The whole world has changed into a cataclysmic world. It should be the same but with more quests and a higher level cap.
168,731
I'm just starting WoW for the first time... My question: Is the storyline and quests that I'm doing the same as what players did when the game started (in 2002 or whatever)? Or have events happened in the game that have progressed the entire timeline/story of the game for new players?
2014/05/20
['https://gaming.stackexchange.com/questions/168731', 'https://gaming.stackexchange.com', 'https://gaming.stackexchange.com/users/76989/']
With each expansion, in the World of Warcraft universe, the level cap of your character increases by 5-10 levels. There is a general "theme", and throughout the release and consequent patches, there are some significant events that take place in terms of storyline. Each expansion is catered predominantly for players within its respective level group. Burning Crusade content caters to levels 60-70, Wrath of the Lich King caters to 70-80 and so on. Each consequent expansion can, in theory, both limit and improve your ability to experience the story line of its predecessors. Most end-game content is designed for groups of players, in anything from 5 to 40 man dungeons. There is a reliance on being able to play alongside other players, in order to have a chance against completing some of these events. With most players leaning towards current content, there can be fewer players available to participate in older content, however, due to the level increases with each expansion, you can often find older content a lot easier to handle given fewer players. As for if you miss out on any content, no, not really. While there is a lot of content, to begin with, you still have access to *most* of the major events surrounding the World of Warcraft universe. For example, you can still easily handle the major end-game raid released for vanilla World of Warcraft, [Ahn'Qiraj](http://wowwiki.wikia.com/Ahn%27Qiraj), with only a handful of level 70s. However, [the event that precipitated its opening](http://wowwiki.wikia.com/Gates_of_Ahn%27Qiraj) [no longer features](http://wowwiki.wikia.com/Gates_of_Ahn%27Qiraj#Permanent_.22Closure.22_of_the_Event), and can not be experienced. You will still be able to experience the majority of each expansions story. The only difference is, you can experience it in a different order, given the ability to freely roam within your characters level restrictions. Eastern Kingdoms and Kalimdor, the two major regions from Vanilla WoW, have undergone a massive redesign with the release of Cataclysm. You will likely experience a difference, here, in comparison to the original WoW. Most of this has been Blizzards way of bringing the vanilla content up to the standards reached with Burning Crusade and Wrath of the Lich King, and you will still experience all the "original lore" storyline in your initial character progression. For reference, here is a list of expansions, along with their general themes and included "racial backstory". You can generally focus on the content from a particular expansion, to experience the story surrounding its theme. * **The Burning Crusade (60-70)**: Explores Outland, the old homeland of the Orcs and Draenei, featured in the events of Warcraft 3: The Frozen Throne. Plot involves the storming of The Black Temple, and the overthrow of Illidan, the threat of the Zul'jin and his Zul'Aman empire, and the betrayal of Keal'thas Sunstrider, in attempting to summon the demon lord Kil'jaeden through the Blood Elves Sunwell. The Draenei and the Blood Elves are also introduced. * **Wrath of the Lich King (70-80)**: Explores Northrend, a forgotten contintent to the north, featured in the events of Warcraft 3. Plot involves the discovery of an old titan complex, an old prison built to hold an Old God, and the war efforts in fighting the undead scourge, leading up to the penultimate battle against The Lich King, himself. This expansion also introduces the Death Knight, a special hero class with their own backstory, and play style. * **Cataclysm (80-85)**: Introduces a massive apocalyptic event known as The Cataclysm, during which a great majority of The Eastern Kingdoms and Kalimdor undergoes a considerable change, including the appearance of the Maelstrom region. Plot involves the alliance and uprising of the Zandalari trolls, the defence against the firelord, Ragnaros, and the fight against the rouge dragon, Deathwing the Destroyer. This Goblins and Worgen are also introduced as more prominent races. * **Mists of Pandaria (85-90)**: Introduces the newly discovered islands of Pandaria. Plot focuses on the renewed fight between the Horde and the Alliance, as well as the civil disputes within the factions. Further plot focuses on the return of the Mogu, the and siege of Orgrimmar. The Pandaran race is also introduced as the games first natural race. * **Warlords of Draenor (90-100)**: Introduces an alternate timeline, as well as the planet Draenor, which eventually became Outland after being torn apart. Plot focuses on an altered timeline, where the orcs do not drink the blood of the demon lord Mannoroth. This leads to an unnatural uprising of the Iron Horde, and a major invasion of Azeroth.
The whole world has changed into a cataclysmic world. It should be the same but with more quests and a higher level cap.
168,731
I'm just starting WoW for the first time... My question: Is the storyline and quests that I'm doing the same as what players did when the game started (in 2002 or whatever)? Or have events happened in the game that have progressed the entire timeline/story of the game for new players?
2014/05/20
['https://gaming.stackexchange.com/questions/168731', 'https://gaming.stackexchange.com', 'https://gaming.stackexchange.com/users/76989/']
Each continent roughly corresponds to an expansion e.g. an arc in the timeline. * Outlands: Burning Crusade (2007). It is unmodified. * Northrend: Wrath of the Lich King (2008). It is unmodified. * Eastern Kingdoms and Kalimdor: Cataclysm (2010). This expansion completely replaces the quests and map from the classic version of the game. The classic story arc is no longer available on the main servers. Thrall is no longer warchief, Garrosh is. * Pandaria: Mists of Pandaria (2012). It is unmodified except for the Vale of Eternal Blossoms, which was destroyed. You can't go back to the original Vale. Also, the legendary cape questline is removed from the game. * Draenor: Warlords of Draenor (2014). The legendary ring questline is removed from the game. * Broken Isles: Legion (2016). Weapon artifacts still have stats and can be leveled up, but they no longer have abilities. Legendary items, besides your weapon artifact, are disabled. * Kul Tiras and Zandalar: Battle for Azeroth (2018). Azerite armor, the Heart of Azeroth, the legendary cloak all seem to still be in the game - expect none of these to be useful in shadowlands. Corrupted gear is no longer attainable and corruption effects are deactivated. You can play in all of the above content to get to level 50. You can start any or all of the expansions, switch expansions at any time, switch back. Whatever you want to do. For levels 50-60, you'll play in the new Shadowlands (2021) content. There is one more bit of content to mention: * Original Eastern Kingdoms and original Kalimdor: Classic (aka Vanilla) (2004). There is a separate installer/server for this content. You can create a separate character to play this content.
With each expansion, in the World of Warcraft universe, the level cap of your character increases by 5-10 levels. There is a general "theme", and throughout the release and consequent patches, there are some significant events that take place in terms of storyline. Each expansion is catered predominantly for players within its respective level group. Burning Crusade content caters to levels 60-70, Wrath of the Lich King caters to 70-80 and so on. Each consequent expansion can, in theory, both limit and improve your ability to experience the story line of its predecessors. Most end-game content is designed for groups of players, in anything from 5 to 40 man dungeons. There is a reliance on being able to play alongside other players, in order to have a chance against completing some of these events. With most players leaning towards current content, there can be fewer players available to participate in older content, however, due to the level increases with each expansion, you can often find older content a lot easier to handle given fewer players. As for if you miss out on any content, no, not really. While there is a lot of content, to begin with, you still have access to *most* of the major events surrounding the World of Warcraft universe. For example, you can still easily handle the major end-game raid released for vanilla World of Warcraft, [Ahn'Qiraj](http://wowwiki.wikia.com/Ahn%27Qiraj), with only a handful of level 70s. However, [the event that precipitated its opening](http://wowwiki.wikia.com/Gates_of_Ahn%27Qiraj) [no longer features](http://wowwiki.wikia.com/Gates_of_Ahn%27Qiraj#Permanent_.22Closure.22_of_the_Event), and can not be experienced. You will still be able to experience the majority of each expansions story. The only difference is, you can experience it in a different order, given the ability to freely roam within your characters level restrictions. Eastern Kingdoms and Kalimdor, the two major regions from Vanilla WoW, have undergone a massive redesign with the release of Cataclysm. You will likely experience a difference, here, in comparison to the original WoW. Most of this has been Blizzards way of bringing the vanilla content up to the standards reached with Burning Crusade and Wrath of the Lich King, and you will still experience all the "original lore" storyline in your initial character progression. For reference, here is a list of expansions, along with their general themes and included "racial backstory". You can generally focus on the content from a particular expansion, to experience the story surrounding its theme. * **The Burning Crusade (60-70)**: Explores Outland, the old homeland of the Orcs and Draenei, featured in the events of Warcraft 3: The Frozen Throne. Plot involves the storming of The Black Temple, and the overthrow of Illidan, the threat of the Zul'jin and his Zul'Aman empire, and the betrayal of Keal'thas Sunstrider, in attempting to summon the demon lord Kil'jaeden through the Blood Elves Sunwell. The Draenei and the Blood Elves are also introduced. * **Wrath of the Lich King (70-80)**: Explores Northrend, a forgotten contintent to the north, featured in the events of Warcraft 3. Plot involves the discovery of an old titan complex, an old prison built to hold an Old God, and the war efforts in fighting the undead scourge, leading up to the penultimate battle against The Lich King, himself. This expansion also introduces the Death Knight, a special hero class with their own backstory, and play style. * **Cataclysm (80-85)**: Introduces a massive apocalyptic event known as The Cataclysm, during which a great majority of The Eastern Kingdoms and Kalimdor undergoes a considerable change, including the appearance of the Maelstrom region. Plot involves the alliance and uprising of the Zandalari trolls, the defence against the firelord, Ragnaros, and the fight against the rouge dragon, Deathwing the Destroyer. This Goblins and Worgen are also introduced as more prominent races. * **Mists of Pandaria (85-90)**: Introduces the newly discovered islands of Pandaria. Plot focuses on the renewed fight between the Horde and the Alliance, as well as the civil disputes within the factions. Further plot focuses on the return of the Mogu, the and siege of Orgrimmar. The Pandaran race is also introduced as the games first natural race. * **Warlords of Draenor (90-100)**: Introduces an alternate timeline, as well as the planet Draenor, which eventually became Outland after being torn apart. Plot focuses on an altered timeline, where the orcs do not drink the blood of the demon lord Mannoroth. This leads to an unnatural uprising of the Iron Horde, and a major invasion of Azeroth.
4,371,698
A money pouch contains a certain number of cents and only one dime. You and your friend are playing a game: They alternate turns and pick one coin at a time, which they put in their pockets. Whoever picks the dime wins. You are trying to decide whether it is better to play first or second: Initially you think that if you pick the dime in your first draw, you immediately win, while if you opt to play second, your probability to pick the dime increases. Which of the two options is more favorable for you? We assume that you can’t see the coins before taking them out of the pouch and also that you can’t tell from the size which coin is which. My thought: Let's say we have $n$ coins in total. If I play first, I have probability of picking the dime: $\frac {1}{n}+\frac {1}{n-2}+\frac {1}{n-4}...$ while if I play second, I have $\frac {1}{n-1}+\frac {1}{n-3}+\frac {1}{n-5}...$. Clearly the second option gives a larger number. Is this correct? Thank you.
2022/02/01
['https://math.stackexchange.com/questions/4371698', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/594462/']
The first essential point is that *the dime has no preference for position*, thus its Pr of being at *any* position is $\frac{1}{n}$ The second essential point is that we don't know whether $n$ is odd or even, and if it is odd, we get one extra try if we go first Thus it is always preferable to go first
Suppose we extend the game as follows. We start off the same where we draw coins one at a time, but we number the draws and mark down which coin was drawn on which numbered draw. Once we reach the dime, we record the winner as usual, but we also continue drawing the remaining coins and marking the draw number of each. In the end, we wind up with $n$ coins drawn, and the draw number for the dime is equiprobable among all $n$ draws. We mark the first player a winner if the dime was drawn in an odd-numbered draw, and we mark the second player the winner if the dime was drawn in an even numbered draw. We know that this will yield the same results. Next, all of the coins that were drawn on odd-numbered draws are distributed to the first player and all the coins that were drawn on even numbered draws are distributed to the second player. If the dime appears in the player's pile, we mark them as a winner again. Again, we know that this will yield the same results. Finally, we start over and mix up all the coins randomly and assign them into two piles. If $n$ is even, the two piles each have $\frac{n}{2}$ coins. If $n$ is odd, one pile has $\frac{n+1}{2}$ coins and the other has $\frac{n-1}{2}$ coins. We give one pile to one player and the other pile to the other. If the pile they are given contains a dime, we mark down the win. But, we continue and allow them to take turns drawing coins from their own pile. If one pile more coins than the other, the first draw must be from the bigger pile. We mark whichever player draws the dime as the winner. Again this yield the same results as the original game. We have just demonstrated different games, each with an injective set of outcomes. This demonstrates there exists a bijection between the sets of outcomes. Any probabilities of winning calculated for any of these three games applies to all three. The easiest is of course the last game where you just split up the piles evenly and whoever has the dime wins. I realize this was a lot of words, and it wasn't necessary to go through all of these steps. I explained it this way in hopes that it shows why it works. If $n$ is even, the first player wins half the time and second player wins half the time. If $n$ is odd, the first player wins $\dfrac{n+1}{2n}$ while the second player wins $\dfrac{n-1}{2n}$ of the time. Not knowing if $n$ is odd or even, there is a slight advantage in choosing to go first all the time, just in case $n$ is odd.
2,331,476
How do you list your commits along with their SHA1 values in git?
2010/02/25
['https://Stackoverflow.com/questions/2331476', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/111674/']
Exactly what format do you want? For just the one line summary and the SHA1: ``` git log --pretty=oneline ``` See git log --help for more formating options.
I'm not sure what you mean. Listing a commit *is* listing its hash, and the easiest way to do it is with git rev-list. ``` $ git rev-list HEAD ``` will give the the reverse chronological list of all commits reachable from the current HEAD.
2,331,476
How do you list your commits along with their SHA1 values in git?
2010/02/25
['https://Stackoverflow.com/questions/2331476', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/111674/']
Exactly what format do you want? For just the one line summary and the SHA1: ``` git log --pretty=oneline ``` See git log --help for more formating options.
While P00ya's answer is correct, newer versions of git allow a simpler syntax: ``` git log --oneline ``` which is shorthand for `git log --pretty=oneline --abbrev-commit` used together.
11,641,563
I don't mean to be vague, but I'm skeptical of the idea of releasing code that is intentionally turned off, and I've not been able to find any good sources relating to the subject. This may truly be a "it depends" question, in which case please feel free to down vote and remove. My specific context is a web app that we host ourselves, with bi-weekly "releases" (push to production). Also, we currently use Subversion, though there's a push to move to Git in the near future. One scenario I've heard is deploying a feature that is dependent upon a library with a known feature that hasn't been released yet, whether your own library, or a 3rd party's. Another is releasing portions of a feature as they are finished, but disabled until all the pieces are together in production. While both of these at first sounded good, I'm questioning the value of code living in production that is disabled, especially as a general practice. It seems like this could lead to unfinished features cluttering the code base, as well as leading to larger configuration files than are needed, just to provide means for disabling/enabling features. What, if any, are the benefits of deploying intentionally disabled code, and what concerns need to be addressed before we do this with any sort of frequency? Also, please share any links, and tell me if this practice has a name.
2012/07/25
['https://Stackoverflow.com/questions/11641563', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/95546/']
It is called [feature toggles](http://martinfowler.com/bliki/FeatureToggle.html) I'd argue that it is no more risky that enabling/disabling features using role-based-authorizations. Your concerns regarding code clutter and increased configurations are valid but advocates of continuous delivery would argue that the alternatives (feature branches) are worse.
The primary basis for doing this I've seen is to separate code pushes from configuration pushes. It's easier to determine whether you have a bad release or bad configuration if you can separate them. You can push a release with incomplete feature X off by default, continue to push releases that can be rolled back without enabling it, then when you decide to turn it on, you can update your config which can also be rolled back if needed.
126,705
I'm following a course where the trainer recommends to identify all the vulnerabilities affecting a web application before trying to exploit them. While I understand the need to identify all the vulnerabilities, I don't understand why **I should wait before trying to exploit a vulnerability I just found (like a sql injection, a command injection, remote file inclusion, ...) and come back to it later?** **Is there any reason to proceed like that?**
2016/06/11
['https://security.stackexchange.com/questions/126705', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/70136/']
That sounds more like a course in how to hack someone else's site than to test yours. Following the suggested logic allows the perpetrator to better plan a quick attack that will let them gain control of the machine before anyone has time to notice the attempts. That provides no benefit for someone who is only testing their own system's security.
If you keep looking you may find an easier to exploit vulnerability or one that gives you more privilege. Of course, if you first find an easy to exploit remote code execution vulnerability there's really no need to look for more.
126,705
I'm following a course where the trainer recommends to identify all the vulnerabilities affecting a web application before trying to exploit them. While I understand the need to identify all the vulnerabilities, I don't understand why **I should wait before trying to exploit a vulnerability I just found (like a sql injection, a command injection, remote file inclusion, ...) and come back to it later?** **Is there any reason to proceed like that?**
2016/06/11
['https://security.stackexchange.com/questions/126705', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/70136/']
There's a chance that the result of exploiting a vulnerability early in the test could change the application. Either crashing it or just breaking certain functionality. Thus making the need to scan for additional vulnerabilities moot. Another reason for thoroughly identifying vulnerabilities is to give the person performing the test a full understanding of the application. Perhaps that first vulnerability could be exploited even further with information gained in the later stages of the vulnerability assessment.
That sounds more like a course in how to hack someone else's site than to test yours. Following the suggested logic allows the perpetrator to better plan a quick attack that will let them gain control of the machine before anyone has time to notice the attempts. That provides no benefit for someone who is only testing their own system's security.
126,705
I'm following a course where the trainer recommends to identify all the vulnerabilities affecting a web application before trying to exploit them. While I understand the need to identify all the vulnerabilities, I don't understand why **I should wait before trying to exploit a vulnerability I just found (like a sql injection, a command injection, remote file inclusion, ...) and come back to it later?** **Is there any reason to proceed like that?**
2016/06/11
['https://security.stackexchange.com/questions/126705', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/70136/']
There's a chance that the result of exploiting a vulnerability early in the test could change the application. Either crashing it or just breaking certain functionality. Thus making the need to scan for additional vulnerabilities moot. Another reason for thoroughly identifying vulnerabilities is to give the person performing the test a full understanding of the application. Perhaps that first vulnerability could be exploited even further with information gained in the later stages of the vulnerability assessment.
If you keep looking you may find an easier to exploit vulnerability or one that gives you more privilege. Of course, if you first find an easy to exploit remote code execution vulnerability there's really no need to look for more.
60,384,568
This is a question about Template Toolkit for perl. I render my templates with a little command-line utility that has the following option enabled ``` DEBUG => Template::Constants::DEBUG_UNDEF, ``` The syntax is `render <file.tt> var1 val1 var2 val2 ....` This is very convenient because the user gets prompts about values that need to be defined, for example ``` $ render file.tt undef error - var1 is undefined $ render file.tt var1 foo undef error - var2 is undefined $ render file.tt var1 foo var2 bar ... template renders correctly ``` For some (optional) values, templates provide defaults, for example: ``` [%- DEFAULT hostname = 0 %] ``` Then the template body would typically contain: ``` [% IF hostname %] hostname = [% hostname %][% ELSE %][% -- a comment, variable hostname not provided %][% END %] ``` How do I make the above idiom work for variables where `0` is a valid value? I want the following to happen: ``` render template.tt ``` Template renders: ``` -- this is a comment, variable enable_networking not provided ``` For ``` render template.tt enable_networking 0 ``` I want ``` enable_networking = 0 ``` The problem is differentiating between defined values and false values. I have tried using `-1` (instead of `0`) both in the `DEFAULT` block and in the `[% IF enable_networking == -1 %]` statement. However, the following `DEFAULT` block ``` [% DEFAULT enable_networking = -1 %] ``` will override value `0` specified on the command-line. (It sees a `enable_networking` is false and sets it to -1) Are there any easy work-arounds (some config variable maybe?)
2020/02/24
['https://Stackoverflow.com/questions/60384568', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12312873/']
To check if a variable is undefined or not you could check if its `size` method returns something greater than 0. Of course this case only aplies if the variable is not initialized or defined at all (`enable_networking = ''` has size = 1, the same with `enable_networking = 0`) To check if a variable is not false... well... first you have to describe wich type of value is false. In this case i will take size = 0 (or size doesn't exists) as undefined, -1 as false and everything else as true: ``` [% IF enable_networking.size and enable_networking != -1 %] enable_networking = [% enable_networking %] [% ELSE %] -- a comment, variable enable_networking not provided [% END %] ``` With the code above if you run ``` render template.tt enable_networking 0 ``` The output will be `enable_networking = 0` And if you run ``` render template.tt ``` The output will be `-- a comment, variable enable_networking not provided` even if you don't declare `[% DEFAULT enable_networking = -1 %]` **EDIT 1:** The `length` method is better suited for this job: ``` [% IF enable_networking.length and enable_networking != -1 %] enable_networking = [% enable_networking %] [% ELSE %] -- a comment, variable enable_networking not provided [% END %] ``` Using `length` instead of `size` also allows you to use `enable_networking = ''` as FALSE along with -1 **EDIT 2:** Ok, after the comments i found a workaround that do the trick: the `TRY` - `CATCH` directives... For optional variables that can have value of 0 the objective would be to `TRY` setting the variable value to itself, if the variable is defined the value will be assigned, otherwise we `CATCH` the undef error and set the default value. For any other type of variable we can use the `DEFAULT` directive: ``` [% DEFAULT hostname = 0 %] [% TRY %] [% enable_networking = enable_networking %] [% CATCH %] [% enable_networking = -1; %] [% END %] hostname = [% hostname %] [% IF enable_networking != -1 AND enable_networking.length %] enable_networking = [% enable_networking %][% ELSE %]-- variable enable_networking not provided[% END %] ``` With this new template if you run ``` $ render template.tt hostname = 0 -- variable enable_networking not provided $ render template.tt enable_networking "" hostname = 0 -- variable enable_networking not provided $ render template.tt hostname myhost enable_networking 0 hostname = myhost enable_networking = 0 ```
All scalar values in TT have a `.defined` vmethod. ``` [% IF hostname.defined %] hostname = [% hostname %][% ELSE %][% -- a comment, variable hostname not provided %][% END %] ``` This is discussed in [the manual](https://metacpan.org/pod/distribution/Template-Toolkit/lib/Template/Manual/VMethods.pod#defined).
267,534
I asked this question before, [Here](https://stackoverflow.com/questions/264441/does-a-native-php-5-function-exist-that-does-the-following-in-1-line) however I think I presented the problem poorly, and got quite a few replies that may have been useful to someone but did not address the actual question and so I pose the question again. Is there a single-line native method in php that would allow me to do the following. Please, please, I understand there are other ways to do this simple thing, but the question I present is does something exist **natively in PHP** that will **grant me access to the array** values directly **without having to create a temporary array**. ``` $rand_place = explode(",",loadFile("csvOf20000places.txt")){rand(0,1000)}; ``` This is a syntax error, however ideally it would be great if this worked! Currently, it seems unavoidable that one must create a temporary array, ie **The following is what I want to avoid:** ``` $temporary_places_array = explode(",",loadFile("csvOf20000places.txt")); $rand_place = $temporary_places_array[rand(0,1000)]; ``` Also, i must note that my actual intentions are not to parse strings, or pull randomly from an array. **I simply want access into the string without a temporary variable**. This is just an example which i hope is easy to understand. There are many times service calls or things you do not have control over returns an array (such as the explode() function) and you just want access into it without having to create a temporary variable. **NATIVELY NATIVELY NATIVELY, i know i can create a function that does it.**
2008/11/06
['https://Stackoverflow.com/questions/267534', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/34561/']
There is no native PHP method of doing this. You could make a function like this: ``` function array_value($array, $key) { return $array[$key]; } ``` And then use it like this: ``` $places = "alabama,alaska,arizona .... zimbabway"; $random_place = array_value(explode(",", $places), rand(0, 1000)); ```
If it's memory concerns, there are other ways of going about this that don't split out into an array. But no, there is nothing builtin to handle this sort of situation. As an alternative, you might try: ``` $pos = 0; $num = 0; while(($pos = strpos($places, ',', $pos+1)) !== false) {$num++;} $which = rand(0, $num); $num = 0; while($num <= $which) {$pos = strpos($places, ',', $pos+1);} $random_place = substr($places, $pos, strpos($places, ',', $pos+1)); ``` I havn't tested this, so there may be a few off-by-one issues in it, but you get the idea. This could be made shorter (and quicker) by cacheing the positions that you work out in the first loop, but this brings you back to the memory issues.
267,534
I asked this question before, [Here](https://stackoverflow.com/questions/264441/does-a-native-php-5-function-exist-that-does-the-following-in-1-line) however I think I presented the problem poorly, and got quite a few replies that may have been useful to someone but did not address the actual question and so I pose the question again. Is there a single-line native method in php that would allow me to do the following. Please, please, I understand there are other ways to do this simple thing, but the question I present is does something exist **natively in PHP** that will **grant me access to the array** values directly **without having to create a temporary array**. ``` $rand_place = explode(",",loadFile("csvOf20000places.txt")){rand(0,1000)}; ``` This is a syntax error, however ideally it would be great if this worked! Currently, it seems unavoidable that one must create a temporary array, ie **The following is what I want to avoid:** ``` $temporary_places_array = explode(",",loadFile("csvOf20000places.txt")); $rand_place = $temporary_places_array[rand(0,1000)]; ``` Also, i must note that my actual intentions are not to parse strings, or pull randomly from an array. **I simply want access into the string without a temporary variable**. This is just an example which i hope is easy to understand. There are many times service calls or things you do not have control over returns an array (such as the explode() function) and you just want access into it without having to create a temporary variable. **NATIVELY NATIVELY NATIVELY, i know i can create a function that does it.**
2008/11/06
['https://Stackoverflow.com/questions/267534', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/34561/']
There is no native PHP method of doing this. You could make a function like this: ``` function array_value($array, $key) { return $array[$key]; } ``` And then use it like this: ``` $places = "alabama,alaska,arizona .... zimbabway"; $random_place = array_value(explode(",", $places), rand(0, 1000)); ```
I spent a great deal of last year researching advanced CSV parsing for PHP and I admit it would be nice to randomly seek at will on a file. One of my semi-deadend's was to scan through a known file and make an index of the position of all known \n's that were not at the beginning of the line. ``` //Grab and load our index $index = unserialize(file_get_contents('somefile.ext.ind')); //What it looks like $index = array( 0 => 83, 1 => 162, 2 => 178, ....); $fHandle = fopen("somefile.ext",'RB'); $randPos = rand(0, count($index)); fseek($fHandle, $index[$randPos]); $line = explode(",", fgets($fHandle)); ``` Tha's the only way I could see it being done anywhere close to what you need. As for creating the index, that's rudimentary stuff. ``` $fHandle = fopen('somefile.ext','rb'); $index = array(); for($i = 0; false !== ($char = fgetc($fHandle)); $i++){ if($char === "\n") $index[] = $i; } ```
267,534
I asked this question before, [Here](https://stackoverflow.com/questions/264441/does-a-native-php-5-function-exist-that-does-the-following-in-1-line) however I think I presented the problem poorly, and got quite a few replies that may have been useful to someone but did not address the actual question and so I pose the question again. Is there a single-line native method in php that would allow me to do the following. Please, please, I understand there are other ways to do this simple thing, but the question I present is does something exist **natively in PHP** that will **grant me access to the array** values directly **without having to create a temporary array**. ``` $rand_place = explode(",",loadFile("csvOf20000places.txt")){rand(0,1000)}; ``` This is a syntax error, however ideally it would be great if this worked! Currently, it seems unavoidable that one must create a temporary array, ie **The following is what I want to avoid:** ``` $temporary_places_array = explode(",",loadFile("csvOf20000places.txt")); $rand_place = $temporary_places_array[rand(0,1000)]; ``` Also, i must note that my actual intentions are not to parse strings, or pull randomly from an array. **I simply want access into the string without a temporary variable**. This is just an example which i hope is easy to understand. There are many times service calls or things you do not have control over returns an array (such as the explode() function) and you just want access into it without having to create a temporary variable. **NATIVELY NATIVELY NATIVELY, i know i can create a function that does it.**
2008/11/06
['https://Stackoverflow.com/questions/267534', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/34561/']
**No, there is no way to do that natively.** You can, however: 1.- Store the unavoidable array instead of the string. Given PHP's limitation this is what makes most sense in my opinion. Also, don't forget you can [unset()](http://php.net/unset) 2.- Use strpos() and friends to parse the string into what you need, as shown in other answers I won't paste here. 3.- Create a function.
If it's memory concerns, there are other ways of going about this that don't split out into an array. But no, there is nothing builtin to handle this sort of situation. As an alternative, you might try: ``` $pos = 0; $num = 0; while(($pos = strpos($places, ',', $pos+1)) !== false) {$num++;} $which = rand(0, $num); $num = 0; while($num <= $which) {$pos = strpos($places, ',', $pos+1);} $random_place = substr($places, $pos, strpos($places, ',', $pos+1)); ``` I havn't tested this, so there may be a few off-by-one issues in it, but you get the idea. This could be made shorter (and quicker) by cacheing the positions that you work out in the first loop, but this brings you back to the memory issues.
267,534
I asked this question before, [Here](https://stackoverflow.com/questions/264441/does-a-native-php-5-function-exist-that-does-the-following-in-1-line) however I think I presented the problem poorly, and got quite a few replies that may have been useful to someone but did not address the actual question and so I pose the question again. Is there a single-line native method in php that would allow me to do the following. Please, please, I understand there are other ways to do this simple thing, but the question I present is does something exist **natively in PHP** that will **grant me access to the array** values directly **without having to create a temporary array**. ``` $rand_place = explode(",",loadFile("csvOf20000places.txt")){rand(0,1000)}; ``` This is a syntax error, however ideally it would be great if this worked! Currently, it seems unavoidable that one must create a temporary array, ie **The following is what I want to avoid:** ``` $temporary_places_array = explode(",",loadFile("csvOf20000places.txt")); $rand_place = $temporary_places_array[rand(0,1000)]; ``` Also, i must note that my actual intentions are not to parse strings, or pull randomly from an array. **I simply want access into the string without a temporary variable**. This is just an example which i hope is easy to understand. There are many times service calls or things you do not have control over returns an array (such as the explode() function) and you just want access into it without having to create a temporary variable. **NATIVELY NATIVELY NATIVELY, i know i can create a function that does it.**
2008/11/06
['https://Stackoverflow.com/questions/267534', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/34561/']
**No, there is no way to do that natively.** You can, however: 1.- Store the unavoidable array instead of the string. Given PHP's limitation this is what makes most sense in my opinion. Also, don't forget you can [unset()](http://php.net/unset) 2.- Use strpos() and friends to parse the string into what you need, as shown in other answers I won't paste here. 3.- Create a function.
``` list($rand_place) = array_slice(explode(',', loadFile("csvOf20000places.txt")), array_rand(explode(',', loadFile("csvOf20000places.txt"))), 1); ``` **EDIT:** Ok, you're right. The question is *very* hard to understand but, I think this is it. The code above will pull random items from the csv file but, to just pull whatever you want out, use this: ``` list($rand_place) = array_slice(explode(',', loadFile("csvOf20000places.txt")), {YOUR_NUMBER}, 1); ``` Replace the holder with the numeric key of the value you want to pull out.
267,534
I asked this question before, [Here](https://stackoverflow.com/questions/264441/does-a-native-php-5-function-exist-that-does-the-following-in-1-line) however I think I presented the problem poorly, and got quite a few replies that may have been useful to someone but did not address the actual question and so I pose the question again. Is there a single-line native method in php that would allow me to do the following. Please, please, I understand there are other ways to do this simple thing, but the question I present is does something exist **natively in PHP** that will **grant me access to the array** values directly **without having to create a temporary array**. ``` $rand_place = explode(",",loadFile("csvOf20000places.txt")){rand(0,1000)}; ``` This is a syntax error, however ideally it would be great if this worked! Currently, it seems unavoidable that one must create a temporary array, ie **The following is what I want to avoid:** ``` $temporary_places_array = explode(",",loadFile("csvOf20000places.txt")); $rand_place = $temporary_places_array[rand(0,1000)]; ``` Also, i must note that my actual intentions are not to parse strings, or pull randomly from an array. **I simply want access into the string without a temporary variable**. This is just an example which i hope is easy to understand. There are many times service calls or things you do not have control over returns an array (such as the explode() function) and you just want access into it without having to create a temporary variable. **NATIVELY NATIVELY NATIVELY, i know i can create a function that does it.**
2008/11/06
['https://Stackoverflow.com/questions/267534', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/34561/']
I know it's poor form to answer a question with a question, but why are you concerned about this? Is it a nitpick, or an optimization question? The Zend engine will optimize this away. However, I'd point out you don't have to create a temporary variable *necessarily*: ``` $rand_place = explode(",",loadFile("csvOf20000places.txt")); $rand_place = $rand_place[rand(0,1000)]; ``` Because of type mutability, you could reuse the variable. Of course, you're still not skipping a step.
You can do this: ``` <?php function foo() { return new ArrayObject(explode(",", "zero,one,two")); } echo foo()->offsetGet(1); // "one" ?> ``` Sadly you **can't** do this: ``` echo (new ArrayObject(explode(",", "zero,one,two")))->offsetGet(2); ```
267,534
I asked this question before, [Here](https://stackoverflow.com/questions/264441/does-a-native-php-5-function-exist-that-does-the-following-in-1-line) however I think I presented the problem poorly, and got quite a few replies that may have been useful to someone but did not address the actual question and so I pose the question again. Is there a single-line native method in php that would allow me to do the following. Please, please, I understand there are other ways to do this simple thing, but the question I present is does something exist **natively in PHP** that will **grant me access to the array** values directly **without having to create a temporary array**. ``` $rand_place = explode(",",loadFile("csvOf20000places.txt")){rand(0,1000)}; ``` This is a syntax error, however ideally it would be great if this worked! Currently, it seems unavoidable that one must create a temporary array, ie **The following is what I want to avoid:** ``` $temporary_places_array = explode(",",loadFile("csvOf20000places.txt")); $rand_place = $temporary_places_array[rand(0,1000)]; ``` Also, i must note that my actual intentions are not to parse strings, or pull randomly from an array. **I simply want access into the string without a temporary variable**. This is just an example which i hope is easy to understand. There are many times service calls or things you do not have control over returns an array (such as the explode() function) and you just want access into it without having to create a temporary variable. **NATIVELY NATIVELY NATIVELY, i know i can create a function that does it.**
2008/11/06
['https://Stackoverflow.com/questions/267534', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/34561/']
**No, there is no way to do that natively.** You can, however: 1.- Store the unavoidable array instead of the string. Given PHP's limitation this is what makes most sense in my opinion. Also, don't forget you can [unset()](http://php.net/unset) 2.- Use strpos() and friends to parse the string into what you need, as shown in other answers I won't paste here. 3.- Create a function.
I spent a great deal of last year researching advanced CSV parsing for PHP and I admit it would be nice to randomly seek at will on a file. One of my semi-deadend's was to scan through a known file and make an index of the position of all known \n's that were not at the beginning of the line. ``` //Grab and load our index $index = unserialize(file_get_contents('somefile.ext.ind')); //What it looks like $index = array( 0 => 83, 1 => 162, 2 => 178, ....); $fHandle = fopen("somefile.ext",'RB'); $randPos = rand(0, count($index)); fseek($fHandle, $index[$randPos]); $line = explode(",", fgets($fHandle)); ``` Tha's the only way I could see it being done anywhere close to what you need. As for creating the index, that's rudimentary stuff. ``` $fHandle = fopen('somefile.ext','rb'); $index = array(); for($i = 0; false !== ($char = fgetc($fHandle)); $i++){ if($char === "\n") $index[] = $i; } ```
267,534
I asked this question before, [Here](https://stackoverflow.com/questions/264441/does-a-native-php-5-function-exist-that-does-the-following-in-1-line) however I think I presented the problem poorly, and got quite a few replies that may have been useful to someone but did not address the actual question and so I pose the question again. Is there a single-line native method in php that would allow me to do the following. Please, please, I understand there are other ways to do this simple thing, but the question I present is does something exist **natively in PHP** that will **grant me access to the array** values directly **without having to create a temporary array**. ``` $rand_place = explode(",",loadFile("csvOf20000places.txt")){rand(0,1000)}; ``` This is a syntax error, however ideally it would be great if this worked! Currently, it seems unavoidable that one must create a temporary array, ie **The following is what I want to avoid:** ``` $temporary_places_array = explode(",",loadFile("csvOf20000places.txt")); $rand_place = $temporary_places_array[rand(0,1000)]; ``` Also, i must note that my actual intentions are not to parse strings, or pull randomly from an array. **I simply want access into the string without a temporary variable**. This is just an example which i hope is easy to understand. There are many times service calls or things you do not have control over returns an array (such as the explode() function) and you just want access into it without having to create a temporary variable. **NATIVELY NATIVELY NATIVELY, i know i can create a function that does it.**
2008/11/06
['https://Stackoverflow.com/questions/267534', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/34561/']
``` list($rand_place) = array_slice(explode(',', loadFile("csvOf20000places.txt")), array_rand(explode(',', loadFile("csvOf20000places.txt"))), 1); ``` **EDIT:** Ok, you're right. The question is *very* hard to understand but, I think this is it. The code above will pull random items from the csv file but, to just pull whatever you want out, use this: ``` list($rand_place) = array_slice(explode(',', loadFile("csvOf20000places.txt")), {YOUR_NUMBER}, 1); ``` Replace the holder with the numeric key of the value you want to pull out.
I spent a great deal of last year researching advanced CSV parsing for PHP and I admit it would be nice to randomly seek at will on a file. One of my semi-deadend's was to scan through a known file and make an index of the position of all known \n's that were not at the beginning of the line. ``` //Grab and load our index $index = unserialize(file_get_contents('somefile.ext.ind')); //What it looks like $index = array( 0 => 83, 1 => 162, 2 => 178, ....); $fHandle = fopen("somefile.ext",'RB'); $randPos = rand(0, count($index)); fseek($fHandle, $index[$randPos]); $line = explode(",", fgets($fHandle)); ``` Tha's the only way I could see it being done anywhere close to what you need. As for creating the index, that's rudimentary stuff. ``` $fHandle = fopen('somefile.ext','rb'); $index = array(); for($i = 0; false !== ($char = fgetc($fHandle)); $i++){ if($char === "\n") $index[] = $i; } ```
267,534
I asked this question before, [Here](https://stackoverflow.com/questions/264441/does-a-native-php-5-function-exist-that-does-the-following-in-1-line) however I think I presented the problem poorly, and got quite a few replies that may have been useful to someone but did not address the actual question and so I pose the question again. Is there a single-line native method in php that would allow me to do the following. Please, please, I understand there are other ways to do this simple thing, but the question I present is does something exist **natively in PHP** that will **grant me access to the array** values directly **without having to create a temporary array**. ``` $rand_place = explode(",",loadFile("csvOf20000places.txt")){rand(0,1000)}; ``` This is a syntax error, however ideally it would be great if this worked! Currently, it seems unavoidable that one must create a temporary array, ie **The following is what I want to avoid:** ``` $temporary_places_array = explode(",",loadFile("csvOf20000places.txt")); $rand_place = $temporary_places_array[rand(0,1000)]; ``` Also, i must note that my actual intentions are not to parse strings, or pull randomly from an array. **I simply want access into the string without a temporary variable**. This is just an example which i hope is easy to understand. There are many times service calls or things you do not have control over returns an array (such as the explode() function) and you just want access into it without having to create a temporary variable. **NATIVELY NATIVELY NATIVELY, i know i can create a function that does it.**
2008/11/06
['https://Stackoverflow.com/questions/267534', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/34561/']
``` list($rand_place) = array_slice(explode(',', loadFile("csvOf20000places.txt")), array_rand(explode(',', loadFile("csvOf20000places.txt"))), 1); ``` **EDIT:** Ok, you're right. The question is *very* hard to understand but, I think this is it. The code above will pull random items from the csv file but, to just pull whatever you want out, use this: ``` list($rand_place) = array_slice(explode(',', loadFile("csvOf20000places.txt")), {YOUR_NUMBER}, 1); ``` Replace the holder with the numeric key of the value you want to pull out.
You can do this: ``` <?php function foo() { return new ArrayObject(explode(",", "zero,one,two")); } echo foo()->offsetGet(1); // "one" ?> ``` Sadly you **can't** do this: ``` echo (new ArrayObject(explode(",", "zero,one,two")))->offsetGet(2); ```
267,534
I asked this question before, [Here](https://stackoverflow.com/questions/264441/does-a-native-php-5-function-exist-that-does-the-following-in-1-line) however I think I presented the problem poorly, and got quite a few replies that may have been useful to someone but did not address the actual question and so I pose the question again. Is there a single-line native method in php that would allow me to do the following. Please, please, I understand there are other ways to do this simple thing, but the question I present is does something exist **natively in PHP** that will **grant me access to the array** values directly **without having to create a temporary array**. ``` $rand_place = explode(",",loadFile("csvOf20000places.txt")){rand(0,1000)}; ``` This is a syntax error, however ideally it would be great if this worked! Currently, it seems unavoidable that one must create a temporary array, ie **The following is what I want to avoid:** ``` $temporary_places_array = explode(",",loadFile("csvOf20000places.txt")); $rand_place = $temporary_places_array[rand(0,1000)]; ``` Also, i must note that my actual intentions are not to parse strings, or pull randomly from an array. **I simply want access into the string without a temporary variable**. This is just an example which i hope is easy to understand. There are many times service calls or things you do not have control over returns an array (such as the explode() function) and you just want access into it without having to create a temporary variable. **NATIVELY NATIVELY NATIVELY, i know i can create a function that does it.**
2008/11/06
['https://Stackoverflow.com/questions/267534', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/34561/']
I know it's poor form to answer a question with a question, but why are you concerned about this? Is it a nitpick, or an optimization question? The Zend engine will optimize this away. However, I'd point out you don't have to create a temporary variable *necessarily*: ``` $rand_place = explode(",",loadFile("csvOf20000places.txt")); $rand_place = $rand_place[rand(0,1000)]; ``` Because of type mutability, you could reuse the variable. Of course, you're still not skipping a step.
If it's memory concerns, there are other ways of going about this that don't split out into an array. But no, there is nothing builtin to handle this sort of situation. As an alternative, you might try: ``` $pos = 0; $num = 0; while(($pos = strpos($places, ',', $pos+1)) !== false) {$num++;} $which = rand(0, $num); $num = 0; while($num <= $which) {$pos = strpos($places, ',', $pos+1);} $random_place = substr($places, $pos, strpos($places, ',', $pos+1)); ``` I havn't tested this, so there may be a few off-by-one issues in it, but you get the idea. This could be made shorter (and quicker) by cacheing the positions that you work out in the first loop, but this brings you back to the memory issues.
267,534
I asked this question before, [Here](https://stackoverflow.com/questions/264441/does-a-native-php-5-function-exist-that-does-the-following-in-1-line) however I think I presented the problem poorly, and got quite a few replies that may have been useful to someone but did not address the actual question and so I pose the question again. Is there a single-line native method in php that would allow me to do the following. Please, please, I understand there are other ways to do this simple thing, but the question I present is does something exist **natively in PHP** that will **grant me access to the array** values directly **without having to create a temporary array**. ``` $rand_place = explode(",",loadFile("csvOf20000places.txt")){rand(0,1000)}; ``` This is a syntax error, however ideally it would be great if this worked! Currently, it seems unavoidable that one must create a temporary array, ie **The following is what I want to avoid:** ``` $temporary_places_array = explode(",",loadFile("csvOf20000places.txt")); $rand_place = $temporary_places_array[rand(0,1000)]; ``` Also, i must note that my actual intentions are not to parse strings, or pull randomly from an array. **I simply want access into the string without a temporary variable**. This is just an example which i hope is easy to understand. There are many times service calls or things you do not have control over returns an array (such as the explode() function) and you just want access into it without having to create a temporary variable. **NATIVELY NATIVELY NATIVELY, i know i can create a function that does it.**
2008/11/06
['https://Stackoverflow.com/questions/267534', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/34561/']
``` list($rand_place) = array_slice(explode(',', loadFile("csvOf20000places.txt")), array_rand(explode(',', loadFile("csvOf20000places.txt"))), 1); ``` **EDIT:** Ok, you're right. The question is *very* hard to understand but, I think this is it. The code above will pull random items from the csv file but, to just pull whatever you want out, use this: ``` list($rand_place) = array_slice(explode(',', loadFile("csvOf20000places.txt")), {YOUR_NUMBER}, 1); ``` Replace the holder with the numeric key of the value you want to pull out.
If it's memory concerns, there are other ways of going about this that don't split out into an array. But no, there is nothing builtin to handle this sort of situation. As an alternative, you might try: ``` $pos = 0; $num = 0; while(($pos = strpos($places, ',', $pos+1)) !== false) {$num++;} $which = rand(0, $num); $num = 0; while($num <= $which) {$pos = strpos($places, ',', $pos+1);} $random_place = substr($places, $pos, strpos($places, ',', $pos+1)); ``` I havn't tested this, so there may be a few off-by-one issues in it, but you get the idea. This could be made shorter (and quicker) by cacheing the positions that you work out in the first loop, but this brings you back to the memory issues.
5,054,428
javascript noob trying to figure something out. I saw a script located here: [Using jQuery to open all external links in a new window](https://stackoverflow.com/questions/1871371/using-jquery-to-open-all-external-links-in-a-new-window) in which urls on a page are checked to see if they match the current page url. If not, this particular script would open them in a new window. I would like to use the same test on urls but if they are external I would like ?iframe to be appended to each url, a la fancybox syntax. My noob script is: ``` $(document).ready(function() { $('a[@href^="http://"]').filter(function() { return this.hostname && this.hostname !== location.hostname; }).append('?iframe') }); ``` which I believe is incorrect. Any assistance? Thanks
2011/02/20
['https://Stackoverflow.com/questions/5054428', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/611318/']
You have to change the `href` attribute using [`attr`](http://api.jquery.com/attr/), not `append` new child elements: ``` $('a[href^="http://"]').filter(function() { // no @ before the attribute name return this.hostname && this.hostname !== location.hostname; }).attr('href', function(i, value) { // takes care of URLs with parameters return value + (value.indexOf('?') > 0 ? '&' : '?') + 'iframe'; }); ``` Note that `hostname` is [only available in HTML5](https://developer.mozilla.org/en/DOM/HTMLAnchorElement). So in browsers not supporting HTML 5, the filter would discard every element (*Update: Given that the question you linked to is from 2009, it seems browsers implemented `hostname` but it was not part of any specification*). You can change it to: ``` var hostname = new RegExp("^http://" + location.hostname); $('a[href^="http://"]').filter(function() { return !hostname.test(this.href); }).attr('href', function(i, value) { return value + (value.indexOf('?') > 0 ? '&' : '?') + 'iframe'; }); ``` And if you also want to convert links to `https` websites, ditch the attribute selector and change the regular expression: ``` var hostname = new RegExp("^https?://" + location.hostname); $('a').filter(function() {... ``` --- **Update:** Specifically for fancybox, according to the [documentation](http://fancybox.net/howto), it should work this way. However, you are right, you could just add the `iframe` class: ``` $('a').filter(function() {...}).addClass('iframe'); ```
Instead of append, which modifies the inner HTML of the element, modify the href attribute: ``` $(document).ready(function() { var elements = $('a[@href^="http://"]').filter(function() { return this.hostname && this.hostname !== location.hostname; }); elements.each(function(index, value) { $(this).attr('href', $(this).attr('href') + '?iframe'); }); }); ```
5,054,428
javascript noob trying to figure something out. I saw a script located here: [Using jQuery to open all external links in a new window](https://stackoverflow.com/questions/1871371/using-jquery-to-open-all-external-links-in-a-new-window) in which urls on a page are checked to see if they match the current page url. If not, this particular script would open them in a new window. I would like to use the same test on urls but if they are external I would like ?iframe to be appended to each url, a la fancybox syntax. My noob script is: ``` $(document).ready(function() { $('a[@href^="http://"]').filter(function() { return this.hostname && this.hostname !== location.hostname; }).append('?iframe') }); ``` which I believe is incorrect. Any assistance? Thanks
2011/02/20
['https://Stackoverflow.com/questions/5054428', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/611318/']
You have to change the `href` attribute using [`attr`](http://api.jquery.com/attr/), not `append` new child elements: ``` $('a[href^="http://"]').filter(function() { // no @ before the attribute name return this.hostname && this.hostname !== location.hostname; }).attr('href', function(i, value) { // takes care of URLs with parameters return value + (value.indexOf('?') > 0 ? '&' : '?') + 'iframe'; }); ``` Note that `hostname` is [only available in HTML5](https://developer.mozilla.org/en/DOM/HTMLAnchorElement). So in browsers not supporting HTML 5, the filter would discard every element (*Update: Given that the question you linked to is from 2009, it seems browsers implemented `hostname` but it was not part of any specification*). You can change it to: ``` var hostname = new RegExp("^http://" + location.hostname); $('a[href^="http://"]').filter(function() { return !hostname.test(this.href); }).attr('href', function(i, value) { return value + (value.indexOf('?') > 0 ? '&' : '?') + 'iframe'; }); ``` And if you also want to convert links to `https` websites, ditch the attribute selector and change the regular expression: ``` var hostname = new RegExp("^https?://" + location.hostname); $('a').filter(function() {... ``` --- **Update:** Specifically for fancybox, according to the [documentation](http://fancybox.net/howto), it should work this way. However, you are right, you could just add the `iframe` class: ``` $('a').filter(function() {...}).addClass('iframe'); ```
Your use of the `append` method is incorrect. The following code shows how to achieve what you require, plus it takes into account a couple of additional factors that you need to bear in mind, namely: 1) What about links that use https rather than http? 2) What about links that already contains querystring parameters? <http://www.blah.com/?something=123> should be changed to <http://www.blah.com/?something=123&iframe> rather than <http://www.blah.com/?something=123?iframe> ``` $(function() { $('a[href^="http"]').filter(function() { return this.hostname && this.hostname !== location.hostname; }).each(function() { this.href += ((this.href.indexOf('?') >= 0) ? '&' : '?') + 'iframe'; }); }); ```
3,396,783
I'm playing with my favorite thing, xml (have the decency to kill me please) and the ultimate goal is save it in-house and use the data in a different manner (this is an export from another system). I've got goo that works, but meh, I think it can be a lot better. ``` public Position(XElement element) { Id = element.GetElementByName("id"); Title = element.GetElementByName("title"); } ``` I'm thinking of making it more automated (hacky) by adding data annotations for the xml element it represents. Something like this for instance. ``` [XmlElement("id")] public string Id { get; set; } [XmlElement("title")] public string Title { get; set; } ``` then writing some reflection/mapper code but both ways feels ... dirty. Should I care? Is there a better way? Maybe deserialize is the right approach? I just have a feeling there's a mo' bettah way to do this.
2010/08/03
['https://Stackoverflow.com/questions/3396783', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/202728/']
You can use the [`XmlSerializer`](http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx) class and markup your class properties with [attributes](http://msdn.microsoft.com/en-us/library/83y7df3e(VS.71).aspx) to control the serialization and deserialization of the objects. Here's a simple method you can use to deserialize your `XDocument` into your object: ``` public static T DeserializeXml<T>(XDocument document) { using (var reader = document.CreateReader()) { var serializer = new XmlSerializer(typeof (T)); return (T) serializer.Deserialize(reader); } } ``` and a simple serializer method: ``` public static String ToXml<T>(T instance) { using (var output = new StringWriter(new StringBuilder())) { var serializer = new XmlSerializer(typeof(T)); serializer.Serialize(output, instance); return output.ToString(); } } ```
The mechanism that you are suggesting already exists in the form of the [XmlSerializer](http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx) class and a set of custom attributes that you can use to control the serialisation process. In fact the .Net framework comes with a tool [xsd.exe](http://msdn.microsoft.com/en-us/library/x6c1kb0s(VS.71).aspx) which will generate these class files for you from a schema definition (.xsd) file. Also, just to make things really easy, Visual Studio even has the ability to generate you an .xsd schema for an xml snippet (its hidden away in the Xml menu somewhere).
176,382
Introduction: ------------- I'm trying to make a Sorcerer subclass that has a Lovecraftian/Far Realm theme. I tried to balance it around Shadow, Divine Soul, Storm and the Abberant/Psionic Mind UA. (I realize that is probably over-tuned some) I'm hoping this isn't overly powerful though probably on the higher end of the spectrum. I'll be play testing it in about a month give or take a week. Design ------ One of the things I wanted in this subclass was an extended spell list as I feel, having played a sorcerer in Pathfinder 1e and DnD 5e, that the limited spells known combined with everyone being a spontaneous caster shoehorn Sorcerers a bit too much into glass cannons with no real versatility. I also wanted a unique feel and theme without stepping on the other subclasses' toes. The Subclass ------------ Umbra Spawn ----------- Level 1: Improved Dark Vision: * Dark Vision - 120 Feet This is right from Shadow Sorcery * Expanded Spell List: These spells are granted as you gain the appropriate level in this subclass to cast them. They are gained automatically and do not count towards spells known. You can see through magical darkness caused by any of these spells that you cast. ``` Spell Name Spell Level Class Level Arms of Hadar level 1 level 1 Darkness level 2 level 3 Hunger of Hadar level 3 level 5 Shadow of Moil level 4 level 7 Synaptic Static level 5 level 9 ``` I'm not too thrilled with Synaptic Static but couldn't find a better thematic spell from PHB or XtGE. I thought about giving Dimension Door at 9 but it made the wording clunky and I felt a linear progression made more sense. I also considered making these spells castable through Sorcery points a la Shadow Magic, though I left that out. Level 6: Far Touch: * You can cast spells with a range of touch up to a range of 30 feet. I'm unsure of how necessary this is, it might make level 6 too strong, though feels thematic. Umbra Tendril: * As a bonus action you can create a void tendril to push or pull yourself or another creature you can see 10 feet. If the creature is unwilling, it makes a strength save against your spell save DC. This ability has a range of 30 feet. I discussed this feature with the DM of my upcoming game, he's going to rule that a creature willing to be moved will trigger Attacks of Opportunity. So the question becomes how powerful is the versatility of this ability. Level 14: Into the Void: * As a reaction to being targeted by a creature you can see, you may spend 2 sorcery points, you are under the effect of blur until the start of your next turn. This does not require concentration. I originally had levels 6 and 14 switched, but I want the core of the class to be the tendril and not the blur. The downside being a lack of sorcery point dumps for 14 levels. Level 18: Umbra Incarnate: * As a bonus action you may spend 6 sorcery points to manifest the void for 1 minute. While under this effect you gain the following: + You have a Flying Speed equal to your movement speed. + You may use your void tendrils up to three times as a bonus action and when this ability is activated. If the target fails their save they take 2D6 force damage. + Magical Darkness is centered around you with a radius of 15 feet. Any number of creatures in range you designate when this ability is activated can see through this darkness. + You are immune to fear effects. Question -------- **Is this balanced as a Sorcerer subclass and is the wording and intent of each feature clear and in line with officially published materials?** I had the flavor of the class in mind while designing this and really wanted the expanded spell list. I am completely unsure of how the tendrils, especially at level 18, are balanced as they work a bit differently from published materials I am aware of.
2020/10/12
['https://rpg.stackexchange.com/questions/176382', 'https://rpg.stackexchange.com', 'https://rpg.stackexchange.com/users/59619/']
Most of this looks fine, so I'll mainly focus on the outliers. **And boy-oh-boy is the level 18 ability an outlier.** That said, I do want to preface this by saying that stepping outside the bounds of balance is the best part of homebrew. This criticism shouldn't distract from the fact that you've got a fun subclass on your hands; it just needs a bit of tweaking. Umbral Incarnate is *significantly* more powerful than any other Sorcerer option, and probably any other ability in 5e. ----------------------------------------------------------------------------------------------------------------------- I would be scared to put this ability on a BBEG, let alone a PC. As it stands, it will warp player choices across classes while simultaneously resulting in an unsatisfying gameplay pattern. Let's start from the top. * *Flying speed*: by itself, this is a perfectly sound choice. Flight is prevalent at higher levels and lends itself well to over-the-top, dynamic battles. No problems here. * *3x tentacle use + 2d6 force damage per tentacle*: This provides far too much battlefield control and damage. This effectively allows the user to emulate a Repelling Blast/Grasp of Hadar Warlock's entire Eldritch Blast rotation on a *bonus action*. Martial classes salivate at the idea of this much battlefield influence. + Thematically, necrotic damage would be a better fit for this ability. + **Recommendation**: I can sense that this is intended to amplify the satisfaction of using the tentacles, which I think is a good goal, as it's the most unique thing this class has to offer. This should require a full action. As it stands, it provides far too much utility and versatility to be balanced. * *Magical darkness penetrable by you and your allies*: very few creatures can see through magical darkness. To my knowledge, only devils and creatures with blindsight or truesight are capable of doing so. This means that the sorcerer and their party will be effectively under the effect of *Greater Invisibility* against *almost every creature in 5e*. All their attacks will have advantage, all attacks against them will be made at disadvantage, and they will be immune to any spells that require sight... *at any range* (as heavily obscured is distance-agnostic). With this effect alone, Umbra Incarnate obliterates this and *any* other similar ability in the game, bar none. + Compare this to the Draconic Bloodline's capstone ability: it inflicts the significantly weaker Frightened condition (disadvantage on attacks + movement penalization), **requires a save**, **requires Concentration**, ***is activated on an action***, only affects targets out to 60 feet, and provides *no* benefits to allies. + This effect has anti-synergy with the flight ability, which encourages movement, as the Sorcerer will be encouraged to stay bound to their party at all times. + **Recommendation**: this should just be regular magical darkness that only the Sorcerer can see through. Applying it to allies makes this stronger than just about any capstone ability in 5e. Additionally, this is too strong of an effect to be activated on a bonus action; make this an action instead. * *Frightened immunity*: there's enough going on here already. + **Recommendation**: remove this. Overall, there's just way too much stuff in this ability, *but it's not a bad idea*. Tone it down and you have a cool kit-amplification ability. 6th Level has too much packed into it. -------------------------------------- Either abilities are fine on their own, but I strongly prefer keeping Umbra Tentacle over Far Touch: Umbra Tentacle is a neat, gameplay defining tool, as it: * Requires no sorcery points to use. * Takes a bonus action, meaning it's almost always available, as Sorcerers rarely take bonus actions. I would clean up the verbiage to make it the source of the ability more clear (does it come from you or a point of your choosing?), but on its own I think this ability is a solid foundation to build upon. Far Touch, however, takes this ability over the top. Umbra Tentacle is similar in power to each other 6th Level ability, so there's no need to cram another ability in, especially something as powerful as a *cost-free* Distant Spell usage on every touch spell. Far Touch should be moved to 14th Level. Into the Void can go. -------------------------------------------------------------- As the ability to see through magical darkness is an integral part of this subclass, in most cases the Sorcerer will want to engage enemies from the cover of magical darkness. As such, attacks against them will already be made at disadvantage, so Into the Void will rarely be useful. Good news: this is the perfect spot for Far Touch. 1st Level is great! ------------------- 1st Level is thematically satisfying and directs the Sorcerer into choices that will reinforce the thematic of this subclass. No tweaks needed here.
Balanced yes, though some changes may make the subclass more distinct ===================================================================== Sorcerer Homebrews are difficult to balance, because you always have to think about the sorcery point cost of abilities. What I've given below are estimates of what I think would be balanced, but the best way to be sure of what does and does not work is to playtest. *Extended Darkvision* - Useful, probably letting you see most hidden creature before they see you, but not overpowered. *Expanded Spell list* - My only worry about giving the sorcerer extra spells would be their interaction with Metamagic, however I don't believe any of these would be problematic. If you don't like Synaptic Static, Maybe consider Enervation (Though its interaction with Metamagic may be strange, specifically Twinned Spell) or Negative Energy Flood. *Far Touch* - This is basically giving the player the Distant Spell Metamagic but removing the Sorcerer point cost. Useful, but might be unnecessarily overlapping. *Umbra Tentacle* - This is interesting, and sorcerers don't often get to make use of there bonus action so it is a nice addition, however I think the two level 6 abilities might be best if combined together, as below: > > **Umbra Tentacle** - As a bonus action, you summon a spectral milky black tentacle within 30 feet of yourself. The tentacle has an AC of 10 + your Charisma Modifier, and hit points equal to 2 times your sorcerer level. The tentacle can then target a creature within 5 feet of it and force them to make a strength saving throw. On a failure, the creature is pushed 10 feet from the tentacle. On subsequent turns you can move the tentacle up to 20 feet and attempt the push again as a bonus action. You are also able to cast spells with a range of touch on creatures you can see as though you were in the tentacle's space. The tentacle disappears after one minute or if you end your turn more than 50 feet from the tentacle. You are unable to summon the tentacle again until after a long rest or if you spend 2 sorcery points. > > > This changes the tentacle to be something you need to control its location, instead of these 2 abilities being able to influence anything on the battlefield in range. I think by making the tentacle have a location and having to move it around the battlefield makes the pull unnecessary, and the ability should be fine with just a push. I tried to make this ability comparable to other similar abilities: * the Shadow Sorcerers *Hound of Ill Omen* ability is comparable, though it is able to deal damage, which I think makes it strong enough to justify the extra sorcery point cost compared to this ability. * The Trickery Domain Cleric has its *Channel Divinity: Invoke Duplicity*, which is very similar; the main difference being the Cleric can cast any spell, not just touch from the target space, and the Umbra tentacle also has its push and can be hit. * EDIT: the UA Lurker in the Deep Warlock subclass has a similar ability as the tendril, Grasp of the Deep. This is a damaging attack more than a utility one like yours, however it still might be worth taking into consideration for any future iterations of this class you try. Overall this may still feel a bit underwhelming, maybe adding some damage to the tentacles push, and increasing the Sorcery point cost to 3 could buff this up, but you would have to play test to confirm. *Into the Void* - I'm not sure if 2 sorcery points is the correct cost for this ability. Blur itself is a second level spell, and it lasts for a full minute, though this ability is able to be used as a reaction. My idea using my alternative Umbra Tentacle: > > **Void Swap** - as a reaction to being targeted by an attack from a creature you can see, you spend 1 sorcery point swap your position with your Umbra Tentacle. The attack has disadvantage on the tentacle, as the tendril's squirms in place after the transfer. > > > Since you wanted the tendril to be the core of the class, this would give the level 14 ability a further tie to the tendril, while still having a similar effect to the original ability. Again, Playtest to figure out the correct number of sorcery points here, I decreased the cost as it would only apply to a single attack instead of until the start of your next turn, and you are likely to use this ability frequently when targeted. *Umbra Incarnate* - I think this is excellent! Really matches the flavour of the class, gives a buff to the Tendril (and works with my alternative), and seems powerful enough to justify being a level 18 ability. Nicely done. Only thing to address is Sorcery Point cost: at level 18 you can use this ability 3 times before a long rest, which seems good to me, but you would need to playtest to be sure. **EDIT** I missed that you now get to use your tentacle three times as a bonus action. Tha's too much. Make it still one time and overall the ability is nice. Summary: Playtest! ------------------ The only way to know if this class is working is to playtest over and over and over again. Is the Spell List sensible? Does the Tendril have too high of a cost? Does the reaction drain spell points too quickly? You won't know until you see it in action.
26,739,981
I'm new to Cake php. I have a problem using bake I set up a migration with user table ``` public $migration = array( 'up' => array( 'create_table' => array( 'users' => array( 'user_id' => array('type' => 'integer', 'null' => false, 'key' => 'primary'), 'username' => array('type' => 'string', 'null' => false, 'length' => 250), 'password' => array('type' => 'text', 'null' => false), 'created' => array('type' => 'string', 'null' => false, 'length' => 14), 'modified' => array('type' => 'string', 'null' => true, 'default' => null, 'length' => 14), 'indexes' => array( 'PRIMARY' => array('column' => 'user_id', 'unique' => 1) ) ) ) ), 'down' => array( 'drop_table' => array( 'users' ) ) ); ``` and migrate this file on the db then I tried to do the command "cake bake all" the problem is that User made a reference to itself with belongsTo and hasMany is that the default of using bake? ``` class User extends AppModel { /** * Validation rules * * @var array */ public $validate = array( 'user_id' => array( 'numeric' => array( 'rule' => array('numeric'), //'message' => 'Your custom message here', //'allowEmpty' => false, //'required' => false, //'last' => false, // Stop validation after this rule //'on' => 'create', // Limit validation to 'create' or 'update' operations ), ), 'username' => array( 'notEmpty' => array( 'rule' => array('notEmpty'), //'message' => 'Your custom message here', //'allowEmpty' => false, //'required' => false, //'last' => false, // Stop validation after this rule //'on' => 'create', // Limit validation to 'create' or 'update' operations ), ), 'date_created' => array( 'notEmpty' => array( 'rule' => array('notEmpty'), //'message' => 'Your custom message here', //'allowEmpty' => false, //'required' => false, //'last' => false, // Stop validation after this rule //'on' => 'create', // Limit validation to 'create' or 'update' operations ), ), ); //The Associations below have been created with all possible keys, those that are not needed can be removed /** * belongsTo associations * * @var array */ public $belongsTo = array( 'User' => array( 'className' => 'User', 'foreignKey' => 'user_id', 'conditions' => '', 'fields' => '', 'order' => '' ) ); /** * hasMany associations * * @var array */ public $hasMany = array( 'User' => array( 'className' => 'User', 'foreignKey' => 'user_id', 'dependent' => false, 'conditions' => '', 'fields' => '', 'order' => '', 'limit' => '', 'offset' => '', 'exclusive' => '', 'finderQuery' => '', 'counterQuery' => '' ) ); } ``` is there something I missing here? Should I leave that and modify it manually or there's a config that I missed.
2014/11/04
['https://Stackoverflow.com/questions/26739981', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1097307/']
> > Today I have the need to allocate a vector with size 100000 in Matlab. > > > Now, as noted in the comments and such, the method you tried (`a=ones(100000);`) creates a 100000x100000 matrix, which is not what you want. I would suggest you try: ``` a = ones(1, 100000); ``` Since that creates a vector rather than a matrix.
Well the first declaration tries to build a matrix of 1000000x1000000 ones. That would be **~931 GB**. The second tries to declare a matrix of 10000 x 10000. That would be **~95MB**. I assumed each one is stored on a byte. If they use floats, than the requested memory size will be 4 times larger.
26,739,981
I'm new to Cake php. I have a problem using bake I set up a migration with user table ``` public $migration = array( 'up' => array( 'create_table' => array( 'users' => array( 'user_id' => array('type' => 'integer', 'null' => false, 'key' => 'primary'), 'username' => array('type' => 'string', 'null' => false, 'length' => 250), 'password' => array('type' => 'text', 'null' => false), 'created' => array('type' => 'string', 'null' => false, 'length' => 14), 'modified' => array('type' => 'string', 'null' => true, 'default' => null, 'length' => 14), 'indexes' => array( 'PRIMARY' => array('column' => 'user_id', 'unique' => 1) ) ) ) ), 'down' => array( 'drop_table' => array( 'users' ) ) ); ``` and migrate this file on the db then I tried to do the command "cake bake all" the problem is that User made a reference to itself with belongsTo and hasMany is that the default of using bake? ``` class User extends AppModel { /** * Validation rules * * @var array */ public $validate = array( 'user_id' => array( 'numeric' => array( 'rule' => array('numeric'), //'message' => 'Your custom message here', //'allowEmpty' => false, //'required' => false, //'last' => false, // Stop validation after this rule //'on' => 'create', // Limit validation to 'create' or 'update' operations ), ), 'username' => array( 'notEmpty' => array( 'rule' => array('notEmpty'), //'message' => 'Your custom message here', //'allowEmpty' => false, //'required' => false, //'last' => false, // Stop validation after this rule //'on' => 'create', // Limit validation to 'create' or 'update' operations ), ), 'date_created' => array( 'notEmpty' => array( 'rule' => array('notEmpty'), //'message' => 'Your custom message here', //'allowEmpty' => false, //'required' => false, //'last' => false, // Stop validation after this rule //'on' => 'create', // Limit validation to 'create' or 'update' operations ), ), ); //The Associations below have been created with all possible keys, those that are not needed can be removed /** * belongsTo associations * * @var array */ public $belongsTo = array( 'User' => array( 'className' => 'User', 'foreignKey' => 'user_id', 'conditions' => '', 'fields' => '', 'order' => '' ) ); /** * hasMany associations * * @var array */ public $hasMany = array( 'User' => array( 'className' => 'User', 'foreignKey' => 'user_id', 'dependent' => false, 'conditions' => '', 'fields' => '', 'order' => '', 'limit' => '', 'offset' => '', 'exclusive' => '', 'finderQuery' => '', 'counterQuery' => '' ) ); } ``` is there something I missing here? Should I leave that and modify it manually or there's a config that I missed.
2014/11/04
['https://Stackoverflow.com/questions/26739981', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1097307/']
> > Today I have the need to allocate a vector with size 100000 in Matlab. > > > Now, as noted in the comments and such, the method you tried (`a=ones(100000);`) creates a 100000x100000 matrix, which is not what you want. I would suggest you try: ``` a = ones(1, 100000); ``` Since that creates a vector rather than a matrix.
Arguments Matter ================ Calling Matlab's `ones()` or `zeros()` or `magic()` with a single argument `n`, creates a *square* matrix with size `n-by-n`: ```matlab >> a = ones(5) a = 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ``` Calling the same functions with 2 arguments `(r, c)` instead creates a matrix of size `r-by-c`: ```matlab >> a = ones(2, 5) a = 1 1 1 1 1 1 1 1 1 1 ``` This is all well documented in [Matlab's documentation](http://www.mathworks.de/help/matlab/ref/zeros.html). Size Matters Too ================ Doubles ------- Having said this, when you do `a = zeros(1e6)` you are creating a square matrix of size `1e6 * 1e6 = 1e12`. Since these are doubles the total allocated size would be `8 * 1e12 Bytes` which is circa `(8 * 1e12) / 1024^3 = 7450.6GB`. Do you have this much RAM on your machine? Compare this with `a = zeros(1, 1e6)` which creates a column-vector of size `1 * 1e6 = 1e6`, for a total allocated size of `(8 * 1e6) / 1024^3 = 7.63MB`. Logicals -------- Logical values, on the other hand are boolean values, which can be set to either `0` or `1` representing `False` or `True`. With this in mind, you can allocate matrices of logicals using either [`false()`](http://www.mathworks.de/help/matlab/ref/false.html) or [`true()`](http://www.mathworks.de/help/matlab/ref/true.html). Here the same single-argument rule applies, hence `a = false(1e6)` creates a square matrix of size `1e6 * 1e6 = 1e12`. Matlab today, as many other programming languages, stores bit values, such as booleans, into single Bytes. Even though there is a clear cost in terms of memory usage, such a mechanism provides significant performance improvements. This is because it is [accessing single bits is a slow operation](http://www.mathworks.com/matlabcentral/answers/22439-logical-array-memory-allocation). The total allocated size of our `a = false(1e6)` matrix would therefore be `1e12 Bytes` which is circa `1e12 / 1024^3 = 931.32GB`.
107,330
We have an environment where we have blasted a prepped Windows image out to multiple machines. We now need to customize the networking settings on each image en masse. What tools exist to modify that image and customize the IP address/netmask/gateway post-imaging? I would also look at a commercial solution that is able to deploy and customize Windows images as long as it runs on Linux and is fully scriptable. To clarify, my order of operations is: * Server PXE boots * Various Things are done to the hardware to prep it * Image is copied onto the hard drive * Image is customized (network settings) (Naturally, if such a deployment tool exists that can do the last two in one step, I'll take that)
2010/01/28
['https://serverfault.com/questions/107330', 'https://serverfault.com', 'https://serverfault.com/users/2101/']
DHCP is the only choice (IMHO) when you get over 5 or 6 machines ( and even then ... ) In your case I would also setup dDNS so that your hosts register in DNS when they get a DHCP lease, so if you know the host name you know the ip address. As far as host needed a static IP address. The best way is to let them configure off DHCP, but in the DHCP configuration reserve the IP address for that machine's MAC address. This lets you not have to manually configure IPs but still have "static" ip addressing.
Here's your main issue (as stated): > > **"We don't have access to the DHCP server"** > > > Why don't you have access to your internal DHCP server? **(fix this!)**... Your number of clients concords with most environments using DHCP (recommended). Yes, static IPs would drive you nuts!
107,330
We have an environment where we have blasted a prepped Windows image out to multiple machines. We now need to customize the networking settings on each image en masse. What tools exist to modify that image and customize the IP address/netmask/gateway post-imaging? I would also look at a commercial solution that is able to deploy and customize Windows images as long as it runs on Linux and is fully scriptable. To clarify, my order of operations is: * Server PXE boots * Various Things are done to the hardware to prep it * Image is copied onto the hard drive * Image is customized (network settings) (Naturally, if such a deployment tool exists that can do the last two in one step, I'll take that)
2010/01/28
['https://serverfault.com/questions/107330', 'https://serverfault.com', 'https://serverfault.com/users/2101/']
Here's your main issue (as stated): > > **"We don't have access to the DHCP server"** > > > Why don't you have access to your internal DHCP server? **(fix this!)**... Your number of clients concords with most environments using DHCP (recommended). Yes, static IPs would drive you nuts!
Maintaining a static addressed network quickly becomes a hassle with more than 10-15 machines. You can set static addresses within the DHCP server's GUI. While these are only faux static addresses they ensure that no other device can get that address by requesting it from the DHCP server and when that particular device asks for an address it will always receive the same one.
107,330
We have an environment where we have blasted a prepped Windows image out to multiple machines. We now need to customize the networking settings on each image en masse. What tools exist to modify that image and customize the IP address/netmask/gateway post-imaging? I would also look at a commercial solution that is able to deploy and customize Windows images as long as it runs on Linux and is fully scriptable. To clarify, my order of operations is: * Server PXE boots * Various Things are done to the hardware to prep it * Image is copied onto the hard drive * Image is customized (network settings) (Naturally, if such a deployment tool exists that can do the last two in one step, I'll take that)
2010/01/28
['https://serverfault.com/questions/107330', 'https://serverfault.com', 'https://serverfault.com/users/2101/']
DHCP is the only choice (IMHO) when you get over 5 or 6 machines ( and even then ... ) In your case I would also setup dDNS so that your hosts register in DNS when they get a DHCP lease, so if you know the host name you know the ip address. As far as host needed a static IP address. The best way is to let them configure off DHCP, but in the DHCP configuration reserve the IP address for that machine's MAC address. This lets you not have to manually configure IPs but still have "static" ip addressing.
Maintaining a static addressed network quickly becomes a hassle with more than 10-15 machines. You can set static addresses within the DHCP server's GUI. While these are only faux static addresses they ensure that no other device can get that address by requesting it from the DHCP server and when that particular device asks for an address it will always receive the same one.
107,330
We have an environment where we have blasted a prepped Windows image out to multiple machines. We now need to customize the networking settings on each image en masse. What tools exist to modify that image and customize the IP address/netmask/gateway post-imaging? I would also look at a commercial solution that is able to deploy and customize Windows images as long as it runs on Linux and is fully scriptable. To clarify, my order of operations is: * Server PXE boots * Various Things are done to the hardware to prep it * Image is copied onto the hard drive * Image is customized (network settings) (Naturally, if such a deployment tool exists that can do the last two in one step, I'll take that)
2010/01/28
['https://serverfault.com/questions/107330', 'https://serverfault.com', 'https://serverfault.com/users/2101/']
DHCP is the only choice (IMHO) when you get over 5 or 6 machines ( and even then ... ) In your case I would also setup dDNS so that your hosts register in DNS when they get a DHCP lease, so if you know the host name you know the ip address. As far as host needed a static IP address. The best way is to let them configure off DHCP, but in the DHCP configuration reserve the IP address for that machine's MAC address. This lets you not have to manually configure IPs but still have "static" ip addressing.
If you're talking about servers you **should not** be using DHCP to configure their IP addresses. This creates all sorts of headaches long-term, and even Microsoft will tell you it's not a recommended practice. I relate the parable of the DHCP network that got moved to CoLocation and left the DHCP server behind: Needless to say nothing worked at the CoLo and the admin in question looked looked like an idiot. --- For Desktops and Laptops by all means use DHCP, possibly in combination with static leases if you need to ensure that machines always have the same IP when they come onto your network. This is the most sensible configuration for your end users as it lets them put their laptops on other networks (home, hotel, starbucks) without jumping through a million hoops.
107,330
We have an environment where we have blasted a prepped Windows image out to multiple machines. We now need to customize the networking settings on each image en masse. What tools exist to modify that image and customize the IP address/netmask/gateway post-imaging? I would also look at a commercial solution that is able to deploy and customize Windows images as long as it runs on Linux and is fully scriptable. To clarify, my order of operations is: * Server PXE boots * Various Things are done to the hardware to prep it * Image is copied onto the hard drive * Image is customized (network settings) (Naturally, if such a deployment tool exists that can do the last two in one step, I'll take that)
2010/01/28
['https://serverfault.com/questions/107330', 'https://serverfault.com', 'https://serverfault.com/users/2101/']
DHCP is the only choice (IMHO) when you get over 5 or 6 machines ( and even then ... ) In your case I would also setup dDNS so that your hosts register in DNS when they get a DHCP lease, so if you know the host name you know the ip address. As far as host needed a static IP address. The best way is to let them configure off DHCP, but in the DHCP configuration reserve the IP address for that machine's MAC address. This lets you not have to manually configure IPs but still have "static" ip addressing.
Fixed IP addresses for servers - always. Printers and the like can be done either way but my preference is for fixed. Workstations, laptops and the like should always be DHCP. You should be able to solve your problems by using dynamically updated DNS. Then you don't need an IP address because you can just use the machine name. As l0c0b0x says, if you don't have access to the DHCP server you really need to fix that. An administrator should always have control over his/her network.
107,330
We have an environment where we have blasted a prepped Windows image out to multiple machines. We now need to customize the networking settings on each image en masse. What tools exist to modify that image and customize the IP address/netmask/gateway post-imaging? I would also look at a commercial solution that is able to deploy and customize Windows images as long as it runs on Linux and is fully scriptable. To clarify, my order of operations is: * Server PXE boots * Various Things are done to the hardware to prep it * Image is copied onto the hard drive * Image is customized (network settings) (Naturally, if such a deployment tool exists that can do the last two in one step, I'll take that)
2010/01/28
['https://serverfault.com/questions/107330', 'https://serverfault.com', 'https://serverfault.com/users/2101/']
If you're talking about servers you **should not** be using DHCP to configure their IP addresses. This creates all sorts of headaches long-term, and even Microsoft will tell you it's not a recommended practice. I relate the parable of the DHCP network that got moved to CoLocation and left the DHCP server behind: Needless to say nothing worked at the CoLo and the admin in question looked looked like an idiot. --- For Desktops and Laptops by all means use DHCP, possibly in combination with static leases if you need to ensure that machines always have the same IP when they come onto your network. This is the most sensible configuration for your end users as it lets them put their laptops on other networks (home, hotel, starbucks) without jumping through a million hoops.
Maintaining a static addressed network quickly becomes a hassle with more than 10-15 machines. You can set static addresses within the DHCP server's GUI. While these are only faux static addresses they ensure that no other device can get that address by requesting it from the DHCP server and when that particular device asks for an address it will always receive the same one.
107,330
We have an environment where we have blasted a prepped Windows image out to multiple machines. We now need to customize the networking settings on each image en masse. What tools exist to modify that image and customize the IP address/netmask/gateway post-imaging? I would also look at a commercial solution that is able to deploy and customize Windows images as long as it runs on Linux and is fully scriptable. To clarify, my order of operations is: * Server PXE boots * Various Things are done to the hardware to prep it * Image is copied onto the hard drive * Image is customized (network settings) (Naturally, if such a deployment tool exists that can do the last two in one step, I'll take that)
2010/01/28
['https://serverfault.com/questions/107330', 'https://serverfault.com', 'https://serverfault.com/users/2101/']
Fixed IP addresses for servers - always. Printers and the like can be done either way but my preference is for fixed. Workstations, laptops and the like should always be DHCP. You should be able to solve your problems by using dynamically updated DNS. Then you don't need an IP address because you can just use the machine name. As l0c0b0x says, if you don't have access to the DHCP server you really need to fix that. An administrator should always have control over his/her network.
Maintaining a static addressed network quickly becomes a hassle with more than 10-15 machines. You can set static addresses within the DHCP server's GUI. While these are only faux static addresses they ensure that no other device can get that address by requesting it from the DHCP server and when that particular device asks for an address it will always receive the same one.
20,077,653
I am new to android. I am trying to zoom a series of images as I have 10 images in drawable. I have an image view in main xml and 2 buttons to change the images. I took the whole idea from a question in stackoverflow. The problem is that all the images are changing perfectly but I have no idea to zoom these images. I tried the touch image view codes but remained unsuccessful. Plz help me. Main xml; ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="fill" android:orientation="vertical" android:weightSum="100" > <ImageView android:id="@+id/idImageViewPic" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="100" android:adjustViewBounds="true" android:background="#66FFFFFF" android:maxHeight="91dip" android:maxWidth="47dip" android:padding="10dip" android:src="@drawable/r0" /> <LinearLayout android:id="@+id/linearLayout1" android:layout_width="fill_parent" android:layout_height="wrap_content" > <Button android:id="@+id/bGeri" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="Önceki" > </Button> <Button android:id="@+id/bIleri" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="Sonraki" > </Button> </LinearLayout> </LinearLayout> ``` Main java. ``` package com.galerionsekiz; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; public class Main extends Activity { private ImageView hImageViewPic; private Button iButton, gButton; private int currentImage = 0; int[] images = { R.drawable.r1, R.drawable.r2, R.drawable.r3, R.drawable.r4, R.drawable.r5, R.drawable.r6, R.drawable.r7, R.drawable.r8, R.drawable.r9, R.drawable.r10 }; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); hImageViewPic = (ImageView)findViewById(R.id.idImageViewPic); iButton = (Button) findViewById(R.id.bIleri); gButton = (Button) findViewById(R.id.bGeri); //Just set one Click listener for the image iButton.setOnClickListener(iButtonChangeImageListener); gButton.setOnClickListener(gButtonChangeImageListener); } View.OnClickListener iButtonChangeImageListener = new OnClickListener() {public void onClick(View v) { //Increase Counter to move to next Image currentImage++; currentImage = currentImage % images.length; hImageViewPic.setImageResource(images[currentImage]); } }; View.OnClickListener gButtonChangeImageListener = new OnClickListener() { public void onClick(View v) { //Increase Counter to move to next Image currentImage--; currentImage = (currentImage + images.length) % images.length; hImageViewPic.setImageResource(images[currentImage]); } ```
2013/11/19
['https://Stackoverflow.com/questions/20077653', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3004150/']
Read this [tutorial](http://www.androidhive.info/2013/09/android-fullscreen-image-slider-with-swipe-and-pinch-zoom-gestures/). It is an awesome integration of all image view related possibilities.
You can use [this](https://github.com/chrisbanes/PhotoView) library. It is very easy to implement what you want using this.
16,819,394
I'm having the hardest time using the dropdown list side of Krypton Dropbuttons -- specifically, I don't know how to register that I've actually selected something within the dropdown list. In my project, I am using a dropbutton to apply a change over time, where simply clicking is immediate and the drop list has various increments of time -- I am using tweener-dotnet for the value change over time, as my calculus is awful and why reinvent the wheel?. I am able to use the dropbutton as a regular button just fine. In addition to that, I've been able to set my ContextMenu in the dropbutton, so when I build the solution and click on the dropdown arrow, the list shows up. What I can't do, however, is figure out how to tell the code that I've actually selected something within the dropdown list. I've spent a couple hours, collectively, staring at all three iterations of the DropButton examples, and none of them actually show what I'm looking for (seriously, Component Factory?!). **How do I use the dropdown side of the Krypton Dropbutton?** (For open source sake, I may just go back to a regular dropdown list and a regular button, but I really like the simplicity of the Krypton DropButton, and open source isn't really a priority with this project.)
2013/05/29
['https://Stackoverflow.com/questions/16819394', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1672020/']
I know that this is late, but I've been dealing with something similar. For a `KryptonDropButton` you need to create a `KryptonContextMenu`, as @Roberto has stated. Then I went to add a listener to the manu items that I've added to the assigned `KryptonContextMenu` and found out that the designer does not support the `Name` property (or maybe I was too blind to find it). Anyway, I navigated to the designer file I found that those menu items were generated anyway, with default names. Something like this: ![enter image description here](https://i.stack.imgur.com/ZTLIp.png) I then went to rename those and added events like I would normally to respond to user selection, but I won't hide that this is overkill.
**Update 2018:** the toolkit has been opensourced here: <https://github.com/ComponentFactory/Krypton> Component factory hasn't been actively worked on since 2011. ~~Its still closed source so that is an issue.~~ The Krypton Toolkit itself is a bit iffy in .net 4 and above. The KryptonContextMenu that you need with the KryptonDropButton is one of the bits that I've been having difficulty getting to work.
16,819,394
I'm having the hardest time using the dropdown list side of Krypton Dropbuttons -- specifically, I don't know how to register that I've actually selected something within the dropdown list. In my project, I am using a dropbutton to apply a change over time, where simply clicking is immediate and the drop list has various increments of time -- I am using tweener-dotnet for the value change over time, as my calculus is awful and why reinvent the wheel?. I am able to use the dropbutton as a regular button just fine. In addition to that, I've been able to set my ContextMenu in the dropbutton, so when I build the solution and click on the dropdown arrow, the list shows up. What I can't do, however, is figure out how to tell the code that I've actually selected something within the dropdown list. I've spent a couple hours, collectively, staring at all three iterations of the DropButton examples, and none of them actually show what I'm looking for (seriously, Component Factory?!). **How do I use the dropdown side of the Krypton Dropbutton?** (For open source sake, I may just go back to a regular dropdown list and a regular button, but I really like the simplicity of the Krypton DropButton, and open source isn't really a priority with this project.)
2013/05/29
['https://Stackoverflow.com/questions/16819394', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1672020/']
I'm about a year and a half late, but here's a radiobutton click event. Just select the control and event at the top of the IDE. ``` Public Sub KryptonContextMenuRadioButton1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles KryptonContextMenuRadioButton1.Click 'do something End Sub ```
**Update 2018:** the toolkit has been opensourced here: <https://github.com/ComponentFactory/Krypton> Component factory hasn't been actively worked on since 2011. ~~Its still closed source so that is an issue.~~ The Krypton Toolkit itself is a bit iffy in .net 4 and above. The KryptonContextMenu that you need with the KryptonDropButton is one of the bits that I've been having difficulty getting to work.
16,819,394
I'm having the hardest time using the dropdown list side of Krypton Dropbuttons -- specifically, I don't know how to register that I've actually selected something within the dropdown list. In my project, I am using a dropbutton to apply a change over time, where simply clicking is immediate and the drop list has various increments of time -- I am using tweener-dotnet for the value change over time, as my calculus is awful and why reinvent the wheel?. I am able to use the dropbutton as a regular button just fine. In addition to that, I've been able to set my ContextMenu in the dropbutton, so when I build the solution and click on the dropdown arrow, the list shows up. What I can't do, however, is figure out how to tell the code that I've actually selected something within the dropdown list. I've spent a couple hours, collectively, staring at all three iterations of the DropButton examples, and none of them actually show what I'm looking for (seriously, Component Factory?!). **How do I use the dropdown side of the Krypton Dropbutton?** (For open source sake, I may just go back to a regular dropdown list and a regular button, but I really like the simplicity of the Krypton DropButton, and open source isn't really a priority with this project.)
2013/05/29
['https://Stackoverflow.com/questions/16819394', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1672020/']
I know that this is late, but I've been dealing with something similar. For a `KryptonDropButton` you need to create a `KryptonContextMenu`, as @Roberto has stated. Then I went to add a listener to the manu items that I've added to the assigned `KryptonContextMenu` and found out that the designer does not support the `Name` property (or maybe I was too blind to find it). Anyway, I navigated to the designer file I found that those menu items were generated anyway, with default names. Something like this: ![enter image description here](https://i.stack.imgur.com/ZTLIp.png) I then went to rename those and added events like I would normally to respond to user selection, but I won't hide that this is overkill.
I'm about a year and a half late, but here's a radiobutton click event. Just select the control and event at the top of the IDE. ``` Public Sub KryptonContextMenuRadioButton1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles KryptonContextMenuRadioButton1.Click 'do something End Sub ```
11,486,756
I am having issues creating a html table to display stats from a text file. I am sure there are 100 ways to do this better but here it is: **(The comments in the following script show the outputs)** ``` #!/bin/bash function getapistats () { curl -s http://api.example.com/stats > api-stats.txt awk {'print $1'} api-stats.txt > api-stats-int.txt awk {'print $2'} api-stats.txt > api-stats-fqdm.txt } # api-stats.txt example # 992 cdn.example.com # 227 static.foo.com # 225 imgcdn.bar.com # end api-stats.txt example function get_int () { for i in `cat api-stats-int.txt`; do echo -e "<tr><td>${i}</td>"; done } function get_fqdn () { for f in `cat api-stats-fqdn.txt`; do echo -e "<td>${f}</td></tr>"; done } function build_table () { echo "<table>"; echo -e "`get_int`" "`get_fqdn`"; #echo -e "`get_fqdn`"; echo "</table>"; } getapistats; build_table > api-stats.html; # Output fail :| # <table> # <tr><td>992</td> # <tr><td>227</td> # <tr><td>225</td><td>cdn.example.com</td></tr> # <td>static.foo.com</td></tr> # <td>imgcdn.bar.com</td></tr> # Desired output: # <tr><td>992</td><td>cdn.example.com</td></tr> # ... ```
2012/07/14
['https://Stackoverflow.com/questions/11486756', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1258484/']
This is reasonably simple to do in pure awk: ``` curl -s http://api.example.com/stats > api-stats.txt awk 'BEGIN { print "<table>" } { print "<tr><td>" $1 "</td><td>" $2 "</td></tr>" } END { print "</table>" }' api-stats.txt > api-stats.html ``` Awk is really made for this type of use.
this can be done w/ bash ;) ``` while read -u 3 a && read -u 4 b;do echo $a$b; done 3</etc/passwd 4</etc/services ``` but my experience is that usually it's a bad thing to do things like this in bash/awk/etc the feature i used in the code is **deeply** burried in the bash manual page... i would recommend to use some real language for this kind of data processing for example: (ruby or python) because they are more flexible/readable/maintainable
11,486,756
I am having issues creating a html table to display stats from a text file. I am sure there are 100 ways to do this better but here it is: **(The comments in the following script show the outputs)** ``` #!/bin/bash function getapistats () { curl -s http://api.example.com/stats > api-stats.txt awk {'print $1'} api-stats.txt > api-stats-int.txt awk {'print $2'} api-stats.txt > api-stats-fqdm.txt } # api-stats.txt example # 992 cdn.example.com # 227 static.foo.com # 225 imgcdn.bar.com # end api-stats.txt example function get_int () { for i in `cat api-stats-int.txt`; do echo -e "<tr><td>${i}</td>"; done } function get_fqdn () { for f in `cat api-stats-fqdn.txt`; do echo -e "<td>${f}</td></tr>"; done } function build_table () { echo "<table>"; echo -e "`get_int`" "`get_fqdn`"; #echo -e "`get_fqdn`"; echo "</table>"; } getapistats; build_table > api-stats.html; # Output fail :| # <table> # <tr><td>992</td> # <tr><td>227</td> # <tr><td>225</td><td>cdn.example.com</td></tr> # <td>static.foo.com</td></tr> # <td>imgcdn.bar.com</td></tr> # Desired output: # <tr><td>992</td><td>cdn.example.com</td></tr> # ... ```
2012/07/14
['https://Stackoverflow.com/questions/11486756', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1258484/']
You can do it with one awk at least. ``` curl -s http://api.example.com/stats | awk ' BEGIN{print "<table>"} {printf("<tr><td>%d</td><td>%s</td></tr>\n",$1,$2)} END{print "</table>"} ' ```
this can be done w/ bash ;) ``` while read -u 3 a && read -u 4 b;do echo $a$b; done 3</etc/passwd 4</etc/services ``` but my experience is that usually it's a bad thing to do things like this in bash/awk/etc the feature i used in the code is **deeply** burried in the bash manual page... i would recommend to use some real language for this kind of data processing for example: (ruby or python) because they are more flexible/readable/maintainable
11,486,756
I am having issues creating a html table to display stats from a text file. I am sure there are 100 ways to do this better but here it is: **(The comments in the following script show the outputs)** ``` #!/bin/bash function getapistats () { curl -s http://api.example.com/stats > api-stats.txt awk {'print $1'} api-stats.txt > api-stats-int.txt awk {'print $2'} api-stats.txt > api-stats-fqdm.txt } # api-stats.txt example # 992 cdn.example.com # 227 static.foo.com # 225 imgcdn.bar.com # end api-stats.txt example function get_int () { for i in `cat api-stats-int.txt`; do echo -e "<tr><td>${i}</td>"; done } function get_fqdn () { for f in `cat api-stats-fqdn.txt`; do echo -e "<td>${f}</td></tr>"; done } function build_table () { echo "<table>"; echo -e "`get_int`" "`get_fqdn`"; #echo -e "`get_fqdn`"; echo "</table>"; } getapistats; build_table > api-stats.html; # Output fail :| # <table> # <tr><td>992</td> # <tr><td>227</td> # <tr><td>225</td><td>cdn.example.com</td></tr> # <td>static.foo.com</td></tr> # <td>imgcdn.bar.com</td></tr> # Desired output: # <tr><td>992</td><td>cdn.example.com</td></tr> # ... ```
2012/07/14
['https://Stackoverflow.com/questions/11486756', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1258484/']
This is reasonably simple to do in pure awk: ``` curl -s http://api.example.com/stats > api-stats.txt awk 'BEGIN { print "<table>" } { print "<tr><td>" $1 "</td><td>" $2 "</td></tr>" } END { print "</table>" }' api-stats.txt > api-stats.html ``` Awk is really made for this type of use.
You can do it with one awk at least. ``` curl -s http://api.example.com/stats | awk ' BEGIN{print "<table>"} {printf("<tr><td>%d</td><td>%s</td></tr>\n",$1,$2)} END{print "</table>"} ' ```
78,346
just a quick question. Is the tissue fluid the same water potential as the cells it surrounds? I am a bit confused because if it was lower it would cause water to leave the cell and if it was higher water would enter the cell and both aren't really good for the cell. I believe tissue fluid is isotonic, am I correct?
2018/10/20
['https://biology.stackexchange.com/questions/78346', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/46295/']
Yes, cell membranes are highly permeable for water. While diffusion through the membrane is possible ([description](https://socratic.org/questions/how-can-water-pass-through-the-lipid-bilayer), [and some science](https://pubs.acs.org/doi/pdf/10.1021/j100066a040)), it is most effective through water channel proteins ([aquaporins](https://www.anaesthesiamcq.com/FluidBook/fl1_2.php)). The different expression levels of aquaporins in different cell types result in differences in the permeability. And yes, the tissue fluid has to be isotonic to the cell interior. The water balance in the body is therefore highly regulated. If not enough water is available, the blood osmolarity (ratio between solubles and water) increases. This is sensed in the hypothalamus (an area in the brain which is a major player in hormone regulation) and results in production of the hormone vasopressin. This will not only increase your thirst (and therefore add more water to the system) but also regulate aquaporin expression, improving reabsorbtion of water in the kidney ([nicely shown here](https://opentextbc.ca/anatomyandphysiology/chapter/26-2-water-balance/), [actual science here](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4714093/)). Urine production is of course also important in the response to drinking too much, which can be harmful as well.. If tonicity is deregulated, this has serious consequences for the body ([some more science](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4895078/)). For example, mutations in vasopressin or kindney aquaporins can result in very similar phenotypes, characterized by dehydration because water levels cannot be properly regulated ([even more science](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4400507/)). edited for more explanation, because people complain when I give short answers to short questions ;)
Not necessarily- cells are surrounded by a *plasma membrane* that creates a waterproof seal from their surroundings. This membrane contains embedded proteins, called *transporters* and *channels*, that enable the selective passage of water, ions, and solutes to maintain a *membrane potential*, or concentration difference between inside and outside. This enables cells to maintain homeostasis, despite changing external conditions. You can learn more about these processes here: <https://en.wikipedia.org/wiki/Membrane_potential>
190,902
Let's say that a (recursively axiomatizable) set theory $T$ extending ZF is "ordinal-categorical" if, whenever $M$ and $N$ are standard models of $T$ sharing the same ordinals, one has $M = N$. For example, if $T$ proves $V = L$, then $T$ is ordinal-categorical. I think the same is true if $T$ proves $V = L(0^\sharp)$. Is there anything else that can be said about such theories $T$? In particular, is there a way to find an axiom or axiom schema A such that all ordinal-categorical theories $T$ are precisely the (recursively axiomatizable) extensions of ZF+A? If this is not known, is finding such an A a goal of the inner model program? (Note: In the original post I used the word "canonical" instead of "ordinal-categorical.)
2014/12/16
['https://mathoverflow.net/questions/190902', 'https://mathoverflow.net', 'https://mathoverflow.net/users/17218/']
> > In this edit, the statement of Friedman's theorem is reformulated (the previous formulation was incorrectly stated). Thanks to Dmytro Taranovsky and Farmer Schultzenberg for pointing out the blooper. *See also Remark 2 for recent progress (January 2023) on this topic by Schultzenberg and Taranovsky.* > > > An old theorem of Harvey Friedman answers the question: **Theorem.** *Under a mild set theoretical hypothesis* $\mathrm{H}$ (see Note 1 below), *there is a cofinal subset* $U$ *of* $\omega\_1$ (see Note 2 below) *such that if* $T$ *is any r.e. extension of* $\mathrm{ZF + V \neq L}$ *that has a countable transitive model* $M$ *of height* $\alpha$, *then* $T$ *has another model* $N \neq M$ *of height* $\alpha$. **Note 1.** The mild set theoretical hypothesis $\mathrm{H}$ above asserts that there is an ordinal $\alpha$ of uncountable cofinality such that $V\_{\alpha} \models \mathrm{ZF}$. Thus the existence of a strongly inaccessible cardinal implies $\mathrm{H}$. **Note 2.** $U$ consists of $\omega\_1 \cap G$, where $G$ consists of ordinals $\alpha$ such that $L\_{\mathrm{n}(\alpha)} \cap V\_{\alpha}=L\_{\alpha}$. Here $\mathrm{n}(\alpha)$ is Friedman's notation (in the paper below) for the next admissiable ordinal after $\alpha$, i.e., the least admissible ordinal greater than $\alpha$; this ordinal is denoted $\alpha^{+,\mathrm{CK}}$ [in this MO question of Taranovsky](https://mathoverflow.net/questions/438081/minimum-transitive-models-and-v-l). **Note 3.**  The above Theorem follows from putting together the proof of the hard direction of Theorem 6.2 together with the proof of Lemma 6.3.1 of Friedman's paper below: *Countable models of set theories*, In A. R. D. Mathias & H. Rogers (eds.), **Cambridge Summer School in Mathematical Logic**, Lecture Notes in Mathematics vol. 337, Springer-Verlag. pp. 539--573 (1973). Two Remarks are in order. **Remark 1.** It is known that if the theory $\mathrm{ZF + V = L(0 ^{\#}})$ has transitive model of height $\alpha < \omega\_1$, then $\alpha \in U$; coupled with Friedman's above theorem, this implies that $\mathrm{ZF + V = L(0 ^{\#}})$ has more than one transitive model of height $\alpha$. Thus two transitive models of set theory of the same height could both believe that $0 ^{\#}$ exists, and yet they might have distinct $0 ^{\#}$s. Recall that the complexity of $0 ^{\#}$ is $\Delta^1\_3$. **Remark 2.** In the introduction to his aforementioned paper, Friedman posed the hitherto open question of whether the conclusion of the theorem above holds for $\alpha$ = the ordinal height of the Shepherdson-Cohen minimal model of set theory (it is known that $\alpha \notin U$). Schultzenberg's construction to [this MO question of Taranovsky](https://mathoverflow.net/questions/438081/minimum-transitive-models-and-v-l) implicitly yields a negative answer to Friedman's question. See Taranovsky's answer below for a proposed striking generalization of Schultzenberg's construction.
$\newcommand\Ord{\text{Ord}}\newcommand\Z{\mathbb{Z}}\newcommand\Q{\mathbb{Q}}$This is a nice question, and I don't have much to say about it, except that I did want to mention that it is important in your account that you are talking about standard models, which I take to mean well-founded or transitive models. If you dropped that, the phenomenon would disappear, for the following reason. **Theorem.** For any consistent theory $T$ extending ZF, there are two models of $T$ with the same ordinals, such that they are not isomorphic by any isomorphism fixing the ordinals. **Proof.** Let $M$ be any countable computably saturated model of $T$. It follows that the natural numbers of the model $\omega^M$ are nonstandard and have order type $\omega+\Z\cdot\Q$. The ordinals of $M$ have type $\Ord^M$, which is the same as $\omega^M\cdot\Ord^M$, by an internal isomorphism, and this has order type $(\omega+\Z\cdot\Q)\cdot\Ord^M$. It follows that there is an order-automorphism $\pi:\Ord^M\cong\Ord^M$ that shifts the ordinals within the nonstandard parts of these blocks of $\omega^M$ by one (or one can make more complicated automorphisms). That is, we shift all the $\Z$-chains by one. Since $\Ord^M\subset M$, we may extend $\pi$ to an isomorphism $\pi:M\cong N$ to some model $N$, where $M$ and $N$ have exactly the same ordinals, but where many ordinals $\alpha$ that are even in $M$ are odd in $N$ and vice versa (this will be true exactly for the ordinals that are a nonstandard natural number successor of the largest limit ordinal below them). Thus, $M$ and $N$ have exactly the same ordinals, but are not isomorphic by any isomorphism fixing those ordinals. **QED** In particular, if ZFC is consistent, then there can be models of ZFC+V=L that have exactly the same ordinals, but think different things are true of those ordinals.
190,902
Let's say that a (recursively axiomatizable) set theory $T$ extending ZF is "ordinal-categorical" if, whenever $M$ and $N$ are standard models of $T$ sharing the same ordinals, one has $M = N$. For example, if $T$ proves $V = L$, then $T$ is ordinal-categorical. I think the same is true if $T$ proves $V = L(0^\sharp)$. Is there anything else that can be said about such theories $T$? In particular, is there a way to find an axiom or axiom schema A such that all ordinal-categorical theories $T$ are precisely the (recursively axiomatizable) extensions of ZF+A? If this is not known, is finding such an A a goal of the inner model program? (Note: In the original post I used the word "canonical" instead of "ordinal-categorical.)
2014/12/16
['https://mathoverflow.net/questions/190902', 'https://mathoverflow.net', 'https://mathoverflow.net/users/17218/']
> > In this edit, the statement of Friedman's theorem is reformulated (the previous formulation was incorrectly stated). Thanks to Dmytro Taranovsky and Farmer Schultzenberg for pointing out the blooper. *See also Remark 2 for recent progress (January 2023) on this topic by Schultzenberg and Taranovsky.* > > > An old theorem of Harvey Friedman answers the question: **Theorem.** *Under a mild set theoretical hypothesis* $\mathrm{H}$ (see Note 1 below), *there is a cofinal subset* $U$ *of* $\omega\_1$ (see Note 2 below) *such that if* $T$ *is any r.e. extension of* $\mathrm{ZF + V \neq L}$ *that has a countable transitive model* $M$ *of height* $\alpha$, *then* $T$ *has another model* $N \neq M$ *of height* $\alpha$. **Note 1.** The mild set theoretical hypothesis $\mathrm{H}$ above asserts that there is an ordinal $\alpha$ of uncountable cofinality such that $V\_{\alpha} \models \mathrm{ZF}$. Thus the existence of a strongly inaccessible cardinal implies $\mathrm{H}$. **Note 2.** $U$ consists of $\omega\_1 \cap G$, where $G$ consists of ordinals $\alpha$ such that $L\_{\mathrm{n}(\alpha)} \cap V\_{\alpha}=L\_{\alpha}$. Here $\mathrm{n}(\alpha)$ is Friedman's notation (in the paper below) for the next admissiable ordinal after $\alpha$, i.e., the least admissible ordinal greater than $\alpha$; this ordinal is denoted $\alpha^{+,\mathrm{CK}}$ [in this MO question of Taranovsky](https://mathoverflow.net/questions/438081/minimum-transitive-models-and-v-l). **Note 3.**  The above Theorem follows from putting together the proof of the hard direction of Theorem 6.2 together with the proof of Lemma 6.3.1 of Friedman's paper below: *Countable models of set theories*, In A. R. D. Mathias & H. Rogers (eds.), **Cambridge Summer School in Mathematical Logic**, Lecture Notes in Mathematics vol. 337, Springer-Verlag. pp. 539--573 (1973). Two Remarks are in order. **Remark 1.** It is known that if the theory $\mathrm{ZF + V = L(0 ^{\#}})$ has transitive model of height $\alpha < \omega\_1$, then $\alpha \in U$; coupled with Friedman's above theorem, this implies that $\mathrm{ZF + V = L(0 ^{\#}})$ has more than one transitive model of height $\alpha$. Thus two transitive models of set theory of the same height could both believe that $0 ^{\#}$ exists, and yet they might have distinct $0 ^{\#}$s. Recall that the complexity of $0 ^{\#}$ is $\Delta^1\_3$. **Remark 2.** In the introduction to his aforementioned paper, Friedman posed the hitherto open question of whether the conclusion of the theorem above holds for $\alpha$ = the ordinal height of the Shepherdson-Cohen minimal model of set theory (it is known that $\alpha \notin U$). Schultzenberg's construction to [this MO question of Taranovsky](https://mathoverflow.net/questions/438081/minimum-transitive-models-and-v-l) implicitly yields a negative answer to Friedman's question. See Taranovsky's answer below for a proposed striking generalization of Schultzenberg's construction.
For every c.e theory $T$ extending KP (Kripke-Platek) with a model $M$ of height $α<ω\_1$, the intersection of all such $M$ is a subset of $L\_{α^{+,\mathrm{CK}}}$. This holds since the existence of such $M$ is $Σ^1\_1(α)$. Every model $\text{ZF}+0^\#$ (or just $\text{KP}+0^\#$) of height $α$ includes a set outside of $L\_{α^{+,\mathrm{CK}}}$, so such theories do not have unique models for countable $α$. The interplay of uniqueness and non-uniqueness — and the conditions to guarantee uniqueness — is an important theme in inner model theory. Theories such as $\text{ACA}\_0$ or the primitive recursive set theory have unique minimal $ω$-models, but then for c.e. theories extending $\text{ATR}\_0$, the intersection of all $ω$-models (if there are any) equals HYP. (HYP is the set of hyperarithmetic sets; it corresponds to $L\_{ω\_1^{\mathrm{CK}}}$, the minimal transitive model of KPω.) With $0^\#$, uniqueness of minimal transitive models fails. And going further, $L[M\_1^\#]$ does not satisfy $V=HOD$: Despite being an inner model, $L[M\_1^\#]$ lacks sufficient closure to iterate and identify the true $M\_1^\#$ (the sharp for a Woodin cardinal). Back to the question, for every ordinal-categorical (as defined in the question) c.e. theory $T$, all transitive models are constructible, and for a model $M⊨T$ of possibly uncountable height $α$, $M⊂L\_{α^{+,\mathrm{CK}}}$ (uncountable $α$ can handled using countable elementary submodels). Thus, if $On^M$ is a cardinal (and $T⊢\text{KP}$), then $M ⊨ V=L$. Surprisingly, however, we have the following, which adapts Farmer Schlutzenberg's answer to my recent question [Minimum transitive models and V=L](https://mathoverflow.net/questions/438081/minimum-transitive-models-and-v-l?noredirect=1&lq=1) (the discussions in the two questions complement each other). **Theorem:** There are ordinal-categorical c.e. theories extending $\text{ZFC} + V≠L$ that have arbitrarily large transitive models (assuming ZFC has arbitrarily large transitive models). **Proof:** To get such models, we use existence of (non-trivial) $≤κ$-closed forcings with (as viewed from the generic extension) unique generics. Ordinarily, we might have $V[G]=V[G']$ (which interferes with defining our $G$ in $V[G]$), but we can get unique generics by encoding $G$ into choices for subsequent rounds of forcing and iterating $ω$ times (with full support). Next, for every ordinal $κ$ (including uncountable $κ$), the minimum transitive model $M$ of ZFC of height $>κ$ is pointwise definable with ordinals $<κ$ as constants. Fix a formula picking a $κ$ (as above) in $M$, and a parameter-free definable forcing as above. Using the pointwise definability of $M$ (with ordinals $<κ$ as constants) and the $≤κ$-closure, every dense open set has a parameter-free definable (in $M$) dense open subset. Thus, we can fix a choice of the generic $G$ using a computable schema as in the linked answer. Specifically, enumerate formulas; if a formula $φ\_0$ defines a dense open set here, then pick its first element (under some fixed parameter-free definable well-ordering), and then repeat with $φ\_1, φ\_2, ...$, picking the first element compatible with the previous ones. Our theory will be $\text{ZFC} + V=M[G]$ with $M$ and $G$ as above. A remaining open question is whether there is an ordinal-categorical theory $\text{ZFC} + A + V≠L$ (with a transitive model) where $A$ is a single statement. A model of such a theory cannot be obtained by set forcing (unlike a schema, a statement in the generic extension would be forced by some condition in the poset), and so may require new (perhaps, still forcing-like) construction methods.
33,750,465
I'm working on an app's user interface, and I'm doing it programmatically. I understand the idea behind retain cycles, and feel quite confident I could identify one, but Xcode is giving me warnings when I'm trying to avoid a retain cycle. Essentially, I'm creating a property called `titleLabel` which will have my title, and in `viewDidLoad` I'm initializing it, and placing it on my view. The only problem is, I'm getting an Xcode warning that says: > > Assigning retained object to weak variable; object will be released after assignment > > > My property definition is as follows: ``` @property (nonatomic, weak) UILabel *titleLabel; ``` Obviously I could fix the Xcode warning by changing `weak` to `strong` in my property definition, but I believe that would create a retain cycle (from my understanding) because the button is holding onto the View Controller and the View Controller is holding onto the button. Can anyone give me some insight as to how to do this properly?
2015/11/17
['https://Stackoverflow.com/questions/33750465', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3411191/']
Your understanding is flawed. If the label were to retain a reference to its view controller, you would have a retain cycle if the property were defined as `strong`. However, views do not retain references to their view controllers, so there is no cycle. Xcode is warning you correctly that your label reference will go away after the assignment. You aren't even saved by adding it as a subview (which would retain it), because it's already released by the time you try. The one quasi-exception to views not retaining references to controllers is with table and collection views, which have delegates and datasources which are usually their managing view controller. However, those delegate/datasource properties are defined as `assign` properties (which has another set of problems) so there is no retain cycle there, either.
i think you can set property to strong which will retain its memory and when your view will disappear call then you can set this object to nil which will release its memory.
33,750,465
I'm working on an app's user interface, and I'm doing it programmatically. I understand the idea behind retain cycles, and feel quite confident I could identify one, but Xcode is giving me warnings when I'm trying to avoid a retain cycle. Essentially, I'm creating a property called `titleLabel` which will have my title, and in `viewDidLoad` I'm initializing it, and placing it on my view. The only problem is, I'm getting an Xcode warning that says: > > Assigning retained object to weak variable; object will be released after assignment > > > My property definition is as follows: ``` @property (nonatomic, weak) UILabel *titleLabel; ``` Obviously I could fix the Xcode warning by changing `weak` to `strong` in my property definition, but I believe that would create a retain cycle (from my understanding) because the button is holding onto the View Controller and the View Controller is holding onto the button. Can anyone give me some insight as to how to do this properly?
2015/11/17
['https://Stackoverflow.com/questions/33750465', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3411191/']
Your understanding is flawed. If the label were to retain a reference to its view controller, you would have a retain cycle if the property were defined as `strong`. However, views do not retain references to their view controllers, so there is no cycle. Xcode is warning you correctly that your label reference will go away after the assignment. You aren't even saved by adding it as a subview (which would retain it), because it's already released by the time you try. The one quasi-exception to views not retaining references to controllers is with table and collection views, which have delegates and datasources which are usually their managing view controller. However, those delegate/datasource properties are defined as `assign` properties (which has another set of problems) so there is no retain cycle there, either.
When you create a UI element and add it as a subview to parent view. The Parent view keeps a strong reference to sub View. In your case, you could just create a UILabel variable within your function and add it to the parent. You could then declare a weak property that keeps a reference to this newly created label. This way, the parent view "owns" the label, and it takes care of cleaning up the label when the parent view goes off screen. ``` @interface MasterViewController () @property (nonatomic,weak) UILabel * theLabel; @end @implementation MasterViewController - (void)viewDidLoad { [super viewDidLoad]; UILabel* myLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; [self.view addSubview:myLabel]; self.theLabel = myLabel; } ```
51,943,181
Hey guys so i got this dummy data: ``` 115,IROM,1 125,FOLCOM,1 135,SE,1 111,ATLUZ,1 121,ATLUZ,2 121,ATLUZ,2 142,ATLUZ,2 142,ATLUZ,2 144,BLIZZARC,1 166,STEAD,3 166,STEAD,3 166,STEAD,3 168,BANDOI,1 179,FOX,1 199,C4,2 199,C4,2 ``` Desired output: ``` IROM,1 FOLCOM,1 SE,1 ATLUZ,3 BLIZZARC,1 STEAD,1 BANDOI,1 FOX,1 C4,1 ``` which comes from counting the distinct game id (the 115,125,etc). so for example the ``` 111,ATLUZ,1 121,ATLUZ,2 121,ATLUZ,2 142,ATLUZ,2 142,ATLUZ,2 ``` Will be ``` ATLUZ,3 ``` Since it have 3 distinct game id I tried using ``` cut -d',' -f 2 game.csv|uniq -c ``` Where i got the following output ``` 1 IROM 1 FOLCOM 1 SE 5 ATLUZ 1 BLIZZARC COMP 3 STEAD 1 BANDOI 1 FOX 2 C4 ``` How do i fix this ? using bash ?
2018/08/21
['https://Stackoverflow.com/questions/51943181', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3646742/']
Before executing the `cut` command, do a `uniq`. This will remove the redundant lines and then you follow your command, i.e. apply `cut` to extract `2` field and do `uniq -c` to count character ``` uniq game.csv | cut -d',' -f 2 | uniq -c ```
Could you please try following too in a single `awk`. ``` awk -F, ' !a[$1,$2,$3]++{ b[$1,$2,$3]++ } !f[$2]++{ g[++count]=$2 } END{ for(i in b){ split(i,array,",") c[array[2]]++ } for(q=1;q<=count;q++){ print c[g[q]],g[q] } }' SUBSEP="," Input_file ``` It will give the order of output same as Input\_file's 2nd field occurrence as follows. ``` 1 IROM 1 FOLCOM 1 SE 3 ATLUZ 1 BLIZZARC 1 STEAD 1 BANDOI 1 FOX 1 C4 ```
51,943,181
Hey guys so i got this dummy data: ``` 115,IROM,1 125,FOLCOM,1 135,SE,1 111,ATLUZ,1 121,ATLUZ,2 121,ATLUZ,2 142,ATLUZ,2 142,ATLUZ,2 144,BLIZZARC,1 166,STEAD,3 166,STEAD,3 166,STEAD,3 168,BANDOI,1 179,FOX,1 199,C4,2 199,C4,2 ``` Desired output: ``` IROM,1 FOLCOM,1 SE,1 ATLUZ,3 BLIZZARC,1 STEAD,1 BANDOI,1 FOX,1 C4,1 ``` which comes from counting the distinct game id (the 115,125,etc). so for example the ``` 111,ATLUZ,1 121,ATLUZ,2 121,ATLUZ,2 142,ATLUZ,2 142,ATLUZ,2 ``` Will be ``` ATLUZ,3 ``` Since it have 3 distinct game id I tried using ``` cut -d',' -f 2 game.csv|uniq -c ``` Where i got the following output ``` 1 IROM 1 FOLCOM 1 SE 5 ATLUZ 1 BLIZZARC COMP 3 STEAD 1 BANDOI 1 FOX 2 C4 ``` How do i fix this ? using bash ?
2018/08/21
['https://Stackoverflow.com/questions/51943181', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3646742/']
Before executing the `cut` command, do a `uniq`. This will remove the redundant lines and then you follow your command, i.e. apply `cut` to extract `2` field and do `uniq -c` to count character ``` uniq game.csv | cut -d',' -f 2 | uniq -c ```
Less elegant, but you may use awk as well. If it is not granted that the same ID+NAME combos will always come consecutively, you have to count each by reading the whole file before output: ``` awk -F, '{c[$1,$2]+=1}END{for (ck in c){split(ck,ca,SUBSEP); print ca[2];g[ca[2]]+=1}for(gk in g){print gk,g[gk]}}' game.csv ``` This will count first every [COL1,COL2] pairs then for each COL2 it counts how many distinct [COL1,COL2] pairs are nonzero.