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
|
---|---|---|---|---|---|
39,099,218 | [](https://i.stack.imgur.com/PKlCN.png)I am using yii2 framework since last few weeks. But now I am getting some issues with composer itself.
Just for info, I am using ubuntu 14.04
When I require some new package / extensions, I do the composer add by using composer require command. But I noticed that sometimes it's removing few of the existing packages from my vendor and project.
I tried with following commands.
```
composer require dmstr/yii2-adminlte-asset "*"
composer require 2amigos/yii2-file-upload-widget:~1.0
```
And also tried with some googling.
<http://www.yiiframework.com/wiki/672/install-specific-yii2-vendor-extension-dependency-without-updating-other-packages/>
But it's not working.
Is there a way to add a new package / extension into your existing yii 2 project without removing existing packages or without any composer update command?
**Composer.json**
```
{
"name": "sganz/yii2-advanced-api-template",
"description": "Improved Yii 2 Advanced Application Template By Sandy Ganz, Original by Nenad Zivkovic",
"keywords": ["yii2", "framework", "advanced", "improved", "application template", "nenad", "sganz"],
"type": "project",
"license": "BSD-3-Clause",
"support": {
"tutorial": "http://www.freetuts.org/tutorial/view?id=6",
"source": "https://github.com/sganz/yii2-advanced-api-template.git"
},
"minimum-stability": "dev",
"prefer-stable":true,
"require": {
"php": ">=5.4.0",
"yiisoft/yii2": "*",
"yiisoft/yii2-bootstrap": "*",
"yiisoft/yii2-swiftmailer": "*",
"nenad/yii2-password-strength": "*",
"mihaildev/yii2-ckeditor": "*",
"dmstr/yii2-adminlte-asset": "*"
},
"require-dev": {
"yiisoft/yii2-codeception": "*",
"yiisoft/yii2-debug": "*",
"yiisoft/yii2-gii": "*",
"yiisoft/yii2-faker": "*",
"codeception/specify": "*",
"codeception/verify": "*"
},
"config": {
"vendor-dir": "protected/vendor",
"process-timeout": 1800
},
"extra": {
"asset-installer-paths": {
"npm-asset-library": "protected/vendor/npm",
"bower-asset-library": "protected/vendor/bower"
}
}
}
```
Any help on this would be greatly appreciated. | 2016/08/23 | ['https://Stackoverflow.com/questions/39099218', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6608101/'] | I had this problem few days ago to install a package but when I installed the package all the project updated and my project became broken.So I replace my last vendor again,So I found a safe way for better and safer upgrading packages:
1. archiving your vendor to a zip or rar file and copy composer.json too.
2. add package to composer or install with composer require.
3. dont clear command line screen and copy its screen into a txt file to find versions
4. find your vital and main packages like yiisoft/yii2 and .... and copy their versions.
for doing this open txt file and search in upgrade lines and find something like below:
`- Upgrading yiisoft/yii2 (2.0.39.3 => 2.0.41.1): Extracting archive` means that your current version is 2.0.39.3,so copy this version on composer.json like below:*(without ~ and ^)*
`"yiisoft/yii2": "2.0.39",`
5. remove project vendor folder and extract backup vendor and finally run
`composer install` or `composer update`.
***note:*** dont remove vendor and composer.json backup till your project will works correctly then you can remove them.
\**this is a manually way for upgrading vendors for don't upgrade in vital framework updates temporary like for my project update that yii released Yii2.0.41.*
**a very important note is from yii upgrade notes from [here](https://github.com/yiisoft/yii2/blob/2.0.41/framework/UPGRADE.md) that:**
>
> Note: This document assumes you have composer installed globally so that you can run the composer command. If you have a composer.phar file inside of your project you need to replace composer with php composer.phar in the following.
>
>
> Tip: Upgrading dependencies of a complex software project always comes at the risk of breaking something, so make sure you have a backup (you should be doing this anyway ;) ).
>
>
>
so running `composer update` command directly could break part of your application like me that my admin pannel was broken.
good luck ;) | To avoid uninstallation of other extensions just do following steps.
```
1) "dmstr/yii2-adminlte-asset" : "2.*"
2) "2amigos/yii2-file-upload-widget": "~1.0"
```
to the require section of your composer.json file.
```
2) php composer.phar update
```
run this command in Cmd. |
65,466,881 | I need to recreate the `printf` function for a school project. My current function works flawlessly, except if there are two arguments.
If I do the following: `ft_printf("%c%c", 'a', 'b');`
it will print `aa`, instead of `ab`.
If I do the following: `ft_printf("%c%d", 't', 29);`
it will not print `t29` like it's supposed to.
Instead, it will print `t116` as it does detect that I would like to print an int, but doesn't use the right argument (it converts "t" in its ascii value (116)).
I have included below the code of my main `printf`function, the ft\_analysis function (to find the flags), the ft\_utilities\_one function (which has some basic functions like putchar() for example) as well as the parsing function I'm using to parse the string given as primary argument. Due to how many code there is, I have only included the `char` printing function (ft\_c\_craft) as an example. If you need more clarity regarding how these functions are used, you can find [here my printf repository](https://github.com/maxdesalle/42/tree/main/ft_printf).
ft\_printf.c
```
int ft_printf(const char *str, ...)
{
t_list box;
va_list argptr;
va_start(argptr, str);
ft_parser(argptr, (char *)str, &box);
va_end(argptr);
return (box.len);
}
```
ft\_parser.c
```
static void ft_craft1(va_list argptr, t_list *box)
{
if (box->type == 'c')
ft_c_craft(va_arg(argptr, int), box);
else if (box->type == 's')
ft_s_craft(va_arg(argptr, char *), box);
else if (box->type == 'd' || box->type == 'i')
ft_di_craft(va_arg(argptr, int), box);
}
static void ft_craft2(va_list argptr, t_list *box)
{
if (box->type == 'u')
ft_u_craft(va_arg(argptr, unsigned int), box);
else if (box->type == 'x')
ft_xx_craft(va_arg(argptr, int), 0, box);
else if (box->type == 'X')
ft_xx_craft(va_arg(argptr, int), 1, box);
else if (box->type == 'p')
ft_p_craft(va_arg(argptr, unsigned long long), box);
}
static void ft_type_selector(va_list argptr, t_list *box)
{
if (box->type == 'c' || box->type == 's' || box->type == 'd'
|| box->type == 'i')
ft_craft1(argptr, box);
else
ft_craft2(argptr, box);
}
void ft_parser(va_list argptr, char *str, t_list *box)
{
int i;
i = 0;
while (str[i] != '\0')
{
if (str[i] == '%' && str[i + 1] != '%')
{
ft_analysis(&str[++i], box);
while (ft_strchr("cspdiuxX", str[i]) == NULL)
i++;
if (ft_strchr("cspdiuxX", str[i]))
box->type = str[i];
ft_type_selector(argptr, box);
}
else if (str[i] == '%' && str[i + 1] == '%')
ft_putchar(str[++i], box);
else
ft_putchar(str[i], box);
i++;
}
}
```
ft\_analysis.c
```
static void ft_precision(char *str, t_list *box)
{
box->precision = 0;
while (*str != '\0')
{
if (*str == '.')
{
box->precision = ft_atoi_alpha(++str);
return ;
}
str++;
}
return ;
}
static void ft_width(char *str, t_list *box)
{
box->width = 0;
while (*str != '\0' && *str != '.')
{
if (*str >= '0' && *str <= '9')
{
box->width = ft_atoi_alpha(str);
return ;
}
str++;
}
return ;
}
static void ft_flag(char *str, t_list *box)
{
box->fzero = 0;
box->fplus = 0;
box->fminus = 0;
box->fspace = 0;
while (*str != '\0' && (!(*str >= '1' && *str <= '9')))
if (*str++ == '0')
box->fzero += 1;
else if (ft_strchr(str, '+'))
box->fplus += 1;
else if (ft_strchr(str, '-'))
box->fminus += 1;
else if (ft_strchr(str, ' '))
box->fspace += 1;
return ;
}
void ft_analysis(char *str, t_list *box)
{
ft_precision(str, box);
ft_width(str, box);
ft_flag(str, box);
}
```
ft\_c\_craft.c
```
static void ft_print_char(char c, t_list *box)
{
if (box->fminus == 1)
{
ft_putchar(c, box);
ft_super_putchar(box->width - 1, ' ', box);
return ;
}
else if (box->fzero == 1)
ft_super_putchar(box->width - 1, '0', box);
else if (box->fminus == 0)
ft_super_putchar(box->width - 1, ' ', box);
ft_putchar(c, box);
return ;
}
void ft_c_craft(char c, t_list *box)
{
if (box->width > 1)
ft_print_char(c, box);
else
ft_putchar(c, box);
}
```
ft\_utilities\_one.c
```
void ft_putchar(char c, t_list *box)
{
write(1, &c, 1);
box->len += 1;
}
void ft_putstr(char *str, t_list *box)
{
while (*str != '\0')
{
write(1, str++, 1);
box->len += 1;
}
}
void ft_putstr_precision(char *str, t_list *box)
{
int i;
i = box->precision;
while (*str != '\0' && i-- > 0)
{
write(1, str++, 1);
box->len += 1;
}
}
void ft_super_putchar(int len, char c, t_list *box)
{
while (len-- > 0)
{
write(1, &c, 1);
box->len += 1;
}
}
long ft_atoi_alpha(const char *nptr)
{
long result;
result = 0;
while (*nptr && ((*nptr >= 9 && *nptr <= 13) || *nptr == ' '))
nptr++;
if (*nptr == '-' || *nptr == '+')
nptr++;
while (*nptr && *nptr >= '0' && *nptr <= '9')
result = result * 10 + (*nptr++ - '0');
return (result);
}
``` | 2020/12/27 | ['https://Stackoverflow.com/questions/65466881', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14608442/'] | >
> If I do the following: `ft_printf("%c%c", 'a', 'b');`
>
>
> it will print aa, instead of ab.
>
>
> If I do the following: `ft_printf("%c%d", 't', 29);`
>
>
> it will not print t29 like it's supposed to. Instead, it will print t116 as it does detect that I would like to print an int, but doesn't use the right argument (it converts "t" in its ascii value (116)).
>
>
>
visibly you do not progress and always use the first argument, this is because you give the *va\_list* by value, so you use a copy of it and you cannot progress in the list of argument. Just give it by pointer
in *ft\_printf*
```
ft_parser(&argptr, (char *)str, &box);
```
and :
```
static void ft_craft1(va_list *argptr, t_list *box)
{
if (box->type == 'c')
ft_c_craft(va_arg(*argptr, int), box);
else if (box->type == 's')
ft_s_craft(va_arg(*argptr, char *), box);
else if (box->type == 'd' || box->type == 'i')
ft_di_craft(va_arg(*argptr, int), box);
}
```
etc | Use `switch() case` as in this simple example
```
int ts_formatstring(char *buf, const char *fmt, va_list va)
{
char *start_buf = buf;
while(*fmt)
{
/* Character needs formating? */
if (*fmt == '%')
{
switch (*(++fmt))
{
case 'c':
*buf++ = va_arg(va, int);
break;
case 'd':
case 'i':
{
signed int val = va_arg(va, signed int);
if (val < 0)
{
val *= -1;
*buf++ = '-';
}
ts_itoa(&buf, val, 10);
}
break;
case 's':
{
char * arg = va_arg(va, char *);
while (*arg)
{
*buf++ = *arg++;
}
}
break;
case 'u':
ts_itoa(&buf, va_arg(va, unsigned int), 10);
break;
case 'x':
case 'X':
ts_itoa(&buf, va_arg(va, int), 16);
break;
case '%':
*buf++ = '%';
break;
}
fmt++;
}
/* Else just copy */
else
{
*buf++ = *fmt++;
}
}
*buf = 0;
return (int)(buf - start_buf);
}
```
PS not mycode it is from atollic - used for example purposes. Sme potential UBs. |
12,795 | Related: [Finding Great Books at the Right Level](https://parenting.stackexchange.com/questions/6478/finding-great-books-at-the-right-level)
Of course various books have generic maturity levels. But all children are different, and so are all books; so general guidelines aren't always useful - I frequently encounter content that children theoretically aren't ready for yet, but greatly enjoy.
**What are good guidelines to evaluate if your child is ready for a specific book's content?**
---
NOTE: I don't care about the factor of being able to read the text - first, my kids reading level is well above their age, second I can read to them if the book is worth it but they struggle with more advanced text.
I already saw [this question](https://parenting.stackexchange.com/questions/11350/how-does-one-go-about-determining-if-a-child-adolescent-or-teen-is-capable-of-u?rq=1) which seems like a duplicate, but whose answer addresses the opposite problem - is the child ready for the reading level of the book, as opposed to the content; AND doesn't really deal with specific child's capabilities. What I'm looking for is a process I can use to evaluate a specific book in terms of "is it too early to give to this specific child", not "is there a generic guideline that an average 3rd grader would understand 80% of the book". | 2014/05/31 | ['https://parenting.stackexchange.com/questions/12795', 'https://parenting.stackexchange.com', 'https://parenting.stackexchange.com/users/604/'] | Check out your library!
* Libraries have librarians who are trained to help with reader's advisory. In a big enough library, you will find the librarians read a lot of kids' books - the will ask your child questions about what they have liked in the past and what their interests are, and they will give customized recommendations. (They do this for adults too!)
* Libraries also supply access to specialized databases like NoveList, where you can select all sorts of parameters in order to get reading suggestions.
* Library catalogs often have reviews within their catalog which have been done by professional review sources (School Library Journal, Booklist, Kirkus, etc.) to help you with your selections.
* The librarian will happily teach you how to use NoveList or the catalog or whatever other resources they have.
* Books from the library are free. You can take a whole stack home, and after reading a few pages, if the book is not something your child is interested, he can set it aside and pick a different one from the pile. If he finds a series or author he likes, he can bring home a bunch at once! | I think the Commonsense Media site that @ThomasTaylor mentioned is suitable for getting a general opinion based on an **average** child, but in reality your best bet is going to just be to try them.
Libraries and bookstores usually group them by age range, so choose the first book from a series in the general age range that matches your child.
* If a child likes a particular book, try them with the rest of the series.
* If they find it too difficult, try a slightly simpler read.
* If it doesn't challenge them enough, try books from the next stage up.
Sometimes books work on different levels at different ages, so they may be readable twice. For example, Watership Down may be a hit with really young kids as it has rabbits, as they get older it may be terrifying, and then older still it may be a very sad political allegory.
Just get them reading - whatever the book, it is likely to be far better for them than television (according to any number of studies I haven't personally checked, but sound convincing) |
12,795 | Related: [Finding Great Books at the Right Level](https://parenting.stackexchange.com/questions/6478/finding-great-books-at-the-right-level)
Of course various books have generic maturity levels. But all children are different, and so are all books; so general guidelines aren't always useful - I frequently encounter content that children theoretically aren't ready for yet, but greatly enjoy.
**What are good guidelines to evaluate if your child is ready for a specific book's content?**
---
NOTE: I don't care about the factor of being able to read the text - first, my kids reading level is well above their age, second I can read to them if the book is worth it but they struggle with more advanced text.
I already saw [this question](https://parenting.stackexchange.com/questions/11350/how-does-one-go-about-determining-if-a-child-adolescent-or-teen-is-capable-of-u?rq=1) which seems like a duplicate, but whose answer addresses the opposite problem - is the child ready for the reading level of the book, as opposed to the content; AND doesn't really deal with specific child's capabilities. What I'm looking for is a process I can use to evaluate a specific book in terms of "is it too early to give to this specific child", not "is there a generic guideline that an average 3rd grader would understand 80% of the book". | 2014/05/31 | ['https://parenting.stackexchange.com/questions/12795', 'https://parenting.stackexchange.com', 'https://parenting.stackexchange.com/users/604/'] | Check out your library!
* Libraries have librarians who are trained to help with reader's advisory. In a big enough library, you will find the librarians read a lot of kids' books - the will ask your child questions about what they have liked in the past and what their interests are, and they will give customized recommendations. (They do this for adults too!)
* Libraries also supply access to specialized databases like NoveList, where you can select all sorts of parameters in order to get reading suggestions.
* Library catalogs often have reviews within their catalog which have been done by professional review sources (School Library Journal, Booklist, Kirkus, etc.) to help you with your selections.
* The librarian will happily teach you how to use NoveList or the catalog or whatever other resources they have.
* Books from the library are free. You can take a whole stack home, and after reading a few pages, if the book is not something your child is interested, he can set it aside and pick a different one from the pile. If he finds a series or author he likes, he can bring home a bunch at once! | I am inclined to say the biggest factor for determining if a child is ready for a certain book is their interest level. There is little harm in allowing them to *try* the first couple of pages of a book. If the content interests them they may wish to continue with the story. If they are disinterested, they'll know it and you'll know it.
As you implied, having the ability to *read* the words written on the page is one thing, but having the ability to comprehend and enjoy what is written is completely different. I think you will have to do usability tests on individual books, especially since interests in one genre could vary widely. You will need to get a feel for the patterns of what your child reads and finds interesting.
I am also inclined to say that a good tool for determining this is communication. Ask your child up front what they are interested in. From your consistent querying of what their interests are, you will begin to pick up on the type of content they favor. |
12,795 | Related: [Finding Great Books at the Right Level](https://parenting.stackexchange.com/questions/6478/finding-great-books-at-the-right-level)
Of course various books have generic maturity levels. But all children are different, and so are all books; so general guidelines aren't always useful - I frequently encounter content that children theoretically aren't ready for yet, but greatly enjoy.
**What are good guidelines to evaluate if your child is ready for a specific book's content?**
---
NOTE: I don't care about the factor of being able to read the text - first, my kids reading level is well above their age, second I can read to them if the book is worth it but they struggle with more advanced text.
I already saw [this question](https://parenting.stackexchange.com/questions/11350/how-does-one-go-about-determining-if-a-child-adolescent-or-teen-is-capable-of-u?rq=1) which seems like a duplicate, but whose answer addresses the opposite problem - is the child ready for the reading level of the book, as opposed to the content; AND doesn't really deal with specific child's capabilities. What I'm looking for is a process I can use to evaluate a specific book in terms of "is it too early to give to this specific child", not "is there a generic guideline that an average 3rd grader would understand 80% of the book". | 2014/05/31 | ['https://parenting.stackexchange.com/questions/12795', 'https://parenting.stackexchange.com', 'https://parenting.stackexchange.com/users/604/'] | Check out your library!
* Libraries have librarians who are trained to help with reader's advisory. In a big enough library, you will find the librarians read a lot of kids' books - the will ask your child questions about what they have liked in the past and what their interests are, and they will give customized recommendations. (They do this for adults too!)
* Libraries also supply access to specialized databases like NoveList, where you can select all sorts of parameters in order to get reading suggestions.
* Library catalogs often have reviews within their catalog which have been done by professional review sources (School Library Journal, Booklist, Kirkus, etc.) to help you with your selections.
* The librarian will happily teach you how to use NoveList or the catalog or whatever other resources they have.
* Books from the library are free. You can take a whole stack home, and after reading a few pages, if the book is not something your child is interested, he can set it aside and pick a different one from the pile. If he finds a series or author he likes, he can bring home a bunch at once! | I sometimes put aside books which I didn't think my children should have read (like a cute "middle age" where-is-charlie-kind of book, with explicit torture tools... for preschooler age O\_o). And then found out that anyway they would have not been shocked by the content. Children adapt themselves, if something is out of their grasp then they are going to fill in the blanks with some OK imaginative explanations. To be shocked by middle age torture tools, they would have to understand what's wrong about torture, and children don't go around with right and wrong ideas. I guess that's my opinion for young children's books, but I am not sure how old the children you are talking about are. |
44,812,906 | The general problem
===================
I am trying to understand how to prevent the existence of some pattern before or after a sought-out pattern when writing regex's!
A more specific example
=======================
I'm looking for a regex that will match dates in the format YYMMDD (`(([0-9]{2})(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1]))`) inside a long string while ignoring longer numeric sequences
it should be able to match:
* text151124moretext
* 123text151124moretext
* text151124
* text151124moretext1944
* 151124
but should **ignore**:
* text15112412moretext
(reason: it has 8 numbers instead of 6)
* 151324
(reason: it is not a valid date YYMMDD - there is no 13th month)
how can I make sure that if a number has **more** than these 6 digits, it won't picked up as a date inside one single regex (meaning, that I would rather avoid preprocessing the string)
I've thought of `\D((19|20)([0-9]{2})(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1]))\D` but doesn't this mean that there **has to be** some character before and after?
I'm using bash 3.2 (ERE)
thanks! | 2017/06/28 | ['https://Stackoverflow.com/questions/44812906', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3017323/'] | Try:
```
#!/usr/bin/env bash
extract_date() {
local string="$1"
local _date=`echo "$string" | sed -E 's/.*[^0-9]([0-9]{6})[^0-9].*/\1/'`
#date -d $_date &> /dev/null # for Linux
date -jf '%y%m%d' $_date &> /dev/null # for MacOS
if [ $? -eq 0 ]; then
echo $_date
else
return 1
fi
}
extract_date text15111224moretext # ignore n_digits > 6
extract_date text151125moretext # take
extract_date text151132 # # ignore day 32
extract_date text151324moretext1944 # ignore month 13
extract_date text150931moretext1944 # ignore 31 Sept
extract_date 151126 # take
```
Output:
```
151125
151126
``` | If your tokens are line-separated (i.e. there is only one token per line):
```
^[\D]*[\d]{6}([\D]*|[\D]+[\d]{1,6})$
```
Basically, this regex looks for:
* Any number of non-digits at the beginning of the string;
* Exactly 6 digits
* Any number of non-digits until the end OR at least one non-digit and at least one digit (up to 6) to the end of the string
This regex passes all of your given sample inputs. |
44,812,906 | The general problem
===================
I am trying to understand how to prevent the existence of some pattern before or after a sought-out pattern when writing regex's!
A more specific example
=======================
I'm looking for a regex that will match dates in the format YYMMDD (`(([0-9]{2})(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1]))`) inside a long string while ignoring longer numeric sequences
it should be able to match:
* text151124moretext
* 123text151124moretext
* text151124
* text151124moretext1944
* 151124
but should **ignore**:
* text15112412moretext
(reason: it has 8 numbers instead of 6)
* 151324
(reason: it is not a valid date YYMMDD - there is no 13th month)
how can I make sure that if a number has **more** than these 6 digits, it won't picked up as a date inside one single regex (meaning, that I would rather avoid preprocessing the string)
I've thought of `\D((19|20)([0-9]{2})(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1]))\D` but doesn't this mean that there **has to be** some character before and after?
I'm using bash 3.2 (ERE)
thanks! | 2017/06/28 | ['https://Stackoverflow.com/questions/44812906', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3017323/'] | Try:
```
#!/usr/bin/env bash
extract_date() {
local string="$1"
local _date=`echo "$string" | sed -E 's/.*[^0-9]([0-9]{6})[^0-9].*/\1/'`
#date -d $_date &> /dev/null # for Linux
date -jf '%y%m%d' $_date &> /dev/null # for MacOS
if [ $? -eq 0 ]; then
echo $_date
else
return 1
fi
}
extract_date text15111224moretext # ignore n_digits > 6
extract_date text151125moretext # take
extract_date text151132 # # ignore day 32
extract_date text151324moretext1944 # ignore month 13
extract_date text150931moretext1944 # ignore 31 Sept
extract_date 151126 # take
```
Output:
```
151125
151126
``` | You could use non-capturing groups to define non-digits either side of your date Regex. I had success with this expression and your same test data.
```
(?:\D)([0-9]{2})(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])(?:\D)
``` |
12,672,951 | I want to lock my **camera view** to "**Landscape**" mode.When I click on the simple button in my app, that time device's camera will open and and that **camera should be locked** to "**Landscape mode**". Can anyone know the solution of this problem?
I am using this code inside "CaptureImageActivity.java" activity.
So after execution of this activity my system's camera will open.
```
btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent i=new Intent(android.provider.MediaStore. ACTION_IMAGE_CAPTURE);
i.putExtra(android.provider.MediaStore.EXTRA_SCREEN_ORIENTATION,ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
startActivityForResult(i,1000);
}
});
```
And I want to lock that camera view to "LandScape Mode". And as per solution
```
<activity android:name=".CaptureImageActivity"
android:screenOrientation="landscape"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
```
Only "CaptureImageActivity" activity is locked to "LandScape Mode". | 2012/10/01 | ['https://Stackoverflow.com/questions/12672951', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1711713/'] | Add this into your activity inside manifest file
```
android:screenOrientation="portrait"
``` | ```
By using setCameraDisplayOrientation=
public static void setCameraDisplayOrientation(Activity activity,
int cameraId, android.hardware.Camera camera) {
android.hardware.Camera.CameraInfo info =
new android.hardware.Camera.CameraInfo();
android.hardware.Camera.getCameraInfo(cameraId, info);
int rotation = activity.getWindowManager().getDefaultDisplay()
.getRotation();
int degrees = 0;
switch (rotation) {
case Surface.ROTATION_0: degrees = 0; break;
case Surface.ROTATION_90: degrees = 90; break;
case Surface.ROTATION_180: degrees = 180; break;
case Surface.ROTATION_270: degrees = 270; break;
}
int result;
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
result = (info.orientation + degrees) % 360;
result = (360 - result) % 360; // compensate the mirror
} else { // back-facing
result = (info.orientation - degrees + 360) % 360;
}
camera.setDisplayOrientation(result);
}
``` |
12,672,951 | I want to lock my **camera view** to "**Landscape**" mode.When I click on the simple button in my app, that time device's camera will open and and that **camera should be locked** to "**Landscape mode**". Can anyone know the solution of this problem?
I am using this code inside "CaptureImageActivity.java" activity.
So after execution of this activity my system's camera will open.
```
btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent i=new Intent(android.provider.MediaStore. ACTION_IMAGE_CAPTURE);
i.putExtra(android.provider.MediaStore.EXTRA_SCREEN_ORIENTATION,ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
startActivityForResult(i,1000);
}
});
```
And I want to lock that camera view to "LandScape Mode". And as per solution
```
<activity android:name=".CaptureImageActivity"
android:screenOrientation="landscape"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
```
Only "CaptureImageActivity" activity is locked to "LandScape Mode". | 2012/10/01 | ['https://Stackoverflow.com/questions/12672951', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1711713/'] | see this link to lock your camera orientation,use `setDisplayOrientation (int degrees)`
documentation can be found on following link :
<http://developer.android.com/reference/android/hardware/Camera.html#setDisplayOrientation%28int%29>
for more details see this answer :
[How to set Android camera orientation properly?](https://stackoverflow.com/questions/4645960/how-to-set-android-camera-orientation-properly) | ```
By using setCameraDisplayOrientation=
public static void setCameraDisplayOrientation(Activity activity,
int cameraId, android.hardware.Camera camera) {
android.hardware.Camera.CameraInfo info =
new android.hardware.Camera.CameraInfo();
android.hardware.Camera.getCameraInfo(cameraId, info);
int rotation = activity.getWindowManager().getDefaultDisplay()
.getRotation();
int degrees = 0;
switch (rotation) {
case Surface.ROTATION_0: degrees = 0; break;
case Surface.ROTATION_90: degrees = 90; break;
case Surface.ROTATION_180: degrees = 180; break;
case Surface.ROTATION_270: degrees = 270; break;
}
int result;
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
result = (info.orientation + degrees) % 360;
result = (360 - result) % 360; // compensate the mirror
} else { // back-facing
result = (info.orientation - degrees + 360) % 360;
}
camera.setDisplayOrientation(result);
}
``` |
10,172,336 | How can I install this theme <http://simplyhacking.com/spacedust-xcode-theme-for-xcode-4.html> on XCode 4.3.2? | 2012/04/16 | ['https://Stackoverflow.com/questions/10172336', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/631792/'] | Download that Spacedust.dvtcolortheme and save it under:
```
~/Library/Developer/Xcode/UserData/FontAndColorThemes
```
It might be that this folder doesn't exist yet if you never copied an existing Colortheme in the preferences of Xcode. In that case: simply create that directory.
Then restart Xcode. | I wanted to add one more little information that after adding the theme to FontAndColorThemes folder and restarting xcode4, go to Fonts & Colors.
you should see it under :
>
> Preferences -> Fonts & Colors.
>
>
>
select your theme and enjoy the theme.
ref : <http://superqichi.com/add-new-theme-to-xcode-4> |
10,172,336 | How can I install this theme <http://simplyhacking.com/spacedust-xcode-theme-for-xcode-4.html> on XCode 4.3.2? | 2012/04/16 | ['https://Stackoverflow.com/questions/10172336', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/631792/'] | Download that Spacedust.dvtcolortheme and save it under:
```
~/Library/Developer/Xcode/UserData/FontAndColorThemes
```
It might be that this folder doesn't exist yet if you never copied an existing Colortheme in the preferences of Xcode. In that case: simply create that directory.
Then restart Xcode. | ThemeInstaller is an easy app for installing themes in Xcode.
Having ThemeInstaller all you need to do is to open an .dvtcolortheme, or go to codethemes.net and press "install" under any of your choice.
In Xcode you need to press "cmd" + "," and there you have all of your installed themes. |
10,172,336 | How can I install this theme <http://simplyhacking.com/spacedust-xcode-theme-for-xcode-4.html> on XCode 4.3.2? | 2012/04/16 | ['https://Stackoverflow.com/questions/10172336', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/631792/'] | I wanted to add one more little information that after adding the theme to FontAndColorThemes folder and restarting xcode4, go to Fonts & Colors.
you should see it under :
>
> Preferences -> Fonts & Colors.
>
>
>
select your theme and enjoy the theme.
ref : <http://superqichi.com/add-new-theme-to-xcode-4> | ThemeInstaller is an easy app for installing themes in Xcode.
Having ThemeInstaller all you need to do is to open an .dvtcolortheme, or go to codethemes.net and press "install" under any of your choice.
In Xcode you need to press "cmd" + "," and there you have all of your installed themes. |
1,522,677 | How to add outlook custom fields in ms access?
Example:
```
Set objOutlook = CreateObject("Outlook.Application")
Set item = objOutlook.CreateItem(2)
Set nms = objOutlook.GetNamespace("MAPI")
Set fldContacts = nms.GetDefaultFolder(10)
Set itms = fldContacts.Items
Set item = itms.Add
item.FirstName = Me.FirstName
...
item.Email1Address = Me.Email
item.Fields("ClientId") = "Client1"
item.Display
```
item.Fields("ClientId") = "Client1" -> This line does not work, any idea how to make this thing work? Thanks!! | 2009/10/05 | ['https://Stackoverflow.com/questions/1522677', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/154698/'] | Underscore matches one character only. Is this what you're looking for?
```
LIKE '___ ___'
``` | ```
SELECT *
FORM SomeTable
WHERE Postal LIKE '___ ___'
```
Or even better, when you want to specify exact numbers-letters, you can do this:
```
SELECT *
FORM SomeTable
WHERE Postal LIKE '[a-z][a-z][a-z] [0-9][0-9][0-9]'
```
It depends of the type of code you want to get. |
12,058,016 | I am attempting to set up an sftp server on ubuntu/precise on EC2. I have been successful in adding a new user that can connect via ssh, however once I add the following clause:
```
Match Group sftp
ChrootDirectory /home/%u
AllowTCPForwarding no
X11Forwarding no
ForceCommand internal-sftp
```
I can no longer connect (at all, ssh or otherwise) and I get the message
```
Error: Connection refused
Error: Could not connect to server
```
I am able to connect with the subsystem set to:
```
#Subsystem sftp /usr/lib/openssh/sftp-server
Subsystem sftp internal-sftp
```
Any idea why the ssh server is failing with this "Match" clause? Essentially, everything is working except for the "chroot" part. | 2012/08/21 | ['https://Stackoverflow.com/questions/12058016', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/634621/'] | Ok, solved the issue:
2 things were causing a problem
1. I had to move the "Match" Clause to the END of the file, it was in the middle
2. There was a permissions issue - found the answer elsewhere that fixed it
from: <https://askubuntu.com/questions/134425/how-can-i-chroot-sftp-only-ssh-users-into-their-homes>
"All this pain is thanks to several security issues as detailed here. Basically the chroot directory has to be owned by root and can't be any group-write access. Lovely. So you essentially need to turn your chroot into a holding cell and within that you can have your editable content.
```
sudo chown root /home/bob
sudo chmod go-w /home/bob
sudo mkdir /home/bob/writable
sudo chown bob:sftponly /home/bob/writable
sudo chmod ug+rwX /home/bob/writable
```
And bam, you can log in and write in /writable." | Make sure that /home and /home/%u are chowned to root:root. |
11,748,272 | I'm trying to determine where a slowdown is occurring in my GPU code. I've verified that the code runs correctly on its own (it doesn't throw any errors, outputs are correct, finishes cleanly, etc). When I try to profile the code in Visual Profiler, it seems to run normally, dumping correct intermediate outputs to stdout. The GPU is being used (I've checked with cuda-gdb and dumping `printf()`s from inside my kernels). Once all the code has completed, Visual Profiler reports that viper has terminated the executable. However, no timeline is generated. Instead, the main window shows 0, 10, 20, 25 microseconds all "collapsed" on top of one another. When I tell the Visual Profiler to run all analysis options, it proceeds through the 24 runs without problems, but still no timeline is generated.
I'm using CUDA 4.2, driver version 295.41 on Ubuntu x86\_64 with a GeForce 460. | 2012/07/31 | ['https://Stackoverflow.com/questions/11748272', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/994259/'] | When the visual profiler fails to generate a timeline it is typically because it cannot locate a component required for profiling. This component is a shared library found in /usr/local/cuda/lib64 called libcuinj.so. Is that path on your LD\_LIBRARY\_PATH? How are you launching the Visual Profiler? The script in /usr/local/cuda/bin/nvvp should set the path correctly for you.
The 4.2 version of the visual profiler does not do a good job of reporting errors when this shared library is not found. The upcoming 5.0 version of the visual profiler has much better error reporting in this regard. | I don't know if it's the same under Linux, but in Nsight under Windows, there are two basic types of profiling that you can run. "Application trace" and "Profile". Only under Application trace do you get the timelines. Application trace records the timestamps when CUDA and kernel calls were made. The Profile setting offers options to analyze the kernels. It reads the hardware counters from the GPU and generates performance information related to one or multiple kernels (and no timelines). |
1,944,198 | I'm given the problem where one can perform perfect shuffles (i.e. you split the deck into halves and then interweave them) on a deck of $52$ cards (both in and out shuffles) and I am supposed to determine whether all $52!$ possible deck orderings are possible through a composition of such shuffles. I know that given only in or out shuffles you cannot do so since they are cyclic and of order $8$ and $52$ but I really have no idea how to even begin to tackle this problem of composing them. Was hoping for any hints or thoughts on as to how I should attempt this problem? Thanks!
EDIT: An out shuffle is when you interweave leaving the top card on the top while an in shuffle is when you interweave by putting the top card of the bottom half on top of the whole deck. | 2016/09/27 | ['https://math.stackexchange.com/questions/1944198', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/164995/'] | Not an answer, just a suggestion.
You have two permutations, and you want to find out if they generate the entire group of all permutations.
If $a$ is one permutation, and $b$ is the other, then $ab^{-1}=(1\,27)(2\,28)(3\,29)\cdots(26\,52)$. We can see that $a$ and $c=ab^{-1}$ generates the same subgroup as $a$ and $b$.
$c=ab^{-1}$ is probably easier to deal with, since its order is $2$. | Given an initial configuration of a deck of $52$ cards, perfectly shuffling them $52$ times will take you through exactly $52$ of the $52!$ permutations on the deck. In order to hit every one of them, you must perfectly shuffle the deck and then switch the top two cards before perfectly shuffling it again. Of course you'd be doing this for several lifetimes. In the same vein, perfectly out-shuffling $52$ times, and then in-shuffling once before out-shuffling again $52$ times will indeed have the same effect as composing (or switching just the top two cards) the permutations. But again we could never experience this in hundreds of lifetimes. A computer simulation could demonstrate it perhaps. The (n-1) k-cycle has $8$ elements in its one-orbit for $n=52$, whereas the (n+1) k-cycle has $52$. This is how order is determined. There is no multiplication that can be performed on these orders to determine whether they span the full symmetric set. We can see the composition. Go through all $52$ configurations stemming from the initial position, make one alteration, repeat. Time permitting, we will see every member of S sub $52$. |
48,891,174 | I have a normal Angular Material 2 DataTable with sort headers.
All sort are headers work fine. Except for the one with an object as value.
These doesn't sort at all.
For example:
```html
<!-- Project Column - This should sort!-->
<ng-container matColumnDef="project.name">
<mat-header-cell *matHeaderCellDef mat-sort-header> Project Name </mat-header-cell>
<mat-cell *matCellDef="let element"> {{element.project.name}} </mat-cell>
</ng-container>
```
note the `element.project.name`
Here's the displayColumn config:
```
displayedColumns = ['project.name', 'position', 'name', 'test', 'symbol'];
```
Changing `'project.name'` to `'project'` doesn't work nor `"project['name']"`
What am I missing? Is this even possible?
Here's a Stackblitz:
[Angular Material2 DataTable sort objects](https://stackblitz.com/edit/angular-rtw2fx)
**Edit:**
Thanks for all your answers.
I've already got it working with dynamic data. So I don't have to add a switch statement for every new nested property.
Here's my solution: (Creating a new DataSource which extends MatTableDataSource is not necessary)
```js
export class NestedObjectsDataSource extends MatTableDataSource<MyObjectType> {
sortingDataAccessor: ((data: WorkingHours, sortHeaderId: string) => string | number) =
(data: WorkingHours, sortHeaderId: string): string | number => {
let value = null;
if (sortHeaderId.indexOf('.') !== -1) {
const ids = sortHeaderId.split('.');
value = data[ids[0]][ids[1]];
} else {
value = data[sortHeaderId];
}
return _isNumberValue(value) ? Number(value) : value;
}
constructor() {
super();
}
}
``` | 2018/02/20 | ['https://Stackoverflow.com/questions/48891174', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7515302/'] | It was hard to find documentation on this, but it is possible by using `sortingDataAccessor` and a switch statement. For example:
```
@ViewChild(MatSort) sort: MatSort;
ngOnInit() {
this.dataSource = new MatTableDataSource(yourData);
this.dataSource.sortingDataAccessor = (item, property) => {
switch(property) {
case 'project.name': return item.project.name;
default: return item[property];
}
};
this.dataSource.sort = sort;
}
``` | You can write a function in component to get deeply property from object. Then use it in `dataSource.sortingDataAccessor` like below
```
getProperty = (obj, path) => (
path.split('.').reduce((o, p) => o && o[p], obj)
)
ngOnInit() {
this.dataSource = new MatTableDataSource(yourData);
this.dataSource.sortingDataAccessor = (obj, property) => this.getProperty(obj, property);
this.dataSource.sort = sort;
}
columnDefs = [
{name: 'project.name', title: 'Project Name'},
{name: 'position', title: 'Position'},
{name: 'name', title: 'Name'},
{name: 'test', title: 'Test'},
{name: 'symbol', title: 'Symbol'}
];
```
And in html
```
<ng-container *ngFor="let col of columnDefs" [matColumnDef]="col.name">
<mat-header-cell *matHeaderCellDef>{{ col.title }}</mat-header-cell>
<mat-cell *matCellDef="let row">
{{ getProperty(row, col.name) }}
</mat-cell>
</ng-container>
``` |
48,891,174 | I have a normal Angular Material 2 DataTable with sort headers.
All sort are headers work fine. Except for the one with an object as value.
These doesn't sort at all.
For example:
```html
<!-- Project Column - This should sort!-->
<ng-container matColumnDef="project.name">
<mat-header-cell *matHeaderCellDef mat-sort-header> Project Name </mat-header-cell>
<mat-cell *matCellDef="let element"> {{element.project.name}} </mat-cell>
</ng-container>
```
note the `element.project.name`
Here's the displayColumn config:
```
displayedColumns = ['project.name', 'position', 'name', 'test', 'symbol'];
```
Changing `'project.name'` to `'project'` doesn't work nor `"project['name']"`
What am I missing? Is this even possible?
Here's a Stackblitz:
[Angular Material2 DataTable sort objects](https://stackblitz.com/edit/angular-rtw2fx)
**Edit:**
Thanks for all your answers.
I've already got it working with dynamic data. So I don't have to add a switch statement for every new nested property.
Here's my solution: (Creating a new DataSource which extends MatTableDataSource is not necessary)
```js
export class NestedObjectsDataSource extends MatTableDataSource<MyObjectType> {
sortingDataAccessor: ((data: WorkingHours, sortHeaderId: string) => string | number) =
(data: WorkingHours, sortHeaderId: string): string | number => {
let value = null;
if (sortHeaderId.indexOf('.') !== -1) {
const ids = sortHeaderId.split('.');
value = data[ids[0]][ids[1]];
} else {
value = data[sortHeaderId];
}
return _isNumberValue(value) ? Number(value) : value;
}
constructor() {
super();
}
}
``` | 2018/02/20 | ['https://Stackoverflow.com/questions/48891174', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7515302/'] | I use a generic method which allows you to use a dot.seperated.path with `mat-sort-header` or `matColumnDef`. This fails silently returning undefined if it cannot find the property dictated by the path.
```
function pathDataAccessor(item: any, path: string): any {
return path.split('.')
.reduce((accumulator: any, key: string) => {
return accumulator ? accumulator[key] : undefined;
}, item);
}
```
You just need to set the data accessor
```
this.dataSource.sortingDataAccessor = pathDataAccessor;
``` | Another alternative, that no one threw out here, flatten the column first...
```
yourData.map((d) =>
d.flattenedName = d.project && d.project.name ?
d.project.name :
'Not Specified');
this.dataSource = new MatTableDataSource(yourData);
```
Just another alternative, pros and cons for each! |
48,891,174 | I have a normal Angular Material 2 DataTable with sort headers.
All sort are headers work fine. Except for the one with an object as value.
These doesn't sort at all.
For example:
```html
<!-- Project Column - This should sort!-->
<ng-container matColumnDef="project.name">
<mat-header-cell *matHeaderCellDef mat-sort-header> Project Name </mat-header-cell>
<mat-cell *matCellDef="let element"> {{element.project.name}} </mat-cell>
</ng-container>
```
note the `element.project.name`
Here's the displayColumn config:
```
displayedColumns = ['project.name', 'position', 'name', 'test', 'symbol'];
```
Changing `'project.name'` to `'project'` doesn't work nor `"project['name']"`
What am I missing? Is this even possible?
Here's a Stackblitz:
[Angular Material2 DataTable sort objects](https://stackblitz.com/edit/angular-rtw2fx)
**Edit:**
Thanks for all your answers.
I've already got it working with dynamic data. So I don't have to add a switch statement for every new nested property.
Here's my solution: (Creating a new DataSource which extends MatTableDataSource is not necessary)
```js
export class NestedObjectsDataSource extends MatTableDataSource<MyObjectType> {
sortingDataAccessor: ((data: WorkingHours, sortHeaderId: string) => string | number) =
(data: WorkingHours, sortHeaderId: string): string | number => {
let value = null;
if (sortHeaderId.indexOf('.') !== -1) {
const ids = sortHeaderId.split('.');
value = data[ids[0]][ids[1]];
} else {
value = data[sortHeaderId];
}
return _isNumberValue(value) ? Number(value) : value;
}
constructor() {
super();
}
}
``` | 2018/02/20 | ['https://Stackoverflow.com/questions/48891174', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7515302/'] | Just add this to your data source and you will be able to access the nested object
```
this.dataSource.sortingDataAccessor = (item, property) => {
// Split '.' to allow accessing property of nested object
if (property.includes('.')) {
const accessor = property.split('.');
let value: any = item;
accessor.forEach((a) => {
value = value[a];
});
return value;
}
// Access as normal
return item[property];
};
``` | Another alternative, that no one threw out here, flatten the column first...
```
yourData.map((d) =>
d.flattenedName = d.project && d.project.name ?
d.project.name :
'Not Specified');
this.dataSource = new MatTableDataSource(yourData);
```
Just another alternative, pros and cons for each! |
48,891,174 | I have a normal Angular Material 2 DataTable with sort headers.
All sort are headers work fine. Except for the one with an object as value.
These doesn't sort at all.
For example:
```html
<!-- Project Column - This should sort!-->
<ng-container matColumnDef="project.name">
<mat-header-cell *matHeaderCellDef mat-sort-header> Project Name </mat-header-cell>
<mat-cell *matCellDef="let element"> {{element.project.name}} </mat-cell>
</ng-container>
```
note the `element.project.name`
Here's the displayColumn config:
```
displayedColumns = ['project.name', 'position', 'name', 'test', 'symbol'];
```
Changing `'project.name'` to `'project'` doesn't work nor `"project['name']"`
What am I missing? Is this even possible?
Here's a Stackblitz:
[Angular Material2 DataTable sort objects](https://stackblitz.com/edit/angular-rtw2fx)
**Edit:**
Thanks for all your answers.
I've already got it working with dynamic data. So I don't have to add a switch statement for every new nested property.
Here's my solution: (Creating a new DataSource which extends MatTableDataSource is not necessary)
```js
export class NestedObjectsDataSource extends MatTableDataSource<MyObjectType> {
sortingDataAccessor: ((data: WorkingHours, sortHeaderId: string) => string | number) =
(data: WorkingHours, sortHeaderId: string): string | number => {
let value = null;
if (sortHeaderId.indexOf('.') !== -1) {
const ids = sortHeaderId.split('.');
value = data[ids[0]][ids[1]];
} else {
value = data[sortHeaderId];
}
return _isNumberValue(value) ? Number(value) : value;
}
constructor() {
super();
}
}
``` | 2018/02/20 | ['https://Stackoverflow.com/questions/48891174', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7515302/'] | Another alternative, that no one threw out here, flatten the column first...
```
yourData.map((d) =>
d.flattenedName = d.project && d.project.name ?
d.project.name :
'Not Specified');
this.dataSource = new MatTableDataSource(yourData);
```
Just another alternative, pros and cons for each! | It's trying to sort by element['project.name']. Obviously element doesn't have such a property.
It should be easy to create a custom datasource that extends MatTableDatasource and supports sorting by nested object properties. Check out the examples in material.angular.io docs on using a custom source. |
48,891,174 | I have a normal Angular Material 2 DataTable with sort headers.
All sort are headers work fine. Except for the one with an object as value.
These doesn't sort at all.
For example:
```html
<!-- Project Column - This should sort!-->
<ng-container matColumnDef="project.name">
<mat-header-cell *matHeaderCellDef mat-sort-header> Project Name </mat-header-cell>
<mat-cell *matCellDef="let element"> {{element.project.name}} </mat-cell>
</ng-container>
```
note the `element.project.name`
Here's the displayColumn config:
```
displayedColumns = ['project.name', 'position', 'name', 'test', 'symbol'];
```
Changing `'project.name'` to `'project'` doesn't work nor `"project['name']"`
What am I missing? Is this even possible?
Here's a Stackblitz:
[Angular Material2 DataTable sort objects](https://stackblitz.com/edit/angular-rtw2fx)
**Edit:**
Thanks for all your answers.
I've already got it working with dynamic data. So I don't have to add a switch statement for every new nested property.
Here's my solution: (Creating a new DataSource which extends MatTableDataSource is not necessary)
```js
export class NestedObjectsDataSource extends MatTableDataSource<MyObjectType> {
sortingDataAccessor: ((data: WorkingHours, sortHeaderId: string) => string | number) =
(data: WorkingHours, sortHeaderId: string): string | number => {
let value = null;
if (sortHeaderId.indexOf('.') !== -1) {
const ids = sortHeaderId.split('.');
value = data[ids[0]][ids[1]];
} else {
value = data[sortHeaderId];
}
return _isNumberValue(value) ? Number(value) : value;
}
constructor() {
super();
}
}
``` | 2018/02/20 | ['https://Stackoverflow.com/questions/48891174', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7515302/'] | It was hard to find documentation on this, but it is possible by using `sortingDataAccessor` and a switch statement. For example:
```
@ViewChild(MatSort) sort: MatSort;
ngOnInit() {
this.dataSource = new MatTableDataSource(yourData);
this.dataSource.sortingDataAccessor = (item, property) => {
switch(property) {
case 'project.name': return item.project.name;
default: return item[property];
}
};
this.dataSource.sort = sort;
}
``` | It's trying to sort by element['project.name']. Obviously element doesn't have such a property.
It should be easy to create a custom datasource that extends MatTableDatasource and supports sorting by nested object properties. Check out the examples in material.angular.io docs on using a custom source. |
48,891,174 | I have a normal Angular Material 2 DataTable with sort headers.
All sort are headers work fine. Except for the one with an object as value.
These doesn't sort at all.
For example:
```html
<!-- Project Column - This should sort!-->
<ng-container matColumnDef="project.name">
<mat-header-cell *matHeaderCellDef mat-sort-header> Project Name </mat-header-cell>
<mat-cell *matCellDef="let element"> {{element.project.name}} </mat-cell>
</ng-container>
```
note the `element.project.name`
Here's the displayColumn config:
```
displayedColumns = ['project.name', 'position', 'name', 'test', 'symbol'];
```
Changing `'project.name'` to `'project'` doesn't work nor `"project['name']"`
What am I missing? Is this even possible?
Here's a Stackblitz:
[Angular Material2 DataTable sort objects](https://stackblitz.com/edit/angular-rtw2fx)
**Edit:**
Thanks for all your answers.
I've already got it working with dynamic data. So I don't have to add a switch statement for every new nested property.
Here's my solution: (Creating a new DataSource which extends MatTableDataSource is not necessary)
```js
export class NestedObjectsDataSource extends MatTableDataSource<MyObjectType> {
sortingDataAccessor: ((data: WorkingHours, sortHeaderId: string) => string | number) =
(data: WorkingHours, sortHeaderId: string): string | number => {
let value = null;
if (sortHeaderId.indexOf('.') !== -1) {
const ids = sortHeaderId.split('.');
value = data[ids[0]][ids[1]];
} else {
value = data[sortHeaderId];
}
return _isNumberValue(value) ? Number(value) : value;
}
constructor() {
super();
}
}
``` | 2018/02/20 | ['https://Stackoverflow.com/questions/48891174', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7515302/'] | You can write a function in component to get deeply property from object. Then use it in `dataSource.sortingDataAccessor` like below
```
getProperty = (obj, path) => (
path.split('.').reduce((o, p) => o && o[p], obj)
)
ngOnInit() {
this.dataSource = new MatTableDataSource(yourData);
this.dataSource.sortingDataAccessor = (obj, property) => this.getProperty(obj, property);
this.dataSource.sort = sort;
}
columnDefs = [
{name: 'project.name', title: 'Project Name'},
{name: 'position', title: 'Position'},
{name: 'name', title: 'Name'},
{name: 'test', title: 'Test'},
{name: 'symbol', title: 'Symbol'}
];
```
And in html
```
<ng-container *ngFor="let col of columnDefs" [matColumnDef]="col.name">
<mat-header-cell *matHeaderCellDef>{{ col.title }}</mat-header-cell>
<mat-cell *matCellDef="let row">
{{ getProperty(row, col.name) }}
</mat-cell>
</ng-container>
``` | I customized for multiple nested object level.
```
this.dataSource.sortingDataAccessor =
(data: any, sortHeaderId: string): string | number => {
let value = null;
if (sortHeaderId.includes('.')) {
const ids = sortHeaderId.split('.');
value = data;
ids.forEach(function (x) {
value = value? value[x]: null;
});
} else {
value = data[sortHeaderId];
}
return _isNumberValue(value) ? Number(value) : value;
};
``` |
48,891,174 | I have a normal Angular Material 2 DataTable with sort headers.
All sort are headers work fine. Except for the one with an object as value.
These doesn't sort at all.
For example:
```html
<!-- Project Column - This should sort!-->
<ng-container matColumnDef="project.name">
<mat-header-cell *matHeaderCellDef mat-sort-header> Project Name </mat-header-cell>
<mat-cell *matCellDef="let element"> {{element.project.name}} </mat-cell>
</ng-container>
```
note the `element.project.name`
Here's the displayColumn config:
```
displayedColumns = ['project.name', 'position', 'name', 'test', 'symbol'];
```
Changing `'project.name'` to `'project'` doesn't work nor `"project['name']"`
What am I missing? Is this even possible?
Here's a Stackblitz:
[Angular Material2 DataTable sort objects](https://stackblitz.com/edit/angular-rtw2fx)
**Edit:**
Thanks for all your answers.
I've already got it working with dynamic data. So I don't have to add a switch statement for every new nested property.
Here's my solution: (Creating a new DataSource which extends MatTableDataSource is not necessary)
```js
export class NestedObjectsDataSource extends MatTableDataSource<MyObjectType> {
sortingDataAccessor: ((data: WorkingHours, sortHeaderId: string) => string | number) =
(data: WorkingHours, sortHeaderId: string): string | number => {
let value = null;
if (sortHeaderId.indexOf('.') !== -1) {
const ids = sortHeaderId.split('.');
value = data[ids[0]][ids[1]];
} else {
value = data[sortHeaderId];
}
return _isNumberValue(value) ? Number(value) : value;
}
constructor() {
super();
}
}
``` | 2018/02/20 | ['https://Stackoverflow.com/questions/48891174', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7515302/'] | I like @Hieu\_Nguyen solutions. I'll just add that if you use lodash in you project as I do then the solution translates to this:
```
import * as _ from 'lodash';
this.dataSource.sortingDataAccessor = _.get;
```
No need to reinvent the deep property access. | I customized for multiple nested object level.
```
this.dataSource.sortingDataAccessor =
(data: any, sortHeaderId: string): string | number => {
let value = null;
if (sortHeaderId.includes('.')) {
const ids = sortHeaderId.split('.');
value = data;
ids.forEach(function (x) {
value = value? value[x]: null;
});
} else {
value = data[sortHeaderId];
}
return _isNumberValue(value) ? Number(value) : value;
};
``` |
48,891,174 | I have a normal Angular Material 2 DataTable with sort headers.
All sort are headers work fine. Except for the one with an object as value.
These doesn't sort at all.
For example:
```html
<!-- Project Column - This should sort!-->
<ng-container matColumnDef="project.name">
<mat-header-cell *matHeaderCellDef mat-sort-header> Project Name </mat-header-cell>
<mat-cell *matCellDef="let element"> {{element.project.name}} </mat-cell>
</ng-container>
```
note the `element.project.name`
Here's the displayColumn config:
```
displayedColumns = ['project.name', 'position', 'name', 'test', 'symbol'];
```
Changing `'project.name'` to `'project'` doesn't work nor `"project['name']"`
What am I missing? Is this even possible?
Here's a Stackblitz:
[Angular Material2 DataTable sort objects](https://stackblitz.com/edit/angular-rtw2fx)
**Edit:**
Thanks for all your answers.
I've already got it working with dynamic data. So I don't have to add a switch statement for every new nested property.
Here's my solution: (Creating a new DataSource which extends MatTableDataSource is not necessary)
```js
export class NestedObjectsDataSource extends MatTableDataSource<MyObjectType> {
sortingDataAccessor: ((data: WorkingHours, sortHeaderId: string) => string | number) =
(data: WorkingHours, sortHeaderId: string): string | number => {
let value = null;
if (sortHeaderId.indexOf('.') !== -1) {
const ids = sortHeaderId.split('.');
value = data[ids[0]][ids[1]];
} else {
value = data[sortHeaderId];
}
return _isNumberValue(value) ? Number(value) : value;
}
constructor() {
super();
}
}
``` | 2018/02/20 | ['https://Stackoverflow.com/questions/48891174', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7515302/'] | The answer as given can even be shortened, no switch required, as long as you use the dot notation for the fields.
```
ngOnInit() {
this.dataSource = new MatTableDataSource(yourData);
this.dataSource.sortingDataAccessor = (item, property) => {
if (property.includes('.')) return property.split('.').reduce((o,i)=>o[i], item)
return item[property];
};
this.dataSource.sort = sort;
}
``` | If you want to have an Angular material table with some extended features, like sorting for nested objects have a look at <https://github.com/mikelgo/ngx-mat-table-extensions/blob/master/libs/ngx-mat-table/README.md> .
I created this lib because I was missing some features of mat-table out of the box.
The advanced sorting is similar to @Hieu Nguyen suggested answer but a bit extended to also have proper sorting by upper and smaller case letters. |
48,891,174 | I have a normal Angular Material 2 DataTable with sort headers.
All sort are headers work fine. Except for the one with an object as value.
These doesn't sort at all.
For example:
```html
<!-- Project Column - This should sort!-->
<ng-container matColumnDef="project.name">
<mat-header-cell *matHeaderCellDef mat-sort-header> Project Name </mat-header-cell>
<mat-cell *matCellDef="let element"> {{element.project.name}} </mat-cell>
</ng-container>
```
note the `element.project.name`
Here's the displayColumn config:
```
displayedColumns = ['project.name', 'position', 'name', 'test', 'symbol'];
```
Changing `'project.name'` to `'project'` doesn't work nor `"project['name']"`
What am I missing? Is this even possible?
Here's a Stackblitz:
[Angular Material2 DataTable sort objects](https://stackblitz.com/edit/angular-rtw2fx)
**Edit:**
Thanks for all your answers.
I've already got it working with dynamic data. So I don't have to add a switch statement for every new nested property.
Here's my solution: (Creating a new DataSource which extends MatTableDataSource is not necessary)
```js
export class NestedObjectsDataSource extends MatTableDataSource<MyObjectType> {
sortingDataAccessor: ((data: WorkingHours, sortHeaderId: string) => string | number) =
(data: WorkingHours, sortHeaderId: string): string | number => {
let value = null;
if (sortHeaderId.indexOf('.') !== -1) {
const ids = sortHeaderId.split('.');
value = data[ids[0]][ids[1]];
} else {
value = data[sortHeaderId];
}
return _isNumberValue(value) ? Number(value) : value;
}
constructor() {
super();
}
}
``` | 2018/02/20 | ['https://Stackoverflow.com/questions/48891174', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7515302/'] | The answer as given can even be shortened, no switch required, as long as you use the dot notation for the fields.
```
ngOnInit() {
this.dataSource = new MatTableDataSource(yourData);
this.dataSource.sortingDataAccessor = (item, property) => {
if (property.includes('.')) return property.split('.').reduce((o,i)=>o[i], item)
return item[property];
};
this.dataSource.sort = sort;
}
``` | Just add this to your data source and you will be able to access the nested object
```
this.dataSource.sortingDataAccessor = (item, property) => {
// Split '.' to allow accessing property of nested object
if (property.includes('.')) {
const accessor = property.split('.');
let value: any = item;
accessor.forEach((a) => {
value = value[a];
});
return value;
}
// Access as normal
return item[property];
};
``` |
48,891,174 | I have a normal Angular Material 2 DataTable with sort headers.
All sort are headers work fine. Except for the one with an object as value.
These doesn't sort at all.
For example:
```html
<!-- Project Column - This should sort!-->
<ng-container matColumnDef="project.name">
<mat-header-cell *matHeaderCellDef mat-sort-header> Project Name </mat-header-cell>
<mat-cell *matCellDef="let element"> {{element.project.name}} </mat-cell>
</ng-container>
```
note the `element.project.name`
Here's the displayColumn config:
```
displayedColumns = ['project.name', 'position', 'name', 'test', 'symbol'];
```
Changing `'project.name'` to `'project'` doesn't work nor `"project['name']"`
What am I missing? Is this even possible?
Here's a Stackblitz:
[Angular Material2 DataTable sort objects](https://stackblitz.com/edit/angular-rtw2fx)
**Edit:**
Thanks for all your answers.
I've already got it working with dynamic data. So I don't have to add a switch statement for every new nested property.
Here's my solution: (Creating a new DataSource which extends MatTableDataSource is not necessary)
```js
export class NestedObjectsDataSource extends MatTableDataSource<MyObjectType> {
sortingDataAccessor: ((data: WorkingHours, sortHeaderId: string) => string | number) =
(data: WorkingHours, sortHeaderId: string): string | number => {
let value = null;
if (sortHeaderId.indexOf('.') !== -1) {
const ids = sortHeaderId.split('.');
value = data[ids[0]][ids[1]];
} else {
value = data[sortHeaderId];
}
return _isNumberValue(value) ? Number(value) : value;
}
constructor() {
super();
}
}
``` | 2018/02/20 | ['https://Stackoverflow.com/questions/48891174', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7515302/'] | Just add this to your data source and you will be able to access the nested object
```
this.dataSource.sortingDataAccessor = (item, property) => {
// Split '.' to allow accessing property of nested object
if (property.includes('.')) {
const accessor = property.split('.');
let value: any = item;
accessor.forEach((a) => {
value = value[a];
});
return value;
}
// Access as normal
return item[property];
};
``` | I had the same issue, by testing the first proposition I had some errors, I could fixe it by adding "switch (property)"
```
this.dataSource.sortingDataAccessor =(item, property) => {
switch (property) {
case 'project.name': return item.project.name;
default: return item[property];
}
};
``` |
31,514 | A neutron outside the nucleus lives for about 15 minutes and decays mainly through weak decays (beta decay). Many other weakly decaying particles decay with lifetimes between $10^{-10}$ and $10^{-12}$ seconds, which is consistent with $\alpha\_W \simeq 10^{-6}$.
Why does the neutron lives so much longer than the others? | 2012/07/07 | ['https://physics.stackexchange.com/questions/31514', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/1502/'] | NB: I feel like this is a pretty half-assed job, and I apologize for that but having opened my mouth in the comments I guess I have to write *something* to back it up.
---
We start with Fermi's golden rule for all transitions. The probability of the transition is
$$ P\_{i\to f} = \frac{2\pi}{\hbar} \left|M\_{i,f}\right|^2 \rho $$
where $\rho$ is the density of final states which is proportional to $p^2$ for massive particles. To find the rate1 for all possible final states we sum over these probabilities incoherently. When the mass difference between the initial and final states is much less than the $W$ mass the matrix element $M\_{i,f}$ depends only weakly (hah!) on the particular state and the sum is well approximated by a sum *only* over the density of states:
$$P\_\text{decay} \approx \frac{2\pi}{\hbar} \left|M\_{}\right|^2 \int\_\text{all outcomes} \rho .$$
This sum is collectively called the phase space available to the decay. In these cases the matrix element is also quite small for [the reason that Dr BDO discusses](https://physics.stackexchange.com/a/31526/520).
The phase space computation can be quite complicated as it must be taken over all unconstrained momenta of the products. For decays to two body states it turns out to be easy, there is no freedom in the final states except the $4\pi$ angular distribution in the decay frame (their are eight degrees of freedom in two 4-vectors, but 2 masses and the conservation of four momentum account for all of them except the azimuthal and polar angles of one of the particles).
The decays that you have asked about are to three body states. That gives us twelve degrees of freedom less three constraints from masses, four from conservation of 4-momentum which leaves five. Three of these are the Euler angles describing the orientation of the decay (and a factor of $8\pi^2$ to $\rho$), so our sum is over two non-trival momenta. The integral looks something like
$$
\begin{array}\\
\rho \propto \int p\_1^2 \mathrm{d}p\_1 \int p\_2^2 \mathrm{d}p\_2 \int \mathrm{d}(\cos\theta)
&\delta(m\_0 - E\_1 - E\_2-E\_3 ) \\
&\delta(E\_1^2 - m\_1^2 - p\_1^2) \\
&\delta(E\_2^2 - m\_2^2 - p\_2^2) \\
&\delta(E\_2^2 - m\_2^2 - p\_2^2) \\
&\delta(\vec{p}\_1 + \vec{p}\_2 + \vec{p}\_3)
\end{array}
$$
which is easier to compute in Monte Carlo than by hand. (BTW--the reason for introducing the seemingly redundant integral over the angle $\theta$ between the momenta of particles 1 and 2 will become evident in a little while).
For beta decays the remnant nucleus is very heavy compared to the released energy, [which simplifies the above in one limit](http://hyperphysics.phy-astr.gsu.edu/hbase/quantum/fermi2.html).
In the case of muon decay, it is not unreasonable to treat all the products as ultra-relativistic, and the above reduces to
$$
\begin{array}\\
\rho \propto \int p\_1^2 \mathrm{d}p\_1 \int p\_2^2 \mathrm{d}p\_2 \int \mathrm{d}(\cos\theta)
&\delta(m\_0 - E\_1 - E\_2 - E\_3 ) \\
&\delta(E\_1 - p\_1) \\
&\delta(E\_2 - p\_2) \\
&\delta(E\_3 - p\_3) \\
&\delta(\vec{p}\_1 + \vec{p}\_2 + \vec{p}\_3) \\
= \int p\_1^2 \mathrm{d}p\_1 \int p\_2^2 \mathrm{d}p\_2 \int \mathrm{d}(\cos\theta)
&\delta(m\_0 - p\_1 - p\_2 - p\_3 ) \\
&\delta(\vec{p}\_1 + \vec{p}\_2 + \vec{p}\_3) \\
= \int p\_1^2 \mathrm{d}p\_1 \int p\_2^2 \mathrm{d}p\_2 \int \mathrm{d}(\cos\theta)
&\delta(m\_0 - p\_1 - p\_2 - \left|\vec{p}\_1 + \vec{p}\_2\right| )\\
= \int p\_1^2 \mathrm{d}p\_1 \int p\_2^2 \mathrm{d}p\_2 \int \mathrm{d}(\cos\theta)
&\delta\left(m\_0 - p\_1 - p\_2 - \sqrt{p\_1^2 + p\_2^2 - p\_1p\_2\cos\theta} \right)
\end{array}
$$
The integral over the angle will evaluate to one in some regions and zero in others and as such is equivalent to correctly assigning the limits of the other two integrals, so writing $\delta m = m\_0 - m\_1 - m\_2 - m\_3$ we get
$$
\begin{array}
\rho
& \propto \int\_0^{\delta m/2} p\_1^2 \mathrm{d}p\_1 \int\_0^{\delta m-p\_1} p\_2^2 \mathrm{d}p\_2 \\
& \propto \int\_0^{\delta m/2} p\_1^2 \mathrm{d}p\_1 \left[ \frac{p\_2^3}{3}\right]\_{p\_2=0}^{\delta m-p\_1} \\
& \propto \int\_0^{\delta m/2} p\_1^2 \mathrm{d}p\_1 \frac{(\delta m - p\_1)^3}{3}
\end{array}
$$
which I am not going to bother finishing but shows that that phase space can vary as a high power of the mass difference (up to the sixth power in this case).
---
1 The lifetime of the state is inversely proportional to the probability | As you correctly state, the neutron decay is an decay due to the weak interaction, these are quite a bit slower than other decays due the mass of the
intermediate W boson, 81GeV, which slows the reaction, additionally the neutron decay only liberates a small amount of energy, around 1 MeV, it is the ratio of the liberated energy to the mass of the W which sets the speed of the reaction which is thus much slower than other decays as all the other particle decay release much more energy. |
31,514 | A neutron outside the nucleus lives for about 15 minutes and decays mainly through weak decays (beta decay). Many other weakly decaying particles decay with lifetimes between $10^{-10}$ and $10^{-12}$ seconds, which is consistent with $\alpha\_W \simeq 10^{-6}$.
Why does the neutron lives so much longer than the others? | 2012/07/07 | ['https://physics.stackexchange.com/questions/31514', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/1502/'] | NB: I feel like this is a pretty half-assed job, and I apologize for that but having opened my mouth in the comments I guess I have to write *something* to back it up.
---
We start with Fermi's golden rule for all transitions. The probability of the transition is
$$ P\_{i\to f} = \frac{2\pi}{\hbar} \left|M\_{i,f}\right|^2 \rho $$
where $\rho$ is the density of final states which is proportional to $p^2$ for massive particles. To find the rate1 for all possible final states we sum over these probabilities incoherently. When the mass difference between the initial and final states is much less than the $W$ mass the matrix element $M\_{i,f}$ depends only weakly (hah!) on the particular state and the sum is well approximated by a sum *only* over the density of states:
$$P\_\text{decay} \approx \frac{2\pi}{\hbar} \left|M\_{}\right|^2 \int\_\text{all outcomes} \rho .$$
This sum is collectively called the phase space available to the decay. In these cases the matrix element is also quite small for [the reason that Dr BDO discusses](https://physics.stackexchange.com/a/31526/520).
The phase space computation can be quite complicated as it must be taken over all unconstrained momenta of the products. For decays to two body states it turns out to be easy, there is no freedom in the final states except the $4\pi$ angular distribution in the decay frame (their are eight degrees of freedom in two 4-vectors, but 2 masses and the conservation of four momentum account for all of them except the azimuthal and polar angles of one of the particles).
The decays that you have asked about are to three body states. That gives us twelve degrees of freedom less three constraints from masses, four from conservation of 4-momentum which leaves five. Three of these are the Euler angles describing the orientation of the decay (and a factor of $8\pi^2$ to $\rho$), so our sum is over two non-trival momenta. The integral looks something like
$$
\begin{array}\\
\rho \propto \int p\_1^2 \mathrm{d}p\_1 \int p\_2^2 \mathrm{d}p\_2 \int \mathrm{d}(\cos\theta)
&\delta(m\_0 - E\_1 - E\_2-E\_3 ) \\
&\delta(E\_1^2 - m\_1^2 - p\_1^2) \\
&\delta(E\_2^2 - m\_2^2 - p\_2^2) \\
&\delta(E\_2^2 - m\_2^2 - p\_2^2) \\
&\delta(\vec{p}\_1 + \vec{p}\_2 + \vec{p}\_3)
\end{array}
$$
which is easier to compute in Monte Carlo than by hand. (BTW--the reason for introducing the seemingly redundant integral over the angle $\theta$ between the momenta of particles 1 and 2 will become evident in a little while).
For beta decays the remnant nucleus is very heavy compared to the released energy, [which simplifies the above in one limit](http://hyperphysics.phy-astr.gsu.edu/hbase/quantum/fermi2.html).
In the case of muon decay, it is not unreasonable to treat all the products as ultra-relativistic, and the above reduces to
$$
\begin{array}\\
\rho \propto \int p\_1^2 \mathrm{d}p\_1 \int p\_2^2 \mathrm{d}p\_2 \int \mathrm{d}(\cos\theta)
&\delta(m\_0 - E\_1 - E\_2 - E\_3 ) \\
&\delta(E\_1 - p\_1) \\
&\delta(E\_2 - p\_2) \\
&\delta(E\_3 - p\_3) \\
&\delta(\vec{p}\_1 + \vec{p}\_2 + \vec{p}\_3) \\
= \int p\_1^2 \mathrm{d}p\_1 \int p\_2^2 \mathrm{d}p\_2 \int \mathrm{d}(\cos\theta)
&\delta(m\_0 - p\_1 - p\_2 - p\_3 ) \\
&\delta(\vec{p}\_1 + \vec{p}\_2 + \vec{p}\_3) \\
= \int p\_1^2 \mathrm{d}p\_1 \int p\_2^2 \mathrm{d}p\_2 \int \mathrm{d}(\cos\theta)
&\delta(m\_0 - p\_1 - p\_2 - \left|\vec{p}\_1 + \vec{p}\_2\right| )\\
= \int p\_1^2 \mathrm{d}p\_1 \int p\_2^2 \mathrm{d}p\_2 \int \mathrm{d}(\cos\theta)
&\delta\left(m\_0 - p\_1 - p\_2 - \sqrt{p\_1^2 + p\_2^2 - p\_1p\_2\cos\theta} \right)
\end{array}
$$
The integral over the angle will evaluate to one in some regions and zero in others and as such is equivalent to correctly assigning the limits of the other two integrals, so writing $\delta m = m\_0 - m\_1 - m\_2 - m\_3$ we get
$$
\begin{array}
\rho
& \propto \int\_0^{\delta m/2} p\_1^2 \mathrm{d}p\_1 \int\_0^{\delta m-p\_1} p\_2^2 \mathrm{d}p\_2 \\
& \propto \int\_0^{\delta m/2} p\_1^2 \mathrm{d}p\_1 \left[ \frac{p\_2^3}{3}\right]\_{p\_2=0}^{\delta m-p\_1} \\
& \propto \int\_0^{\delta m/2} p\_1^2 \mathrm{d}p\_1 \frac{(\delta m - p\_1)^3}{3}
\end{array}
$$
which I am not going to bother finishing but shows that that phase space can vary as a high power of the mass difference (up to the sixth power in this case).
---
1 The lifetime of the state is inversely proportional to the probability | You can estimate the neutron lifetime using dimensional analysis. Beta decay is correctly described by the well known four-fermion Fermi theory, so the amplitude must be proportional to the coupling $G\_F\approx10^{-5}\text{GeV}^{-2}$ (the Fermi constant). The decay rate is proportional to the squared amplitude:
$$\Gamma\propto G\_F^2\thinspace.$$
$\Gamma$ has units of Mass while $G\_F^2$ has units of $[\text{Mass}]^{-4}$, so to get the units wright we must have
$$\Gamma\propto G\_F^2 \Delta^5$$
where $\Delta$ is some quantity that has units of mass. The relevant mass scale in neutron decay is the mass difference between neutron and proton, so $\Delta=m\_n-m\_p\approx10^{-3}\text{GeV}$.
To be a bitsy more accurate one can try guess the $\pi$ dependence of the decay rate. This comes from the phase space of a 3-body decay, which usually goes as
$$(2\pi)^4\times\Big[\thinspace(2\pi)^{-3}\times(2\pi)^{-3}\times(2\pi)^{-3}\Big]\times (\pi^2)\ \propto\ \pi^{-3}\thinspace.$$
The first factor comes from the four momenta conservation delta function, the three $(2\pi)^{-3}$ in the bracket come from the integration measure of the 4-momenta of each outgoing particle and the last factor comes from integrating the angle variables. One finally gets the following estimation
$$\Gamma\propto \frac{1}{\pi^3}G\_F^2(m\_n-m\_p)^5$$
If one plugs in all the numbers, the estimated lifetime of the neutron reads
$$\tau\_{\text{neutron}}\ =\ \Gamma^{-1}\ \approx\ \pi^3 \ \text{sec.}$$
This is a bit shorter than the real value which is at least one order of magnitude larger. But it explains why the neutron's lifetime is so large (inverse of the 5th power of the small mass difference) with respect to other weak decay processes. |
31,514 | A neutron outside the nucleus lives for about 15 minutes and decays mainly through weak decays (beta decay). Many other weakly decaying particles decay with lifetimes between $10^{-10}$ and $10^{-12}$ seconds, which is consistent with $\alpha\_W \simeq 10^{-6}$.
Why does the neutron lives so much longer than the others? | 2012/07/07 | ['https://physics.stackexchange.com/questions/31514', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/1502/'] | You can estimate the neutron lifetime using dimensional analysis. Beta decay is correctly described by the well known four-fermion Fermi theory, so the amplitude must be proportional to the coupling $G\_F\approx10^{-5}\text{GeV}^{-2}$ (the Fermi constant). The decay rate is proportional to the squared amplitude:
$$\Gamma\propto G\_F^2\thinspace.$$
$\Gamma$ has units of Mass while $G\_F^2$ has units of $[\text{Mass}]^{-4}$, so to get the units wright we must have
$$\Gamma\propto G\_F^2 \Delta^5$$
where $\Delta$ is some quantity that has units of mass. The relevant mass scale in neutron decay is the mass difference between neutron and proton, so $\Delta=m\_n-m\_p\approx10^{-3}\text{GeV}$.
To be a bitsy more accurate one can try guess the $\pi$ dependence of the decay rate. This comes from the phase space of a 3-body decay, which usually goes as
$$(2\pi)^4\times\Big[\thinspace(2\pi)^{-3}\times(2\pi)^{-3}\times(2\pi)^{-3}\Big]\times (\pi^2)\ \propto\ \pi^{-3}\thinspace.$$
The first factor comes from the four momenta conservation delta function, the three $(2\pi)^{-3}$ in the bracket come from the integration measure of the 4-momenta of each outgoing particle and the last factor comes from integrating the angle variables. One finally gets the following estimation
$$\Gamma\propto \frac{1}{\pi^3}G\_F^2(m\_n-m\_p)^5$$
If one plugs in all the numbers, the estimated lifetime of the neutron reads
$$\tau\_{\text{neutron}}\ =\ \Gamma^{-1}\ \approx\ \pi^3 \ \text{sec.}$$
This is a bit shorter than the real value which is at least one order of magnitude larger. But it explains why the neutron's lifetime is so large (inverse of the 5th power of the small mass difference) with respect to other weak decay processes. | As you correctly state, the neutron decay is an decay due to the weak interaction, these are quite a bit slower than other decays due the mass of the
intermediate W boson, 81GeV, which slows the reaction, additionally the neutron decay only liberates a small amount of energy, around 1 MeV, it is the ratio of the liberated energy to the mass of the W which sets the speed of the reaction which is thus much slower than other decays as all the other particle decay release much more energy. |
160,714 | I have 2 numbers in 2 columns. I am trying to get ranges of numbers between those two numbers.
For example, when I have 1330 in 1st column and 1335 in second column, I want this result:
```
1330
1331
1332
1333
1334
1335
```
My spreadsheet: [Range of number between two number google sheet](https://docs.google.com/spreadsheets/d/1xxClDPq96Ghg09gfzz4RSCQDeShVa9EgRwLkwReMMNY/edit?usp=sharing). | 2021/12/13 | ['https://webapps.stackexchange.com/questions/160714', 'https://webapps.stackexchange.com', 'https://webapps.stackexchange.com/users/276710/'] | I wouldn't recommend placing your formula *below* your raw data columns, because it would prevent your raw data in Columns A and B from expanding downward. Instead place your results off to the right somewhere (or in another sheet).
That said, based on the data in your sample spreadsheet, try first deleting everything from A7 down. Then place the following single formula in, say, cell D3:
`=ArrayFormula(QUERY(FLATTEN(IF(A3:A="",,IF(A3:A+SEQUENCE(1,10,0)>IF(B3:B="",A3:A,B3:B),,A3:A+SEQUENCE(1,10,0)))),"Select * WHERE Col1 Is Not Null"))`
This will produce all results.
If your range between the number in Col-A and the number in Col-B will ever exceed 10, just change the two instances of `10` in the formula to a number that exceeds the max range that may occur between the two columns.
If you want to use this formula in a separate sheet of the spreadsheet, just be sure to prefix `Sheet1!` to the front of each range shown in the formula (e.g., `Sheet1!A3:A`, etc.). | You can get the sequence `1330 1331 1332 1333 1334 1335` like this:
`=iferror( sequence(1, B3 - A3 + 1, A3), A3 )`
Put that in cell `D3` and copy the cell down to `D3:D6`. The use this formula to get the final list:
`=query( flatten(D3:I6), "where Col1 is not null", 0 )` |
699,971 | I used to use `overlayroot-chroot` in Ubuntu:
<http://manpages.ubuntu.com/manpages/bionic/man8/overlayroot-chroot.8.html>
But now that I have changed to Debian it is not there, and `sudo apt install overlayroot-chroot` does not find it.
How does one get it for Debian? | 2022/04/22 | ['https://unix.stackexchange.com/questions/699971', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/358674/'] | You say, "... on my network ..."
If you have access to the physical network layer, then yes, it is possible.
Some managed switches have the ability to copy traffic destined for port X to Port Y.
Another possibility, if the `tcpdump` host has multiple NICs, is to put the `tcpdump` host in between the other two hosts and let it bridge the traffic. | Solution found probably.
The syntax is correct, but modern switched networks (unlike the older with shared bus like the old good 10base2 or base5) don't send traffic out the switch port
not connected to the destination MAC address, so tcpdump will show packets only from host connected directly. |
18,804 | First - this is a question directed towards advanced practitioners of mindfulness or similar meditation.
I have been meditating and practicing other transformational work for about 17 years. Throughout the work, I've had many peak experiences, many "aha" moments, and I've experienced the deepening and expansiveness of my awareness and understanding.
I've learned to be suspicious of any type of insight or experience that presents itself as "the answer" - in other words; I've had thoughts like "this is finally it! I got it!" So many times that I pretty much ignore that type of noise as soon as notice it.
Lately while meditating, I've become increasingly aware of physical sensations (neither pleasant or unpleasant) in my body, particularly around my upper chakras; and the overall - for lack of a better word - intensity of my experience is elevated.
As I allude to - I've never had a transformational experience that I considered "real" that came about with a bang - the worthwhile experiences are usually quite subtle - if fact my sense is that the essence of transformation is increasingly subtle rather than the other way around.
My question is, what do I make of my recent experiences? It carries with it an intensity that seems well, intense.
I recognize that more information is probably necessary to answer this; but in general terms, is this par for the course? Is it just something to notice, and let pass? Is it a symptom of something and/or, is there anything to do about it? | 2017/01/05 | ['https://buddhism.stackexchange.com/questions/18804', 'https://buddhism.stackexchange.com', 'https://buddhism.stackexchange.com/users/315/'] | In meditation you get experience [Pīti](https://en.wikipedia.org/wiki/P%C4%ABti), [Sukha](https://en.wikipedia.org/wiki/Sukha), [Passaddhi](https://en.wikipedia.org/wiki/Passaddhi) which can be intense, pleasant and stubtle. If you dwell on these too much you get attached to them and crave to them, causing regression in your meditation. Also if you think this is the final goal you stop short half way.
So do not give much importance to them and continue your practice.
Also see: [That "Electric Feel" body sensation during meditation](https://buddhism.stackexchange.com/questions/3471) | The title and the question are a little different, but I'll try to address both. I think of meditation as a way to practice paying attention. When I meditate, I try to focus more on paying attention and less on whether the experience matches my expectations.
Asking "What to expect from meditation?" is kind of like asking, "What should I expect what I stand outside and listen?". If you pay attention, you may notice things. What you notice will depend on your own circumstances. Some times nothing may seem to happen; other times, you may notice something dramatic.
An idea you may hear about in Buddhism is taking refuge in the Three Jewels: the Buddha, the Dharma, and the Sangha. In addition to asking questions here, if you're curious about the sensations you notice in meditation, you might consider seeking out a Sangha where you can share your experiences with others in a more intimate way than you can on an Internet site. I think a Sangha will often have a teacher who can help you investigate what you notice in meditation. |
18,804 | First - this is a question directed towards advanced practitioners of mindfulness or similar meditation.
I have been meditating and practicing other transformational work for about 17 years. Throughout the work, I've had many peak experiences, many "aha" moments, and I've experienced the deepening and expansiveness of my awareness and understanding.
I've learned to be suspicious of any type of insight or experience that presents itself as "the answer" - in other words; I've had thoughts like "this is finally it! I got it!" So many times that I pretty much ignore that type of noise as soon as notice it.
Lately while meditating, I've become increasingly aware of physical sensations (neither pleasant or unpleasant) in my body, particularly around my upper chakras; and the overall - for lack of a better word - intensity of my experience is elevated.
As I allude to - I've never had a transformational experience that I considered "real" that came about with a bang - the worthwhile experiences are usually quite subtle - if fact my sense is that the essence of transformation is increasingly subtle rather than the other way around.
My question is, what do I make of my recent experiences? It carries with it an intensity that seems well, intense.
I recognize that more information is probably necessary to answer this; but in general terms, is this par for the course? Is it just something to notice, and let pass? Is it a symptom of something and/or, is there anything to do about it? | 2017/01/05 | ['https://buddhism.stackexchange.com/questions/18804', 'https://buddhism.stackexchange.com', 'https://buddhism.stackexchange.com/users/315/'] | >
> Is it just something to notice, and let pass? Is it a symptom of something and/or, is there anything to do about it?
>
>
>
Treat the object according to your practice, i.e. for
Samatha meditation:
* when mind wanders, bring it back to the breath.
Vipassana meditation:
* every object is treated in the same way, there is no discrimination, i.e. no object is more or less important than the other. Note the object and return to the rising and falling of the abdomen. | The title and the question are a little different, but I'll try to address both. I think of meditation as a way to practice paying attention. When I meditate, I try to focus more on paying attention and less on whether the experience matches my expectations.
Asking "What to expect from meditation?" is kind of like asking, "What should I expect what I stand outside and listen?". If you pay attention, you may notice things. What you notice will depend on your own circumstances. Some times nothing may seem to happen; other times, you may notice something dramatic.
An idea you may hear about in Buddhism is taking refuge in the Three Jewels: the Buddha, the Dharma, and the Sangha. In addition to asking questions here, if you're curious about the sensations you notice in meditation, you might consider seeking out a Sangha where you can share your experiences with others in a more intimate way than you can on an Internet site. I think a Sangha will often have a teacher who can help you investigate what you notice in meditation. |
18,804 | First - this is a question directed towards advanced practitioners of mindfulness or similar meditation.
I have been meditating and practicing other transformational work for about 17 years. Throughout the work, I've had many peak experiences, many "aha" moments, and I've experienced the deepening and expansiveness of my awareness and understanding.
I've learned to be suspicious of any type of insight or experience that presents itself as "the answer" - in other words; I've had thoughts like "this is finally it! I got it!" So many times that I pretty much ignore that type of noise as soon as notice it.
Lately while meditating, I've become increasingly aware of physical sensations (neither pleasant or unpleasant) in my body, particularly around my upper chakras; and the overall - for lack of a better word - intensity of my experience is elevated.
As I allude to - I've never had a transformational experience that I considered "real" that came about with a bang - the worthwhile experiences are usually quite subtle - if fact my sense is that the essence of transformation is increasingly subtle rather than the other way around.
My question is, what do I make of my recent experiences? It carries with it an intensity that seems well, intense.
I recognize that more information is probably necessary to answer this; but in general terms, is this par for the course? Is it just something to notice, and let pass? Is it a symptom of something and/or, is there anything to do about it? | 2017/01/05 | ['https://buddhism.stackexchange.com/questions/18804', 'https://buddhism.stackexchange.com', 'https://buddhism.stackexchange.com/users/315/'] | In meditation, you can consider these three:
1. Mental factors that you cultivate, a bit like a sportsman. For instance, mindfulness, alertness and concentration.
2. Experiences of yours (that are also mental factors, in fact) that indicate something about the quality of your mind. For instance, Prasrabhi indicate the achievement of śamatha. Each dhyāna has its branches as well. In this respect, each branch indicate something about the quality of one's mind. For instance, if you abide in neither-pleasure-nor-pain, it shows you abide in the fourth dhyāna.
3. The objects you pay attention to. This is because the purpose of meditation is to get to open one's eyes so as to see things the way they are. Another way of saying is that the purpose is to directly realize the sixteen aspects of the four noble truths.
Ṭhānissaro Bhikkhu and others point out that samatha and vipassana are aspects of the same practice ("practicing dhyānas"). It is impossible to achieve even calm abiding without having contentment, few desire, and ethical discipline, and these three do not come about without a good deal of understanding to start with. Such an understanding comes about through studying, listening to the teachings, and engaging in vipassana. Without understanding, one's practice of samatha will be forceful, fruitless and might even be harmful. In turn, whatever one gets to see with a still and clear might will be more beneficial.
What you experience might indicate the quality of your mind. Either way, you have to get clearer about it, to know what to do with it. | The title and the question are a little different, but I'll try to address both. I think of meditation as a way to practice paying attention. When I meditate, I try to focus more on paying attention and less on whether the experience matches my expectations.
Asking "What to expect from meditation?" is kind of like asking, "What should I expect what I stand outside and listen?". If you pay attention, you may notice things. What you notice will depend on your own circumstances. Some times nothing may seem to happen; other times, you may notice something dramatic.
An idea you may hear about in Buddhism is taking refuge in the Three Jewels: the Buddha, the Dharma, and the Sangha. In addition to asking questions here, if you're curious about the sensations you notice in meditation, you might consider seeking out a Sangha where you can share your experiences with others in a more intimate way than you can on an Internet site. I think a Sangha will often have a teacher who can help you investigate what you notice in meditation. |
65,195,952 | I created this data frame:
```
Count <- c(1:10)
Give <- c(0,0,5,0,0,5,0,5,0,5)
X <- c(rep(0,10))
Y <- c(rep(0,10))
Z <- c(rep(0,10))
X_Target <- 5
Y_Target <- 10
Z_Target <- 5
```
Basically I have 3 vectors (X,Y,Z) and a target for each one of them.
I want to have a new calculation for X,Y and Z that based on the vector Give.
Once the number on Give is bigger than 0 then it's need to be added to Vector X until it equel to X\_Target. Then - the calcultion need to move to the next vector (Y) and do the same, and then to next vector...
The output should be like the following:
```
Count Give X Y Z
1 0 0 0 0
2 0 0 0 0
3 5 5 0 0
4 0 5 0 0
5 0 5 0 0
6 5 5 5 0
7 0 5 5 0
8 5 5 10 0
9 0 5 10 0
10 5 5 10 5
```
In this example I have only 3 vectors but please keep in mind that I'll have at least 60 vectors so I need it to be automatic as it can.
Hope I manage to explain myself :)
Thnanks! | 2020/12/08 | ['https://Stackoverflow.com/questions/65195952', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14686993/'] | A `string` is not a single `rune`, it may contain multiple `runes`. You may use a simple type [conversion](https://golang.org/ref/spec#Conversions) to convert a `string` to a `[]runes` containing all its runes like `[]rune(sample)`.
The `for range` iterates over the runes of a `string`, so in your example `runeValue` is of type `rune`, you may use it in your `converter` map, e.g.:
```
var converter = map[rune]rune{}
sample := "⌘こんにちは"
for _, runeValue := range sample {
converter[runeValue] = runeValue
}
fmt.Println(converter)
```
But since `rune` is an alias for `int32`, printing the above `converter` map will print integer numbers, output will be:
```
map[8984:8984 12371:12371 12385:12385 12395:12395 12399:12399 12435:12435]
```
If you want to print characters, use the `%c` verb of [`fmt.Printf()`](https://golang.org/pkg/fmt/#Printf):
```
fmt.Printf("%c\n", converter)
```
Which will output:
```
map[⌘:⌘ こ:こ ち:ち に:に は:は ん:ん]
```
Try the examples on the [Go Playground](https://play.golang.org/p/1O2hH3SnPFv).
If you want to replace (switch) certain runes in a `string`, use the [`strings.Map()`](https://golang.org/pkg/strings/#Map) function, for example:
```
sample := "⌘こんにちは"
result := strings.Map(func(r rune) rune {
if r == '⌘' {
return 'a'
}
if r == 'こ' {
return 'b'
}
return r
}, sample)
fmt.Println(result)
```
Which outputs (try it on the [Go Playground](https://play.golang.org/p/w2CTVJu9jgL)):
```
abんにちは
```
If you want the replacements defined by a `converter` map:
```
var converter = map[rune]rune{
'⌘': 'a',
'こ': 'b',
}
sample := "⌘こんにちは"
result := strings.Map(func(r rune) rune {
if c, ok := converter[r]; ok {
return c
}
return r
}, sample)
fmt.Println(result)
```
This outputs the same. Try this one on the [Go Playground](https://play.golang.org/p/ra-skPc0s_3). | Convert string to rune array:
`runeArray := []rune("пример")` |
16,086,943 | According this [answer](https://stackoverflow.com/a/1570909/240564), it should be option "include files from the App\_data folder" when you publish ASP.NET application. But I don't see it:

Where it is? | 2013/04/18 | ['https://Stackoverflow.com/questions/16086943', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/240564/'] | I don't believe that option is in the newest of Visual Studio.
Instead, you should be able to change the Build Action to "Content" by right-clicking on the files in Solution Explorer and clicking "Properties."
This should then include them in the publishing process. | I used a After Build Target. To just create a empty folder on deploy.
Add this to the end of The project file .csproj
```
<Target Name="CreateDirectories" AfterTargets="GatherAllFilesToPublish">
<MakeDir Directories="$(OutputPath)App_Data\"/>
</Target>
``` |
16,086,943 | According this [answer](https://stackoverflow.com/a/1570909/240564), it should be option "include files from the App\_data folder" when you publish ASP.NET application. But I don't see it:

Where it is? | 2013/04/18 | ['https://Stackoverflow.com/questions/16086943', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/240564/'] | I don't believe that option is in the newest of Visual Studio.
Instead, you should be able to change the Build Action to "Content" by right-clicking on the files in Solution Explorer and clicking "Properties."
This should then include them in the publishing process. | 1. Manually Create the App\_Data folder under the published application's root folder
2. Right click at the App\_Data folder and select **Publish App\_Data folder**.
3. Add an item into the App\_Data folder and set the item to be include in the publish.
<https://forums.asp.net/t/2126248.aspx?App_Data+folder+missing+in+release> |
16,086,943 | According this [answer](https://stackoverflow.com/a/1570909/240564), it should be option "include files from the App\_data folder" when you publish ASP.NET application. But I don't see it:

Where it is? | 2013/04/18 | ['https://Stackoverflow.com/questions/16086943', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/240564/'] | I used a After Build Target. To just create a empty folder on deploy.
Add this to the end of The project file .csproj
```
<Target Name="CreateDirectories" AfterTargets="GatherAllFilesToPublish">
<MakeDir Directories="$(OutputPath)App_Data\"/>
</Target>
``` | 1. Manually Create the App\_Data folder under the published application's root folder
2. Right click at the App\_Data folder and select **Publish App\_Data folder**.
3. Add an item into the App\_Data folder and set the item to be include in the publish.
<https://forums.asp.net/t/2126248.aspx?App_Data+folder+missing+in+release> |
5,397,598 | a need how convert string value in field name valid:
Example:
>
> <%="price.list\_"+current\_user.price.to\_s%>
>
>
>
so
>
> price.list\_1
>
>
>
then is my real field name. this name.this field will use it to do more operations in my view. | 2011/03/22 | ['https://Stackoverflow.com/questions/5397598', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/546530/'] | I think I understood your question. You will need to use the send function
```
<%= price.send("list_#{current_user.price}".to_sym) %>
``` | That should work but you can also do
```
<%= "price.list_#{current_user.price.to_s}" %>
```
**OR**
```
<p>
price.list_<%= current_user.price.to_s %>
</p>
```
**UPDATE:** I misunderstood the question. This is going to require some Javascript or AJAX, depending on your exact application.
**JS:**
```
:onchange => 'update(this.value)'
function update(new_value) {
var update_me = document.getElementById('update_this_field');
update_me.value = new_value;
}
```
**AJAX on RAILS**
```
:onchange => remote_function(:url => {:action => 'update'}, :with => 'Form.element.serialize(this)'), :name => 'foo'
def update
bar = params[:foo]
render :update do |page|
page.replace_html 'update_this_field', "price.list_" + bar
end
end
``` |
721,705 | The following snippet draws a gray square.
```
glColor3b(50, 50, 50);
glBegin(GL_QUADS);
glVertex3f(-1.0, +1.0, 0.0); // top left
glVertex3f(-1.0, -1.0, 0.0); // bottom left
glVertex3f(+1.0, -1.0, 0.0); // bottom right
glVertex3f(+1.0, +1.0, 0.0); // top right
glEnd();
```
In my application, behind this single square exists a colored cube.
What function should I use to make square (and only this square) opaque? | 2009/04/06 | ['https://Stackoverflow.com/questions/721705', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/47775/'] | glColor4f(float r,float g, float b, flaot alpha);
(in your case maybe clColor4b)
also make sure, that blending is enabled.
(you have to reset the color to non-alpha afterwads, which might involve a glGet\* to save the old vertexcolor) | Use `glColor4` instead of `glColor3`. For example:
```
glBlendFunc(GL_SRC_ALPHA,GL_ONE);
glColor4f(1.0f,1.0f,1.0f,0.5f);
``` |
721,705 | The following snippet draws a gray square.
```
glColor3b(50, 50, 50);
glBegin(GL_QUADS);
glVertex3f(-1.0, +1.0, 0.0); // top left
glVertex3f(-1.0, -1.0, 0.0); // bottom left
glVertex3f(+1.0, -1.0, 0.0); // bottom right
glVertex3f(+1.0, +1.0, 0.0); // top right
glEnd();
```
In my application, behind this single square exists a colored cube.
What function should I use to make square (and only this square) opaque? | 2009/04/06 | ['https://Stackoverflow.com/questions/721705', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/47775/'] | In the init function, use these two lines:
```
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
```
And in your render function, ensure that `glColor4f` is used instead of `glColor3f`, and set the 4th argument to the level of opacity required.
```
glColor4f(1.0, 1.0, 1.0, 0.5);
glBegin(GL_QUADS);
glVertex3f(-1.0, +1.0, 0.0); // top left
glVertex3f(-1.0, -1.0, 0.0); // bottom left
glVertex3f(+1.0, -1.0, 0.0); // bottom right
glVertex3f(+1.0, +1.0, 0.0); // top right
glEnd();
``` | glColor4f(float r,float g, float b, flaot alpha);
(in your case maybe clColor4b)
also make sure, that blending is enabled.
(you have to reset the color to non-alpha afterwads, which might involve a glGet\* to save the old vertexcolor) |
721,705 | The following snippet draws a gray square.
```
glColor3b(50, 50, 50);
glBegin(GL_QUADS);
glVertex3f(-1.0, +1.0, 0.0); // top left
glVertex3f(-1.0, -1.0, 0.0); // bottom left
glVertex3f(+1.0, -1.0, 0.0); // bottom right
glVertex3f(+1.0, +1.0, 0.0); // top right
glEnd();
```
In my application, behind this single square exists a colored cube.
What function should I use to make square (and only this square) opaque? | 2009/04/06 | ['https://Stackoverflow.com/questions/721705', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/47775/'] | You can set colors per vertex
```
glBegin(GL_QUADS);
glColor4f(1.0, 0.0, 0.0, 0.5); // red, 50% alpha
glVertex3f(-1.0, +1.0, 0.0); // top left
// Make sure to set the color back since the color state persists
glVertex3f(-1.0, -1.0, 0.0); // bottom left
glVertex3f(+1.0, -1.0, 0.0); // bottom right
glVertex3f(+1.0, +1.0, 0.0); // top right
glEnd();
``` | Use `glColor4` instead of `glColor3`. For example:
```
glBlendFunc(GL_SRC_ALPHA,GL_ONE);
glColor4f(1.0f,1.0f,1.0f,0.5f);
``` |
721,705 | The following snippet draws a gray square.
```
glColor3b(50, 50, 50);
glBegin(GL_QUADS);
glVertex3f(-1.0, +1.0, 0.0); // top left
glVertex3f(-1.0, -1.0, 0.0); // bottom left
glVertex3f(+1.0, -1.0, 0.0); // bottom right
glVertex3f(+1.0, +1.0, 0.0); // top right
glEnd();
```
In my application, behind this single square exists a colored cube.
What function should I use to make square (and only this square) opaque? | 2009/04/06 | ['https://Stackoverflow.com/questions/721705', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/47775/'] | In the init function, use these two lines:
```
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
```
And in your render function, ensure that `glColor4f` is used instead of `glColor3f`, and set the 4th argument to the level of opacity required.
```
glColor4f(1.0, 1.0, 1.0, 0.5);
glBegin(GL_QUADS);
glVertex3f(-1.0, +1.0, 0.0); // top left
glVertex3f(-1.0, -1.0, 0.0); // bottom left
glVertex3f(+1.0, -1.0, 0.0); // bottom right
glVertex3f(+1.0, +1.0, 0.0); // top right
glEnd();
``` | Use `glColor4` instead of `glColor3`. For example:
```
glBlendFunc(GL_SRC_ALPHA,GL_ONE);
glColor4f(1.0f,1.0f,1.0f,0.5f);
``` |
721,705 | The following snippet draws a gray square.
```
glColor3b(50, 50, 50);
glBegin(GL_QUADS);
glVertex3f(-1.0, +1.0, 0.0); // top left
glVertex3f(-1.0, -1.0, 0.0); // bottom left
glVertex3f(+1.0, -1.0, 0.0); // bottom right
glVertex3f(+1.0, +1.0, 0.0); // top right
glEnd();
```
In my application, behind this single square exists a colored cube.
What function should I use to make square (and only this square) opaque? | 2009/04/06 | ['https://Stackoverflow.com/questions/721705', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/47775/'] | In the init function, use these two lines:
```
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
```
And in your render function, ensure that `glColor4f` is used instead of `glColor3f`, and set the 4th argument to the level of opacity required.
```
glColor4f(1.0, 1.0, 1.0, 0.5);
glBegin(GL_QUADS);
glVertex3f(-1.0, +1.0, 0.0); // top left
glVertex3f(-1.0, -1.0, 0.0); // bottom left
glVertex3f(+1.0, -1.0, 0.0); // bottom right
glVertex3f(+1.0, +1.0, 0.0); // top right
glEnd();
``` | You can set colors per vertex
```
glBegin(GL_QUADS);
glColor4f(1.0, 0.0, 0.0, 0.5); // red, 50% alpha
glVertex3f(-1.0, +1.0, 0.0); // top left
// Make sure to set the color back since the color state persists
glVertex3f(-1.0, -1.0, 0.0); // bottom left
glVertex3f(+1.0, -1.0, 0.0); // bottom right
glVertex3f(+1.0, +1.0, 0.0); // top right
glEnd();
``` |
1,051,688 | Let's say I have two custom headers, `foo` and `bar` that contribute to the uniqueness of a REST query, how can I configure nginx to include these in its cache key?
For example we these queries that hit the same url but should be cached differently given their headers:
```
wget --header=foo:1 --header=bar:A http://my.web.site/api/query
wget --header=foo:1 --header=bar:B http://my.web.site/api/query
wget --header=foo:2 --header=bar:A http://my.web.site/api/query
wget --header=foo:2 --header=bar:B http://my.web.site/api/query
``` | 2021/01/29 | ['https://serverfault.com/questions/1051688', 'https://serverfault.com', 'https://serverfault.com/users/679/'] | Ok, so with help of [@Praveen Premaratne](https://serverfault.com/users/446078/praveen-premaratne) and [@Piotr P. Karwasz](https://serverfault.com/users/530633/piotr-p-karwasz) and this [article](http://dev.joget.org/community/display/DX7/NGINX+as+Proxy+to+Tomcat) I came up with following configuration:
>
> don't put in lines with "# managed by Certbot", those are created by certbot, check <https://www.digitalocean.com/community/tutorials/how-to-secure-nginx-with-let-s-encrypt-on-ubuntu-18-04>
>
>
>
**etc/nginx/sites-available/mydomain.com**
```
server {
server_name mydomain.com www.mydomain.com;
root /var/www/mydomain.com;
index index.html;
access_log /var/log/nginx/mydomain-access.log;
error_log /var/log/nginx/mydomain-error.log;
location / {
try_files $uri $uri/ /index.html;
}
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/www.mydomain.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/www.mydomain.com/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}
server {
if ($host = www.mydomain.com) {
return 301 https://$host$request_uri;
} # managed by Certbot
if ($host = mydomain.com) {
return 301 https://$host$request_uri;
} # managed by Certbot
server_name mydomain.com www.mydomain.com;
listen 80;
return 404; # managed by Certbot
}
```
**/etc/nginx/sites-available/api.mydomain.com**
```
server {
server_name api.mydomain.com;
access_log /var/log/nginx/api-mydomain-access.log;
error_log /var/log/nginx/api-mydomain-error.log;
location / {
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Host $http_host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_pass http://127.0.0.1:8080;
}
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/www.mydomain.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/www.mydomain.com/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}
server {
if ($host = api.mydomain.com) {
return 301 https://$host$request_uri;
} # managed by Certbot
server_name api.mydomain.com;
listen 80;
return 404; # managed by Certbot
}
```
**Tomcat server.xml**
```
<Service name="Catalina">
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
address="127.0.0.1"
proxyName="api.mydomain.com"
proxyPort="80"/>
<Engine name="Catalina" defaultHost="localhost">
<Realm className="org.apache.catalina.realm.LockOutRealm">
...
</Realm>
<Host name="localhost" appBase="webapps"
unpackWARs="true" autoDeploy="true">
<Valve className="org.apache.catalina.valves.RemoteIpValve"
remoteIpHeader="x-forwarded-for"
proxiesHeader="x-forwarded-by"
protocolHeader="x-forwarded-proto" />
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
prefix="localhost_access_log" suffix=".txt"
pattern="%h %l %u %t %r %s %b" />
</Host>
</Engine>
``` | Try this:
```
location / {
try_files $uri @backend;
}
location @backend {
include proxy_params;
proxy_pass http://tomcat;
}
``` |
1,051,688 | Let's say I have two custom headers, `foo` and `bar` that contribute to the uniqueness of a REST query, how can I configure nginx to include these in its cache key?
For example we these queries that hit the same url but should be cached differently given their headers:
```
wget --header=foo:1 --header=bar:A http://my.web.site/api/query
wget --header=foo:1 --header=bar:B http://my.web.site/api/query
wget --header=foo:2 --header=bar:A http://my.web.site/api/query
wget --header=foo:2 --header=bar:B http://my.web.site/api/query
``` | 2021/01/29 | ['https://serverfault.com/questions/1051688', 'https://serverfault.com', 'https://serverfault.com/users/679/'] | Ok, so with help of [@Praveen Premaratne](https://serverfault.com/users/446078/praveen-premaratne) and [@Piotr P. Karwasz](https://serverfault.com/users/530633/piotr-p-karwasz) and this [article](http://dev.joget.org/community/display/DX7/NGINX+as+Proxy+to+Tomcat) I came up with following configuration:
>
> don't put in lines with "# managed by Certbot", those are created by certbot, check <https://www.digitalocean.com/community/tutorials/how-to-secure-nginx-with-let-s-encrypt-on-ubuntu-18-04>
>
>
>
**etc/nginx/sites-available/mydomain.com**
```
server {
server_name mydomain.com www.mydomain.com;
root /var/www/mydomain.com;
index index.html;
access_log /var/log/nginx/mydomain-access.log;
error_log /var/log/nginx/mydomain-error.log;
location / {
try_files $uri $uri/ /index.html;
}
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/www.mydomain.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/www.mydomain.com/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}
server {
if ($host = www.mydomain.com) {
return 301 https://$host$request_uri;
} # managed by Certbot
if ($host = mydomain.com) {
return 301 https://$host$request_uri;
} # managed by Certbot
server_name mydomain.com www.mydomain.com;
listen 80;
return 404; # managed by Certbot
}
```
**/etc/nginx/sites-available/api.mydomain.com**
```
server {
server_name api.mydomain.com;
access_log /var/log/nginx/api-mydomain-access.log;
error_log /var/log/nginx/api-mydomain-error.log;
location / {
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Host $http_host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_pass http://127.0.0.1:8080;
}
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/www.mydomain.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/www.mydomain.com/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}
server {
if ($host = api.mydomain.com) {
return 301 https://$host$request_uri;
} # managed by Certbot
server_name api.mydomain.com;
listen 80;
return 404; # managed by Certbot
}
```
**Tomcat server.xml**
```
<Service name="Catalina">
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
address="127.0.0.1"
proxyName="api.mydomain.com"
proxyPort="80"/>
<Engine name="Catalina" defaultHost="localhost">
<Realm className="org.apache.catalina.realm.LockOutRealm">
...
</Realm>
<Host name="localhost" appBase="webapps"
unpackWARs="true" autoDeploy="true">
<Valve className="org.apache.catalina.valves.RemoteIpValve"
remoteIpHeader="x-forwarded-for"
proxiesHeader="x-forwarded-by"
protocolHeader="x-forwarded-proto" />
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
prefix="localhost_access_log" suffix=".txt"
pattern="%h %l %u %t %r %s %b" />
</Host>
</Engine>
``` | If I were to do this using the subdomains approach here's how I would do it.
* Create an Nginx configuration file for the backend API
* Create an Nginx configuration file for the static web content
>
> Static HTML Nginx file `mydomain.com.nginx`
>
>
>
```
server {
server_name mydomain.com;
root /var/www/mydomain.com;
index index.html;
access_log /var/log/nginx/mydomain-access.log;
error_log /var/log/nginx/mydomain-error.log;
location / {
try_files $uri $uri/ /index.html;
}
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/www.mydomain.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/www.mydomain.com/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}
server {
if ($host = mydomain.com) {
return 301 https://$host$request_uri;
} # managed by Certbot
listen 80;
server_name mydomain.com;
return 404; # managed by Certbot
}
```
>
> API Nginx config file `api.mydomain.com.nginx`
>
>
>
```
server {
server_name api.mydomain.com;
access_log /var/log/nginx/api-mydomain-access.log;
error_log /var/log/nginx/api-mydomain-error.log;
location / {
proxy_set_header X-Forwarded-Host $host:$server_port;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://127.0.0.1:8080;
proxy_redirect off;
}
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/api.mydomain.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/api.mydomain.com/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}
server {
if ($host = api.mydomain.com) {
return 301 https://$host$request_uri;
} # managed by Certbot
listen 80;
server_name app.mydomain.com;
return 404; # managed by Certbot
}
```
You can add these to the `/etc/nginx/site-available/` directory and enable them.
*Ps: I would remove the SSL stuff and run Certbot to update them since you've to issue a new certificate for the **app.mydomain.com**, so it would just update the files itself* |
21,241,073 | I'm using the gon gem for rails, which allows you to save variables defined in a controller action and use them in your JavaScript. It works fine when I use it in non-Ajax settings, however, I'm having an issue with using it successfully when doing Ajax requests.
**The problem**: Ruby variables I assign to gon variables in the controller action when making Ajax requests come out as 'undefined' in the JavaScript.
**The objective**: I want to trigger an Ajax request on my page, which:
1) hits an action in the controller, and assigns a Ruby variable to a gon variable.
2) it then renders a js.erb file which executes JavaScript, part of which needs to take the Ruby variable defined in step 1, and treat it as a js variable.
**here's the example action in step 1**:
```
def some_action
gon.my_ajax_var = {some: 'info'}
end
```
**here's the example js.erb file it renders:**
```
/some_action.js.erb
console.log('gon.my_ajax_var equals ' + gon.my_ajax_var) //this doesn't work! comes out as 'undefined' when I expected {some: 'info'}
```
Any thoughts on how I fix this? I took a look at the gon.watch page, but I was confused as to whether that relates to this problem I'm having and how to implement the correct solution. Additionally, if there's a better way to do this without gon, I'm open to that as well.
Thanks! | 2014/01/20 | ['https://Stackoverflow.com/questions/21241073', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1908400/'] | I ended up solving this by doing the following:
**In my controller:**
```
def some_action
@my_ajax_var = {some: 'info'}.to_json
end
```
**In my corresponding view:**
/some\_action.js.erb
```
var my_ajax_var = <%= @my_ajax_var.html_safe %>
```
Would've been nice to have piggybacked off the gon gem, but this got the job done. | It's some time ago that I used erb templates, but I think you need to add tags in your erb-file.
```
/some_action.js.erb
console.log('gon.my_ajax_var equals ' + <%= gon.my_ajax_var %>)
``` |
12,280,600 | I'm having trouble with calling a system command from Java. I've tried the following:
```
if (!found) {
dbContents += ";" + getPreviousValue(i, dbContents);
try {
String cmd = "echo \"Device " + headers[i] + " no data incoming at " + timeString + "\" >> /home/envir/11/log.txt";
Runtime.getRuntime().exec(cmd);
Console.out("N");
}
catch(IOException ioe) {
System.out.println(ioe);
}
```
The thing is that the file "log.txt" is never created whatsoever. I've checked whether the if clause is ever executed or not, and i can see that the message
```
Console.out("N");
```
DOES appear, so i don't know why the 2 previous lines of code don't.
Here is the evidence that the "N" is printed:

I must say that this is the first time I use this stuff of calling a system command from a java file, so maybe this can more than probably be a newbie error.
I'd really appreciate if anyone has an answer for this.
Thanks in advance. | 2012/09/05 | ['https://Stackoverflow.com/questions/12280600', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1452989/'] | It is likely your command is failing. Any error message is send to the Process.getErrorStream() which you are ignoring so you can't see it.
In your case, if all you want to do append to a log file, the best way to do this is in Java. It is faster, cleaner and more likely to work.
```
PrintWriter pw = new PrintWriter(new FileWriter("/home/envir/11/log.txt", true));
pw.println("Device " + headers[i] + " no data incoming at " + timeString);
pw.close();
```
The problem could be that "echo" is not a program on your system. If you are running a shell, it will have commands which are only available when that shell in running.
BTW `>>` is a syntax only shells understand as well. | Maybe your file is not created because the redirection (">>") is not evaluated.
Try to wrap your call like this :
```
String cmd = "sh -c \"echo \\\"Device " + headers[i] + " no data incoming at " + timeString + "\\\" >> /home/envir/11/log.txt\"";
```
Anyway, why don't you use something like a FileWritter ? |
59,835,541 | I have a pandas dataframe of format with 226 columns :
```
**W X Y Z.....**
a b c d.....
e f g h.....
```
i want to subtract columns Y and Z in the following way:
```
**W X Y Z.....**
a (b-c) (c-d) (d-nextvalue).....
e (f-g) (g-h) (h-nextvalue).....
```
how do i go about doing this? I am a rookie in python, thanks in advance | 2020/01/21 | ['https://Stackoverflow.com/questions/59835541', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12724372/'] | Use [`DataFrame.diff`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.diff.html) and if necessary convert first column to index by [`DataFrame.set_index`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html):
```
df = pd.DataFrame({
'W':list('abc'),
'X':[10,5,4],
'Y':[7,8,9],
'Z':[1,1,0],
'E':[5,3,6],
})
df = df.set_index('W').diff(-1, axis=1)
print (df)
X Y Z E
W
a 3.0 6.0 -4.0 NaN
b -3.0 7.0 -2.0 NaN
c -5.0 9.0 -6.0 NaN
``` | To create 'W' as the index you can do,
```
df.set_index('W', inplace=True)
```
Further, you may try the following:
```
for i in range(len(df.columns) - 1):
df.iloc[:, i] = df.iloc[:, i] - df.iloc[:, i+1]
``` |
1,742,639 | I am not from a quantitative science field and most of the my concepts in probability is rustic.
I came up with this probability question so please forgive me for any error.
**A** and **B** are two tennis doubles player. A and B never played doubles tennis as a team together.
```
Probability of A (with another team mate) winning a doubles game= 0.7
Probability of B (with another team mate) winning a doubles game= 0.5
```
then whats the probability of winning a doubles game with A and B as a team ?
I assumed this is an independent event and I carried out this calculation
```
p(A and B) = p(A).p(B)
= 0.7*0.5
= 0.35
```
Is this calculation correct? | 2016/04/14 | ['https://math.stackexchange.com/questions/1742639', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/23624/'] | I think what you need is the probability that they lose, and subtract from $1$. The probability that they both lose (because both of them don't play well) on the same game is $(1-0.5)(1-0.7) = 0.15$, so the probability of the team winning is $1 - 0.15 = 0.85$.
The interpretation of this is the sum of the probabilities of $A$ playing well, but $B$ doesn't (but the team wins), of $B$ playing well but $A$ doesn't (but the team wins anyway), and both $A$ and $B$ play well (the team wins decisively):
$$0.7(1-0.5) + 0.5(1-0.7) + 0.7(0.5) = 0.35 + 0.15 + 0.35 = 0.85.$$
To be fair, this is a bit of an odd problem (not your fault). It requires you to think of the win probabilities of each individual on the team as independent, which in practice is almost certainly *not* the case. | What do you mean by "with another team mate"? Any person at all, as long as it's not A or B? Some particular person? Does it matter who they are playing against? What if A and somebody else are playing against B and somebody else? They can't have probabilities $0.7$ and $0.5$ of winning: the probabilities would have to add to $1$. The question is so vaguely stated that it is impossible to make any sense of it, but certainly it is wrong to multiply the probabilities. |
42,254,397 | In Xamarin.Forms 2.3.4.192-pre2, I have created a custom `ViewCell` that uses a grid for the `DataTemplate` of a `Xamarin.Forms.ListView`.
When the `ListView` is loaded, it throws `System.ArgumentException: NaN is not a valid value for width`.
I've located the [error in the Xamarin.Forms source code](https://github.com/xamarin/Xamarin.Forms/blob/master/Xamarin.Forms.Core/Size.cs#L19), but I can't figure out why the width would be `NaN`
Error
=====
>
> System.ArgumentException: NaN is not a valid value for width
>
>
> Xamarin.Forms.Size.Size(double width, double height)
> Xamarin.Forms.VisualElement.GetSizeRequest(double widthConstraint, double heightConstraint)
> Xamarin.Forms.VisualElement.Measure(double widthConstraint, double heightConstraint, MeasureFlags flags)
> Xamarin.Forms.StackLayout.CompressHorizontalLayout(StackLayout.LayoutInformation layout, double widthConstraint, double heightConstraint)
> Xamarin.Forms.StackLayout.CompressNaiveLayout(StackLayout.LayoutInformation layout, StackOrientation orientation, double widthConstraint, double heightConstraint)
> Xamarin.Forms.StackLayout.CalculateLayout(StackLayout.LayoutInformation layout, double x, double y, double widthConstraint, double heightConstraint, bool processExpanders)
> Xamarin.Forms.StackLayout.LayoutChildren(double x, double y, double width, double height)
> Xamarin.Forms.Layout.UpdateChildrenLayout()
> Xamarin.Forms.Layout.OnSizeAllocated(double width, double height)
> Xamarin.Forms.VisualElement.SizeAllocated(double width, double height)
> Xamarin.Forms.VisualElement.SetSize(double width, double height)
> Xamarin.Forms.VisualElement.set\_Bounds(Rectangle value)
> Xamarin.Forms.VisualElement.Layout(Rectangle bounds)
> Xamarin.Forms.Layout.LayoutChildIntoBoundingRegion(VisualElement child, Rectangle region)
> Xamarin.Forms.Grid.LayoutChildren(double x, double y, double width, double height)
> Xamarin.Forms.Layout.UpdateChildrenLayout()
> Xamarin.Forms.Layout.OnSizeAllocated(double width, double height)
> Xamarin.Forms.VisualElement.SizeAllocated(double width, double height)
> Xamarin.Forms.VisualElement.SetSize(double width, double height)
> Xamarin.Forms.VisualElement.set\_Bounds(Rectangle value)
> Xamarin.Forms.VisualElement.Layout(Rectangle bounds)
> Xamarin.Forms.Layout.LayoutChildIntoBoundingRegion(VisualElement child, Rectangle region)
> Xamarin.Forms.Platform.iOS.ViewCellRenderer.ViewTableCell.LayoutSubviews()
> Xamarin.Forms.Platform.iOS.CellTableViewCell.GetNativeCell(UITableView tableView, Cell cell, bool recycleCells, string templateId)
> Xamarin.Forms.Platform.iOS.ListViewRenderer.ListViewDataSource.GetCell(UITableView tableView, NSIndexPath indexPath)
> UIKit.UIApplication.UIApplicationMain(int, string[], intptr, intptr)(wrapper managed-to-native)
> UIKit.UIApplication.Main(string[] args, IntPtr principal, IntPtr delegate)UIApplication.cs:79
> UIKit.UIApplication.Main(string[] args, string principalClassName, string delegateClassName)UIApplication.cs:63
> MondayPundayApp.iOS.Application.Main(string[] args)Main.cs:17
>
>
>
Code
====
I put together a reproduction in this repository on GitHub:
<https://github.com/brminnick/Xamarin.Forms-NaN-is-not-a-valid-value-for-width-reproduction>
ListView
--------
```
var listView = new ListView(ListViewCachingStrategy.RecycleElement)
{
BackgroundColor = Color.White,
RowHeight = 200,
ItemTemplate = new DataTemplate(typeof(PuzzleCellCardView)),
SeparatorColor = Color.Transparent
};
```
ViewCell
--------
```
public class PuzzleCellCardView : ViewCell
{
Image _puzzleImage;
Label _punNumberValueLabel;
Image _questionMarkImage;
Image _checkImage;
public PuzzleCellCardView()
{
var puzzleImage = new Image
{
HeightRequest = 150,
BackgroundColor = Color.White
};
var punNumberTextLabel = new Label
{
Text = " Pun Number",
Style = StyleConstants.LabelStyle
};
_punNumberValueLabel = new Label
{
Style = StyleConstants.LabelStyle
};
var puzzleNumberStackLayout = new StackLayout
{
Children = {
punNumberTextLabel,
_punNumberValueLabel
},
Orientation = StackOrientation.Horizontal,
BackgroundColor = Color.White
};
_questionMarkImage = new Image
{
Source = App.ImageConstants.QuestionMark,
MinimumHeightRequest = 100,
BackgroundColor = Color.White
};
_checkImage = new Image
{
Source = App.ImageConstants.Check,
MinimumHeightRequest = 100,
BackgroundColor = Color.White
};
var whitePuzzleNumberBackgroundBoxView = new BoxView
{
BackgroundColor = Color.White
};
var cellGridLayout = new Grid
{
BackgroundColor = Color.Black,
Padding = new Thickness(2),
RowSpacing = 2,
ColumnSpacing = 1,
VerticalOptions = LayoutOptions.Fill,
RowDefinitions = {
new RowDefinition{ Height = new GridLength (20, GridUnitType.Absolute) },
new RowDefinition{ Height = new GridLength (150, GridUnitType.Absolute) }
},
ColumnDefinitions = {
new ColumnDefinition{ Width = new GridLength (1, GridUnitType.Star) },
new ColumnDefinition{ Width = new GridLength (1, GridUnitType.Star) }
}
};
cellGridLayout.Children.Add(whitePuzzleNumberBackgroundBoxView, 0, 0);
Grid.SetColumnSpan(whitePuzzleNumberBackgroundBoxView, 2);
cellGridLayout.Children.Add(puzzleNumberStackLayout, 0, 0);
Grid.SetColumnSpan(puzzleNumberStackLayout, 2);
cellGridLayout.Children.Add(_puzzleImage, 0, 1);
cellGridLayout.Children.Add(_checkImage, 1, 1);
cellGridLayout.Children.Add(_questionMarkImage, 1, 1);
if (Device.OS == TargetPlatform.Android)
_puzzleImage.InputTransparent = true;
View = cellGridLayout;
}
}
``` | 2017/02/15 | ['https://Stackoverflow.com/questions/42254397', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5953643/'] | This appears to be a regression with Xamarin.Forms v2.3.4.192-pre2.
The exception is not thrown when using Xamarin.Forms v2.3.3.180.
I submitted the bug to the Xamarin.Forms team via Bugzilla: <https://bugzilla.xamarin.com/show_bug.cgi?id=52533>
Update: This error is fixed in Xamarin.Forms 2.3.4.214-pre5 | Add a container (ex: frame) and specify width for this condainer,
```
<Frame x:Name="AutoCompleterContainer" Grid.Row="1" WidthRequest="400">
<telerikInput:RadAutoComplete ....
</Frame>
``` |
11,380,533 | I create a project with ARC support using the Xcode project wizard. Compared with a program without ARC support, I did not notice any differences. Is there any hint that can tell me if my program supports ARC?
I am using XCode 4.2.1 Build 4D502 | 2012/07/08 | ['https://Stackoverflow.com/questions/11380533', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/705414/'] | You can use `__has_feature`, maybe logging whether the project has ARC in the console like this:
```
#if __has_feature(objc_arc)
// ARC is On
NSLog(@"ARC on");
#else
// ARC is Off
NSLog(@"ARC off");
#endif
```
Alternatively, instead of just logging whether ARC is on, try making the compiler raise an error if ARC is on (or off) like this:
```
#if ! __has_feature(objc_arc)
#error This file must be compiled with ARC. Use -fobjc-arc flag (or convert project to ARC).
#endif
``` | Or to test just once, add this in your code:
```
NSString* dummy = [[[NSString alloc] init] autorelease];
```
This should raise an error if you are using ARC. If it does, ARC is enabled, all is fine and you can remove it again. |
11,380,533 | I create a project with ARC support using the Xcode project wizard. Compared with a program without ARC support, I did not notice any differences. Is there any hint that can tell me if my program supports ARC?
I am using XCode 4.2.1 Build 4D502 | 2012/07/08 | ['https://Stackoverflow.com/questions/11380533', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/705414/'] | You can use `__has_feature`, maybe logging whether the project has ARC in the console like this:
```
#if __has_feature(objc_arc)
// ARC is On
NSLog(@"ARC on");
#else
// ARC is Off
NSLog(@"ARC off");
#endif
```
Alternatively, instead of just logging whether ARC is on, try making the compiler raise an error if ARC is on (or off) like this:
```
#if ! __has_feature(objc_arc)
#error This file must be compiled with ARC. Use -fobjc-arc flag (or convert project to ARC).
#endif
``` | If you just want to know one time if your project has ARC, I suggest using jpalten's answer. If you want your code to only build with ARC on, I suggest qegal's.
However, if you want to know where in Xcode the setting lives:
1. Select your project in the navigator. This will open the project editor.
2. In the project editor, select your target.
3. In the project editor, click Build Settings (if it isn't already selected).
4. In the project editor, click the search box and type `OBJC_ARC`.
This will leave a single line showing in Build Settings, either **Objective-C Automatic Reference Counting** or **CLANG\_ENABLE\_OBJC\_ARC** (depending on whether you're showing setting descriptions or names). If it's set to YES, you have ARC on.
This is your target's pick of whether ARC is used. Note that each **file** can be compiled with a different setting. This is **not** what you asked, but since we already have three answers I thought I'd head off a possible fourth. :)
To see which files override the ARC setting:
1. Select your project in the navigator. This will open the project editor.
2. In the project editor, select your target.
3. In the project editor, click **Build Phases** (not Build Settings).
4. Expand the **Compile Sources** build phase.
Here, you can see the compiler flags for each file. Files with that set whether or not to use ARC will include either **-fno-objc-arc** or **-fobjc-arc**, for specifying MRR or ARC respectively. |
11,380,533 | I create a project with ARC support using the Xcode project wizard. Compared with a program without ARC support, I did not notice any differences. Is there any hint that can tell me if my program supports ARC?
I am using XCode 4.2.1 Build 4D502 | 2012/07/08 | ['https://Stackoverflow.com/questions/11380533', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/705414/'] | You can use `__has_feature`, maybe logging whether the project has ARC in the console like this:
```
#if __has_feature(objc_arc)
// ARC is On
NSLog(@"ARC on");
#else
// ARC is Off
NSLog(@"ARC off");
#endif
```
Alternatively, instead of just logging whether ARC is on, try making the compiler raise an error if ARC is on (or off) like this:
```
#if ! __has_feature(objc_arc)
#error This file must be compiled with ARC. Use -fobjc-arc flag (or convert project to ARC).
#endif
``` | add "-fno-objc-arc" compiler flags for all the .m files in build phases |
11,380,533 | I create a project with ARC support using the Xcode project wizard. Compared with a program without ARC support, I did not notice any differences. Is there any hint that can tell me if my program supports ARC?
I am using XCode 4.2.1 Build 4D502 | 2012/07/08 | ['https://Stackoverflow.com/questions/11380533', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/705414/'] | If you just want to know one time if your project has ARC, I suggest using jpalten's answer. If you want your code to only build with ARC on, I suggest qegal's.
However, if you want to know where in Xcode the setting lives:
1. Select your project in the navigator. This will open the project editor.
2. In the project editor, select your target.
3. In the project editor, click Build Settings (if it isn't already selected).
4. In the project editor, click the search box and type `OBJC_ARC`.
This will leave a single line showing in Build Settings, either **Objective-C Automatic Reference Counting** or **CLANG\_ENABLE\_OBJC\_ARC** (depending on whether you're showing setting descriptions or names). If it's set to YES, you have ARC on.
This is your target's pick of whether ARC is used. Note that each **file** can be compiled with a different setting. This is **not** what you asked, but since we already have three answers I thought I'd head off a possible fourth. :)
To see which files override the ARC setting:
1. Select your project in the navigator. This will open the project editor.
2. In the project editor, select your target.
3. In the project editor, click **Build Phases** (not Build Settings).
4. Expand the **Compile Sources** build phase.
Here, you can see the compiler flags for each file. Files with that set whether or not to use ARC will include either **-fno-objc-arc** or **-fobjc-arc**, for specifying MRR or ARC respectively. | Or to test just once, add this in your code:
```
NSString* dummy = [[[NSString alloc] init] autorelease];
```
This should raise an error if you are using ARC. If it does, ARC is enabled, all is fine and you can remove it again. |
11,380,533 | I create a project with ARC support using the Xcode project wizard. Compared with a program without ARC support, I did not notice any differences. Is there any hint that can tell me if my program supports ARC?
I am using XCode 4.2.1 Build 4D502 | 2012/07/08 | ['https://Stackoverflow.com/questions/11380533', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/705414/'] | Or to test just once, add this in your code:
```
NSString* dummy = [[[NSString alloc] init] autorelease];
```
This should raise an error if you are using ARC. If it does, ARC is enabled, all is fine and you can remove it again. | add "-fno-objc-arc" compiler flags for all the .m files in build phases |
11,380,533 | I create a project with ARC support using the Xcode project wizard. Compared with a program without ARC support, I did not notice any differences. Is there any hint that can tell me if my program supports ARC?
I am using XCode 4.2.1 Build 4D502 | 2012/07/08 | ['https://Stackoverflow.com/questions/11380533', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/705414/'] | If you just want to know one time if your project has ARC, I suggest using jpalten's answer. If you want your code to only build with ARC on, I suggest qegal's.
However, if you want to know where in Xcode the setting lives:
1. Select your project in the navigator. This will open the project editor.
2. In the project editor, select your target.
3. In the project editor, click Build Settings (if it isn't already selected).
4. In the project editor, click the search box and type `OBJC_ARC`.
This will leave a single line showing in Build Settings, either **Objective-C Automatic Reference Counting** or **CLANG\_ENABLE\_OBJC\_ARC** (depending on whether you're showing setting descriptions or names). If it's set to YES, you have ARC on.
This is your target's pick of whether ARC is used. Note that each **file** can be compiled with a different setting. This is **not** what you asked, but since we already have three answers I thought I'd head off a possible fourth. :)
To see which files override the ARC setting:
1. Select your project in the navigator. This will open the project editor.
2. In the project editor, select your target.
3. In the project editor, click **Build Phases** (not Build Settings).
4. Expand the **Compile Sources** build phase.
Here, you can see the compiler flags for each file. Files with that set whether or not to use ARC will include either **-fno-objc-arc** or **-fobjc-arc**, for specifying MRR or ARC respectively. | add "-fno-objc-arc" compiler flags for all the .m files in build phases |
67,877,783 | We use Cosmos DB to track all our devices and also data that is related to the device (and not stored in the device document itself) is stored in the same container with the same partition ID.
Both the device document and the related documents have `/deviceId` as the partition key. When a device is removed, then I remove the device document. I actually want to remove the entire partition, but this doesn't seem to be possible. So I revert to a query that queries for all items with this partition key and remove them from the database.
This works fine, but may consume a lot of RUs if there is a lot of related data (which may be true in some cases). I would rather just remove the device and schedule all related data for removal later (it doesn't hurt to have them in the database for a while). When RU utilization is low, then I start removing these items. Is there a standard solution to do this?
The best solution would be to schedule this and that Cosmos DB would process these commands when it has spare RUs, just like with the TTL deletion. Is this even possible? | 2021/06/07 | ['https://Stackoverflow.com/questions/67877783', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/956435/'] | Dart is [null safe](https://dart.dev/null-safety/understanding-null-safety#uninitialized-variables) . You either must always assign a value or mark it explicitly as nullable using a `?`
```
String _prenom = "Something";
```
or
```
String? _prenom;
``` | in Dart class always add ? after DataType
```
bool? log = true;
String? mail;
String? password;
String? prenom;
String? nom;```
``` |
643 | What is a good English phrase for "produktionsbedingter Leerraum"?
The literal meaning is "an empty space caused by production" and tells buyers that the half-empty cookie box is a feature. | 2011/05/30 | ['https://german.stackexchange.com/questions/643', 'https://german.stackexchange.com', 'https://german.stackexchange.com/users/4/'] | The technical term in the US is ["slack-fill"](http://www.accessdata.fda.gov/scripts/cdrh/cfdocs/cfcfr/CFRSearch.cfm?fr=100.100), however consumers aren't likely to know what this means. (In terms of potato chips and other vacuum-packed goods, this is also called "headspace"):
>
> *Slack-fill is the difference between the actual capacity of a container and the volume of product contained therein.*
>
>
>
In order to explain this concept to consumers, you'd probably need to resort to a more descriptive sentence instead of a technical term. The other answers have provided some suggestions, although they do feel somewhat clumsy.
My additional suggestion:
Product packed with empty space for transportation. | Such a thing doesn't appear written very often, and translating compound words tends to always produce clumsy results.
I would propose either
>
> Free space from manufacturing
>
>
>
(short for "free space resulting from the manufacturing process")
or
>
> Manufactured free space
>
>
>
As a label, perhaps
>
> Space left free by design
>
>
>
would work. |
25,278,612 | I'm new in mobile app development. I'm using Xamarin to develop Android applications. In the hello world app in the OnCreate method I see the following code:
```
Button button = FindViewById<Button>(Resource.Id.MyButton);
```
So I'm trying to create my own button the same way. I create the button in the designer and inside OnCreate method put the line:
```
Button myOwnBtn = FindViewById<Button>(Resource.Id.MyOwnBtn);
```
That gives me an error that there is no MyOwnBtn. Then I'm looking the code of Id class and see there a line like:
```
public const int MyButton=2123344112;
```
If I put there the line:
```
public const int MyOwnBtn=2123344113;
```
Everything works fine. But as I understand it should be generated automatically or it will be a little bit difficult to put there a unique number for each control.
Can anybody tell me what I am doing wrong? And how does FindViewById() work? | 2014/08/13 | ['https://Stackoverflow.com/questions/25278612', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3484533/'] | You have to give the `id` `MyOwnBtn` to the `Button` that you created in the designer.
`findViewById` is a method of the `View` class and it looks for a child view having the `id` that you provided in the argument.
From [official documentation](http://developer.android.com/reference/android/view/View.html#findViewById(int)):
>
> Look for a child view with the given id. If this view has the given id, return this view.
>
>
> | MyButton id is not a const value, It will change every launch. |
25,278,612 | I'm new in mobile app development. I'm using Xamarin to develop Android applications. In the hello world app in the OnCreate method I see the following code:
```
Button button = FindViewById<Button>(Resource.Id.MyButton);
```
So I'm trying to create my own button the same way. I create the button in the designer and inside OnCreate method put the line:
```
Button myOwnBtn = FindViewById<Button>(Resource.Id.MyOwnBtn);
```
That gives me an error that there is no MyOwnBtn. Then I'm looking the code of Id class and see there a line like:
```
public const int MyButton=2123344112;
```
If I put there the line:
```
public const int MyOwnBtn=2123344113;
```
Everything works fine. But as I understand it should be generated automatically or it will be a little bit difficult to put there a unique number for each control.
Can anybody tell me what I am doing wrong? And how does FindViewById() work? | 2014/08/13 | ['https://Stackoverflow.com/questions/25278612', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3484533/'] | You have to give the `id` `MyOwnBtn` to the `Button` that you created in the designer.
`findViewById` is a method of the `View` class and it looks for a child view having the `id` that you provided in the argument.
From [official documentation](http://developer.android.com/reference/android/view/View.html#findViewById(int)):
>
> Look for a child view with the given id. If this view has the given id, return this view.
>
>
> | The Activity or ViewGroup's findViewById() method returns a view that already has an id. The findViewById() method should be used in conjunction with XML layouts to provide a reference to the View that was defined in the XML file.
**Edit**: Not entirely sure if my answer is relevant to Xamarin. I apologize if I have mislead people, I am referring to Java Android application development. |
25,278,612 | I'm new in mobile app development. I'm using Xamarin to develop Android applications. In the hello world app in the OnCreate method I see the following code:
```
Button button = FindViewById<Button>(Resource.Id.MyButton);
```
So I'm trying to create my own button the same way. I create the button in the designer and inside OnCreate method put the line:
```
Button myOwnBtn = FindViewById<Button>(Resource.Id.MyOwnBtn);
```
That gives me an error that there is no MyOwnBtn. Then I'm looking the code of Id class and see there a line like:
```
public const int MyButton=2123344112;
```
If I put there the line:
```
public const int MyOwnBtn=2123344113;
```
Everything works fine. But as I understand it should be generated automatically or it will be a little bit difficult to put there a unique number for each control.
Can anybody tell me what I am doing wrong? And how does FindViewById() work? | 2014/08/13 | ['https://Stackoverflow.com/questions/25278612', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3484533/'] | You have to give the `id` `MyOwnBtn` to the `Button` that you created in the designer.
`findViewById` is a method of the `View` class and it looks for a child view having the `id` that you provided in the argument.
From [official documentation](http://developer.android.com/reference/android/view/View.html#findViewById(int)):
>
> Look for a child view with the given id. If this view has the given id, return this view.
>
>
> | When you declare a **button** in your **.xml** file, you should set an id for it (Usually it is done using **string.xml** file). After that, **R.java** will be updated automatically and set a number to your declared id and you can access your button by that id like what you have done. |
25,278,612 | I'm new in mobile app development. I'm using Xamarin to develop Android applications. In the hello world app in the OnCreate method I see the following code:
```
Button button = FindViewById<Button>(Resource.Id.MyButton);
```
So I'm trying to create my own button the same way. I create the button in the designer and inside OnCreate method put the line:
```
Button myOwnBtn = FindViewById<Button>(Resource.Id.MyOwnBtn);
```
That gives me an error that there is no MyOwnBtn. Then I'm looking the code of Id class and see there a line like:
```
public const int MyButton=2123344112;
```
If I put there the line:
```
public const int MyOwnBtn=2123344113;
```
Everything works fine. But as I understand it should be generated automatically or it will be a little bit difficult to put there a unique number for each control.
Can anybody tell me what I am doing wrong? And how does FindViewById() work? | 2014/08/13 | ['https://Stackoverflow.com/questions/25278612', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3484533/'] | You have to give the `id` `MyOwnBtn` to the `Button` that you created in the designer.
`findViewById` is a method of the `View` class and it looks for a child view having the `id` that you provided in the argument.
From [official documentation](http://developer.android.com/reference/android/view/View.html#findViewById(int)):
>
> Look for a child view with the given id. If this view has the given id, return this view.
>
>
> | It will try to find it from the XML file that you inflate. So make sure you inflate the correct xml file. This code inflates the xml:
```
SetContentView (Resource.Layout.MainLayout);
```
Even if you got the correct id created in a xml file, if you don't inflate it first, the system won't be able to find that view since it is not inflated. |
38,654,071 | I'm making a report in ssrs where I want to get the Integer that specifies the number of day from the year it is today. Today `=Now()` will also be set as default as a Parameter (EndDate) so I'm actually looking for the number of the day of the year the EndDate parameter is. So for example 1st of January is 1, 1st of February is 32, 31st of December is 365. I tought there was this day of year expression in SSRS but it seems gone. Can anyone help me? Maybe with some sort of Dateadd or Datediff? | 2016/07/29 | ['https://Stackoverflow.com/questions/38654071', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5713919/'] | Try this expression
function **DateDiff** in useful for date diffrence between two dates
if we found day no from specific dates we can use as
```
=DateDiff(DateInterval.Day,startdate,enddate)
```
**Example :**
```
=DateDiff(DateInterval.Day,CDate("1/1/2016"),now())
``` | I just found a better way if you want to base the day of the year on a parameter/field:
e.g. With a parameter called EndDate:
'Day of the year, of that parameter:
```
=DatePart("y",Parameters!EndDate.Value)
``` |
38,613,510 | I am trying to run a shell script to execute a binary on a remote linux box. Both the binary and the shell script are on my local window machine. Is there any way through which i can run the binary to the remote machine directly from windows through command line tools like *PLINK*?
I don't want to put the binary and the script to all the remote linux boxes which
i want them to run on,Instead I want to run the shell script which will intern invoke the binary and do the desirable functions directly through my local machine. | 2016/07/27 | ['https://Stackoverflow.com/questions/38613510', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5381104/'] | You can run the shell script remotely, just by piping it through ssh:
```
cat my_script.sh | ssh -T my_server
```
(Or whatever the windows/plink equivalent is.)
However, you can't run the binary remotely through a pipe, the file will have to exist on the remote server. You can do this by pushing the file from your windows machine to a known location on the remote server, and then editing your script to expect the file to exist in that location:
```
scp my_binary my_server:/tmp
cat my_script.sh | ssh -T my_server
```
And then just have your script run that binary:
```
/tmp/my_binary
```
Or you can write the script so that it pulls the binary file from a central location where you're hosting it:
```
wget -O /tmp/my_binary http://my_fileserver/my_binary
/tmp/my_binary
```
Note, if the shell script doesn't do anything else besides invoke the binary, then you don't need it. You can just fire the commands directly through ssh:
```
ssh -T my_server "cd /tmp && wget http://my_fileserver/my_binary && ./my_binary"
``` | You will have to copy the binary to the remote Linux box before it can be executed. However, you could have a script on the windows machine that uses sftp to transfer the binary program to a temporary directory under `/tmp` before running it, so there is no manual setup required. |
35,507,451 | So I have this list:
```
list = ["NYC Football", ["NY Giants","NY Jets"], "NYC Hockey", ["NY Rangers", "NY Islanders", "NJ Devils"]]
```
How would I loop through this list and only print out:
```
NY Giants
NY Jets
NY Rangers
NY Islanders
NJ Devils
``` | 2016/02/19 | ['https://Stackoverflow.com/questions/35507451', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] | You could use the following:
```
my_list = ["NYC Football", ["NY Giants","NY Jets"], "NYC Hockey", ["NY Rangers", "NY Islanders", "NJ Devils"]]
for item in my_list:
if type(item) == list:
for i in item:
print(i)
```
**Output**
```
NY Giants
NY Jets
NY Rangers
NY Islanders
NJ Devils
```
**Aside:** you shouldn't use the keyword `list` as a variable name. In my example I have altered it to `my_list`. | Loop over the outer list, and only if the item is a list, iterate over it and print its items:
```
for thing in my_list: #don't call it "list"
if isinstance(thing, list):
for other in thing:
print(other)
```
Another way:
```
for thing in filter(lambda x: isinstance(x, list)):
for other in thing:
print(other)
``` |
35,507,451 | So I have this list:
```
list = ["NYC Football", ["NY Giants","NY Jets"], "NYC Hockey", ["NY Rangers", "NY Islanders", "NJ Devils"]]
```
How would I loop through this list and only print out:
```
NY Giants
NY Jets
NY Rangers
NY Islanders
NJ Devils
``` | 2016/02/19 | ['https://Stackoverflow.com/questions/35507451', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] | First of all, please don't use the name list for a list. You will shadow the built in list, which is going to give you a hard to detect bug sooner or later.
As chepner already mentioned in the comments, I strongly recommend converting your list to a dictionary in order to have a clean sport:teams mapping.
```
>>> lst = ["NYC Football", ["NY Giants","NY Jets"], "NYC Hockey", ["NY Rangers", "NY Islanders", "NJ Devils"]]
>>> teams = dict(zip(*[iter(lst)]*2))
>>> teams
{'NYC Football': ['NY Giants', 'NY Jets'], 'NYC Hockey': ['NY Rangers', 'NY Islanders', 'NJ Devils']}
```
To get the sports, issue
```
>>> teams.keys()
['NYC Football', 'NYC Hockey']
```
To get the teams, issue
```
>>> teams.values()
[['NY Giants', 'NY Jets'], ['NY Rangers', 'NY Islanders', 'NJ Devils']]
```
You could also un-nest this list with `itertools.chain`:
```
>>> list(chain.from_iterable(teams.values()))
['NY Giants', 'NY Jets', 'NY Rangers', 'NY Islanders', 'NJ Devils']
```
I assumed that the order of the dictionary is not important. If it is, you can use an `OrderedDict` from the `collections` module.
```
>>> from collections import OrderedDict
>>> teams = OrderedDict(zip(*[iter(lst)]*2))
>>> for team in chain.from_iterable(teams.values()):
... print(team)
...
NY Giants
NY Jets
NY Rangers
NY Islanders
NJ Devils
``` | Loop over the outer list, and only if the item is a list, iterate over it and print its items:
```
for thing in my_list: #don't call it "list"
if isinstance(thing, list):
for other in thing:
print(other)
```
Another way:
```
for thing in filter(lambda x: isinstance(x, list)):
for other in thing:
print(other)
``` |
20,237,917 | I am trying to initialize collection view its showing incompatible type. I have written below code
```
UICollectionView * collCobj = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 260, 320, 230) collectionViewLayout:UICollectionViewScrollPositionLeft];
``` | 2013/11/27 | ['https://Stackoverflow.com/questions/20237917', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2742598/'] | There are multiple smaller problems with your codes.
1. Names in authors and books XML files do not match. I guess it's only some typos.
2. Predicates belong to an axis step, not in their own (remove the slash after `book` in line one).
3. XML and XQuery are capitalization sensitive! `<Book/>` uses a capital B, so do the same in your XQuery, again in line 1.
4. In Line two, you're looping over all `<authorRoot/>` elements. Use `authorRoot/author` instead.
5. In line three you're hiding the book `$p` with it's name for the rest of this FLWOR expression, but you want to use the book again in line five. Better use another variable name.
6. Better do not use the `descendant-or-self`-step `//` if you don't need it (lines one and two). This decreases performance.
I don't get what your idea for filtering was in lines three to five. Compare yourself with this working solution. Additionally I used speaking variable names, don't confuse yourself with unnecessary short ones.
Replace `$book` and `$authors` by the respecting `doc(...)` functions.
```none
for $book in $books//library/Book[title/contains(., 'Title1')]
for $author in $authors//authorRoot/author
where $book/author = $author/Name
return $author/Location/text()
```
If you want to have a list of distinct places, wrap `distinct-values(...)` around all four lines.
An alternative without explicit loops:
```none
$authors/authorRoot/author[
Name = $books/library/Book[contains(title, 'Title1')]/author)
]/Location
```
The second solution is also valid XPath 1.0, the first requires an XPath 3.0 or XQuery processor. | If you use
```
let $books := <library>
<Book>
<title>Title1</title>
<author>Ellizabith</author>
</Book>
<Book>
<title>Title2</title>
<author>Sam</author>
</Book>
<Book>
<title>Title3</title>
<author>Ryan</author>
</Book>
</library>
let $authors := <authorRoot>
<author>
<Name>Rayan</Name>
<Location>Yahoo</Location>
</author>
<author>
<Name>Syan</Name>
<Location>Google</Location>
</author>
<author>
<Name>Sam</Name>
<Location>Bing</Location>
</author>
<author>
<Name>Ellizabith</Name>
<Location>Apple</Location>
</author>
</authorRoot>
return $authors/author[Name = $books/Book[contains(title, 'Title1')]/author]/Location/string()
```
the result is `Apple`. |
6,778,627 | Just finishing up a site and having an issue with position: fixed on IE7. I've Googled it and tried different Doctypes but the fixed area is still moving out of position on IE7.
I've not got IE7 but a client staffer has it and I can see the issue using an online IE renderer/tester.
I've removed the .htaccess from the test site so you can see the site/code.
<http://drinkzing.com/test>
Any advise or help would be appreciated. | 2011/07/21 | ['https://Stackoverflow.com/questions/6778627', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/856285/'] | Use [XPath](http://www.w3schools.com/xpath/) to get the nodes.
//child2 - to get the list of all "child2" elements | If you can use SAX parser than it is easy here your ContentHandler
```
public class CH extends DefaultHandler
{
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException
{
if (qName.equals("child2"))
{
// here you go do what you need here with the attributes
}
}
}
```
pass it to parser and you are done
like
```
import org.xml.sax.*;
public class TestParse {
public static void main(String[] args) {
try {
XMLReader parser =
org.xml.sax.helpers.XMLReaderFactory.createXMLReader();
// Create a new instance and register it with the parser
ContentHandler contentHandler = new CH();
parser.setContentHandler(contentHandler);
parser.parse("foo.xml"); // see javadoc you can give it a string or stream
} catch (Exception e) {
e.printStackTrace();
}
}
}
``` |
6,778,627 | Just finishing up a site and having an issue with position: fixed on IE7. I've Googled it and tried different Doctypes but the fixed area is still moving out of position on IE7.
I've not got IE7 but a client staffer has it and I can see the issue using an online IE renderer/tester.
I've removed the .htaccess from the test site so you can see the site/code.
<http://drinkzing.com/test>
Any advise or help would be appreciated. | 2011/07/21 | ['https://Stackoverflow.com/questions/6778627', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/856285/'] | Using XPath, you could do it something like this:
```
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList child2Nodes= (NodeList) xpath.evaluate("//child2", doc,
XPathConstants.NODESET);
```
Where doc is your org.w3c.dom.Document class. | Use [XPath](http://www.w3schools.com/xpath/) to get the nodes.
//child2 - to get the list of all "child2" elements |
6,778,627 | Just finishing up a site and having an issue with position: fixed on IE7. I've Googled it and tried different Doctypes but the fixed area is still moving out of position on IE7.
I've not got IE7 but a client staffer has it and I can see the issue using an online IE renderer/tester.
I've removed the .htaccess from the test site so you can see the site/code.
<http://drinkzing.com/test>
Any advise or help would be appreciated. | 2011/07/21 | ['https://Stackoverflow.com/questions/6778627', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/856285/'] | Using XPath, you could do it something like this:
```
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList child2Nodes= (NodeList) xpath.evaluate("//child2", doc,
XPathConstants.NODESET);
```
Where doc is your org.w3c.dom.Document class. | If you can use SAX parser than it is easy here your ContentHandler
```
public class CH extends DefaultHandler
{
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException
{
if (qName.equals("child2"))
{
// here you go do what you need here with the attributes
}
}
}
```
pass it to parser and you are done
like
```
import org.xml.sax.*;
public class TestParse {
public static void main(String[] args) {
try {
XMLReader parser =
org.xml.sax.helpers.XMLReaderFactory.createXMLReader();
// Create a new instance and register it with the parser
ContentHandler contentHandler = new CH();
parser.setContentHandler(contentHandler);
parser.parse("foo.xml"); // see javadoc you can give it a string or stream
} catch (Exception e) {
e.printStackTrace();
}
}
}
``` |
35,524,140 | I'm writing a shell script to perform a series of actions in remote. Then I want to come back to local and perform the next series of actions. When I use exit, I'm exiting from the shell script instead of logging out of the remote machine.
```
set -x
ssh $1
cd /var/log/sysstat/
for (( i = 11; i <= 19; i++ ))
do
sar -f $i >> /home/sirish.aditya/cpu_11-19.csv
sar -f $i -r >> /home/sirish.aditya/mem_11-19.csv
done
exit
mkdir /Users/sirish.aditya/workSpace/cpustats_srm/$1
scp sirish.aditya@$1:/home/sirish.aditya/mem_11-19.csv /Users/sirish.aditya/workSpace/cpustats_srm/$1
scp sirish.aditya@$1:/home/sirish.aditya/cpu_11-19.csv /Users/sirish.aditya/workSpace/cpustats_srm/$1
```
--
```
ssh sirish.aditya@remote_machine 'bash -s' < memory.sh remote_machine
```
Can somebody help on this?
Thanks in advance | 2016/02/20 | ['https://Stackoverflow.com/questions/35524140', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4658006/'] | In the example code above, there is circular reference between `A`and `B` classes. These [will be garbage collected](https://stackoverflow.com/a/1910203/3736955) IF they are not reachable by any other object instance in `Application`.
"`Activity`is destroyed" does not mean it is garbage collected. But when `Activity` is garbage collected, its variables, Views, which only `Activity` references to, will be garbage collected as well. *I think*, on `onDestroy()` of `Activity` class, variables will be assigned to `null` but still their values will be held on memory until they are garbage collected.
In the link written in question, `Presenter` object had reference to `Activity` and vice versa. They would be garbage collected if they were not referenced by other object instances in `Application`. But `Activity` is [referenced by](https://github.com/ribot/android-boilerplate/pull/31) `Presenter` which is referenced by `Subscription`object, which is also referenced by some static class.
Same rules apply to when creating `Adapter` and passing `Context` from `Activity`. If they both are not referenced by other objects, there will not be a leak. But to be cautious, [you should pass](http://android-developers.blogspot.com.tr/2009/01/avoiding-memory-leaks.html) `Application Context`to `Adapter`instead of `Activity Context`. | It would depend on if the object references in A and B are the same object references within each other. After you edited the example to include how A and B were instantiated (newed up), there IS NOT a memory leak in your example because the instances created of each are not the same instances (different memory reference).
It would be possible to create a memory leak in a case like this, depending on how the two classes are constructed or instantiated. The definition of the classes given above doesn't have enough information to determine if a memory leak is present.
For example, given the following class definitions:
```
class A extends Activity{
private B objectB;
public void setB(B b){
objectB = b;
}
}
class B{
private A objectA;
public B(A a){
objectA = a;
}
}
```
If you then created a Test class instantiating A and B as shown here:
```
class Test(){
public static void main(String... args){
A a = new A();
B b = new B(a);
a.setB(b);
}
}
```
In this case, a memory leak has been introduced because as B is instantiated, it is passed a reference to A and then we explicitly set B in A to the same B holding a reference to this instance of A.
If we change the code in Test by one line:
```
class Test(){
public static void main(String... args){
A a = new A();
B b = new B(a);
a.setB(new B()); //Modified this line
}
}
```
Now we no longer have a memory leak, as the B we pass to A is not the same instance as the B holding a reference to A. |
48,254 | I coded a php chat that stores the text in a txt file and retrieves it, and I want to know if XSS can get past it or if someone can replace `xhr.open("POST","uhh.php");` with something that contains the same php code but without `htmlspecialchars` or something like that. What are the vulnerabilities? (More specifically, I don't want people putting html elements through the chat, and that also leads to security issues.)
This is `uhh.php`:
```
<?php
$usr=$_POST["usr"];
$msg=$_POST["msg"];
if($usr&&$msg){
$txt="$usr: $msg";
$txt=htmlspecialchars(join("\n",str_split($txt,33)));
$split=explode("\n",file_get_contents("uhh.txt") . $txt);
while(count($split)>10){
$split=array_slice($split,1);
}
file_put_contents("uhh.txt",join("\n",$split) . "\n");
}
?>
watchu lookeen at???
```
And this is the code to the html page (JavaScript included):
```
<!DOCTYPE html>
<html><head>
<title>Chatting</title>
<style>
#chatlog {
text-align:left;
border:1px solid black;
width:300px;
height:200px;
}
#chatbar {
width:300px;
}
</style>
<style type="text/css"></style></head>
<body>
<center>
<div id="chatlog">Bagelhead: lol<br>Bagelhead: yes t is<br>Abe: ok proxy off now<br>Bagelhead: gtg<br>Bagelhead: :P<br>Test: Test<br>Abe: <p>Test</p><br>Abe: Test<br>TEST: ab<br>TEST: abe<br></div>
<input maxlength="9001" placeholder="Press / to chat" type="text" id="chatbar">
</center>
<script>
setInterval(function(){
var xhr=new XMLHttpRequest();
xhr.open("GET","uhh.txt?a="+Math.random());
xhr.onload=function(){
document.getElementById("chatlog").innerHTML=xhr.responseText.replace(/\n/g,"<br/>");
}
xhr.send();
},1000)
var cb=document.querySelector("#chatbar"),usr="";
function chat(m){
var xhr=new XMLHttpRequest();
xhr.open("POST","uhh.php");
var fd=new FormData();
fd.append("usr",usr);
fd.append("msg",m);
xhr.send(fd);
}
window.onkeyup=function(e){
if(e.keyIdentifier=="U+00BF"){
cb.focus();
}else if(e.keyIdentifier=="Enter"){
if(usr){
chat(cb.value);
cb.value="";
}else{
usr=cb.value;
cb.placeholder="Press / to chat";
cb.value="";
cb.maxLength=9001;
}
}
}
</script>
</body></html>
```
`uhh.txt` is just a blank text file. | 2014/04/26 | ['https://codereview.stackexchange.com/questions/48254', 'https://codereview.stackexchange.com', 'https://codereview.stackexchange.com/users/41369/'] | Looks safe to me, but I would change the way you request the server. This way, you send many requests to the server and for more then few people using it, the server could be flooded by these requests. It would however require switching txt file for script file. Then you could use so called long poll.
You are probably wondering what long poll is and how it works. Long poll is technique where client opens connection to the server and leaves it open. When new message comes, server sends it and closes the connection. Trick is, client immediately opens new connection. Same happens when old connection times out.
Problem here is, when you use PHP on server side, it just executes some code and closes the connection. So, you have 2 possibilities: Best idea is to use server written in node.js, which is made for such things (and there are other advantages like that you don't have to store the message anywhere, you just recieve it and immediately send it to all clients and other...). If you want or have to use PHP, then you must use the sleep() function. Then, you have while loop, that each for example 200 miliseconds check for new message in database and either sends it or sleeps for another 200 miliseconds.
If you want to try, here is part of my client code which takes care of server communication:
```
//function, that returns right kind of AJAX object based on browser
//I don't have worst case scenario (AJAX not supported) here, because I usually check for required support at the beginning of the script
function createAjax() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else {
return new ActiveXObject('Microsoft.XMLHTTP');
}
}
/*
Class that takes care of receiving new messages from server
PARAMS:
longPollServerURL - string - URL of server file, which acts as long poll server
lastIdGetURL - string - URL of txt file, where last message id is saved
newMessageCallback - function - callback to get called when new message is received
it is called with 4 params:
id of the message, time when the message was sent as unix timestamp,
nickname of the person who sent it, message text itself
*/
function ChatLongPoll(longPollServerURL, lastIdGetURL, newMessageCallback) {
var mainContext = this,
httpRequest = createAjax();
//function that starts long poll and sets what should happen when connection ends
this.startLongPoll = function() {
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState == 4) {
var _decodedResponse = JSON.parse(httpRequest.responseText);
if (_decodedResponse.status == 'new') {
for (var i = 0; i <_decodedResponse.messages.length; i++) {
newMessageCallback(_decodedResponse.messages[i].id, _decodedResponse.messages[i].time, _decodedResponse.messages[i].from, _decodedResponse.messages[i].messageText);
mainContext.lastMessageId = _decodedResponse.messages[i].id;
}
}
mainContext.openLongPoll();
}
};
mainContext.openLongPoll();
};
//function that opens connection to the server
this.openLongPoll = function() {
httpRequest.open('GET', longPollServerURL + '?lastId=' + mainContext.lastMessageId, true);
httpRequest.send(null);
};
//function that downloads ID of last message sent
this.getLastMessageId = function() {
var _id = false;
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState == 4) {
_id = httpRequest.responseText;
}
};
httpRequest.open('GET', lastIdGetURL, false);
httpRequest.send(null);
return _id;
};
this.lastMessageId = this.getLastMessageId();
}
/*
Class that takes care of sending messages to server
PARAMS:
newMessageServerURL - string - URL of file, which saves and validates the message
callback - function - function to handle response from server (ok / wrongFormat / noName / ... status etc... (that depends on how you make your server))
*/
function ChatSendMessage(newMessageServerURL, callback) {
var httpRequest = createAjax();
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState == 4) {
callback(JSON.parse(httpRequest.responseText));
}
};
//function that sends the message to server and saves it to httpRequest.lastMessage
this.sendMessage = function (from, messageText) {
var L_postData = 'from=' + encodeURIComponent(from) + '&messageText=' + encodeURIComponent(messageText);
httpRequest.lastMessage = messageText;
httpRequest.open('POST', newMessageServerURL, true);
httpRequest.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
httpRequest.send(L_postData);
};
}
/*
Short class that just simplifies access to those 2 classes before
PARAMS:
newMessageServerURL - string - URL of file, which saves and validates the message
longPollServerURL - string - URL of server file, which acts as long poll server
lastIdGetURL - string - URL of txt file, where last message id is saved
messageReceivedCallback - function - callback to get called when new message is received, it is called with 4 params: id of the message, time when the message was sent as unix timestamp, nickname of the person who sent it, message text itself
sentMessageCallback - function - function to handle response from server (ok / wrongFormat / noName / ... status etc... (that depends on how you make your server))
*/
function ServerCommunicator(newMessageServerURL, longPollServerURL, lastIdGetURL, messageReceivedCallback, sentMessageCallback) {
var longPoll = new ChatLongPoll(longPollServerURL, lastIdGetURL, messageReceivedCallback);
var sendMessage = new ChatSendMessage(newMessageServerURL, sentMessageCallback);
this.sendMessage = sendMessage.sendMessage;
this.startLongPoll = longPoll.startLongPoll;
}
``` | For the XSS part, here's some resources. It would be better off if I just referenced them rather than write the entire thing down. The second one might be the one you want:
* [https://www.owasp.org/index.php/XSS\_(Cross\_Site\_Scripting)\_Prevention\_Cheat\_Sheet](https://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet)
* <https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet>
By the definition of [`htmlspecialchars`](http://docs.php.net/manual/en/function.htmlspecialchars.php):
>
> Certain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings. This function returns a string with these conversions made. If you require all input substrings that have associated named entities to be translated, use htmlentities() instead.
>
>
>
You might want to look at [`htmlentities`](http://docs.php.net/manual/en/function.htmlentities.php) instead.
Also, in my experience, even if you are safe with just one input, you can still be victim of fragmented XSS, where an XSS attack is broken into parts which actually pass through preventive measures. The last time I did such was on a Wordpress plugin, which also happens to be a chat widget. What I did was carefully craft my XSS where the first half was injected to the username and the second continued on as the message. The first half commented out the code in between until the second half.
For the JS part, mostly reusability and some notes:
```
// You could factor out the XHR to their own functions and make them handy
// Notes:
// - I haven't seen onload used in xhr. Read more about onreadystatechange event
// and readystate properties for cross-browser compatibility.
var MyAJAX = {
get : function (url, data,callback) {
var xhr = new XMLHttpRequest();
// Serialize
var serializedData = Object.keys(data).reduce(function(serialized,key,index){
if(index) serialized += '&';
serialized += encodeURI(key + '=' data[key]);
return serialized;
},'?');
xhr.open("GET", url + serializedData);
xhr.onload = function(e){
callback.call(null,e.response);
};
xhr.send()
},
post: function (url, data,callback) {
var formData = new FormData();
var xhr = new XMLHttpRequest();
// For each in data object, append
Object.keys(data).forEach(function(key){
fd.append(key,data[key]);
});
xhr.open("POST", url);
xhr.onload = function(e){
callback.call(null,e.response);
};
xhr.send(formData);
}
}
// Cache DOM elements
// Notes:
// - If you use an ID, you're better off with getElementById rather than querySelectorAll
var usr = "";
var cb = document.getElementById("chatbar");
var chatLog = document.getElementById("chatlog");
// And your AJAX function looks as clean as this when used
setInterval(function(){
MyAJAX.get('uhh.txt',{
a : Math.random()
},function(data){
chatLog.innerHTML = data.replace(/\n/g, "<br/>");
});
},1000);
function chat(m) {
MyAJAX.post('uhh.php',{
"usr" : usr,
"msg" : m
},function(data){
// Do something when sent
});
}
// I suggest you don't place this event on window. Place it on the
// element for efficiency.
cb.addEventListener('keyup',function(e){
var identifier = e.keyIdentifier;
if (identifier == "U+00BF") {
cb.focus();
} else if (e.keyIdentifier == "Enter") {
if (usr) {
chat(cb.value);
cb.value = "";
} else {
usr = cb.value;
cb.placeholder = "Press / to chat";
cb.value = "";
// This only limits this on the browser. There's no one
// stopping anyone sending more than this without using a browser
cb.maxLength = 9001;
}
}
});
``` |
10,287,618 | Well the motivation is the idea that a python test runner would have functionality similar to [nose](http://readthedocs.org/docs/nose/en/latest/)
the difference being it being able to run C Unit tests. I am yet to find anything similar.
Here are some of the requirements of test runner.
1. The test runner is responsible for running a series of tests and gathering results for all of them.
2. The testrunner should support multiple test methods ( including self-describing, reftest and script )
3. Must be able to load tests automatically based on manifest files.
4. The test runner must be able to order test cases smartly
5. The test runner must allow for tests to be run in random order and repetitively
6. The test runner must allow for complete and partial execution of tests
7. It must be possible to create test runners that work on various platforms
8. The test runner must provide some way to output collected results
9. The test runner must allow for automatic and manual gathering of context information
10. The test runner must include context information in collected results
11. The test runner must support positive and negative testing
12. The test runner must support testing of time based information
13. The test runner must allow a test to report its result automatically
14. The test runner must allow humans to report on manual test outcome
15. The test runner must allow reftests to be run by humans
16. The test runner should allow for humans to comment on a test outcome
17. The test runner must allow tests to be created on smaller tests
18. The test runner must be usable by external entities and individuals | 2012/04/23 | ['https://Stackoverflow.com/questions/10287618', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/454488/'] | Rather than doing all this yourself (a tremedous piece of work), how about using `py.test`? It's a powerful test runner, among other things. It satisfies most of your requirements (well, those that are clear - some don't make a lot of sense to me) out of the box, and is customizable enough to add anything you need beyond that.
The killer feature, however, is that they actively developed and documented a way to do precisely this: [Working with non-python tests](http://pytest.org/latest/example/nonpython.html). The example over there is minimal, but the API seems powerful enough. In fact, you wouldn't be the first to use this capability (giving you another source of information) - someone already built a [JavaScript testing framework](http://pypi.python.org/pypi/oejskit) with it. | A much better solution than the already proposed py.test is PySys System Test Framework that solves almost all of the points above, and you can extend very easily to achieve the few that are not already covered
You will have to write a common "execute" method that start the C test as an external process and then grep on a string that indicate commonly that it is passing. It is not more than 15 lines of code.
The framework will do the rest for you |
29,556,212 | I have a huge document and I need to listen on all `mousemoves` on this document.
My first obvious idea was `addEventListener()` on body, but it might introduce some performance issues (you know, bubbling stuff).
There is a mythical parameter in `addEventListener()` - `useCapture`. I don't quite get the inner workings of event propagation in DOM, but it looks promising.
Will it be better to use capture phase, or it is not worth it? | 2015/04/10 | ['https://Stackoverflow.com/questions/29556212', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/300639/'] | The capture phase works as follows: instead of bubbling from the innermost DOM element up and out, capture starts out from the window and goes in.
Capture phase happens before the bubbling phase, so it's handy if you want to stop the propagation of an event before it even gets to the inner DOM elements.
Which can also be a problem if done inadvertently. If you set your mousemove at capture phase in the body and stop the propagation of that event for some reason, no other DOM element is going to get a mousemove event anymore.
See the always enlightening Quirksmode post on it: <http://www.quirksmode.org/js/events_order.html> | jQuery did have `live` deprecated due to the fact that [bubbling does take time to reach the root](http://www.sitepoint.com/on-vs-live-review/) (where `live` placed all handlers). For small stuff, this isn't an issue. But if you have a deep DOM tree or a lot of things happening, then this becomes a big problem. The better replacement for jQuery was `on` as you can decide how far up (or down) the tree the handler can be attached. This limited what elements the event can be triggered from, as well as the number of nodes to bubble up.
The bigger issue here is what runs in response to the event, as `mousemove` fires several times during movement. Binding it to body means that the code you attached to the event has to fire every time you move the mouse. You might want to limit what runs in response to the event, or keep the attached code as lean and as non-blocking as possible. |
2,491,023 | I am interested in properties of regular neighbourhood meshes, but I feel like
I'm missing *keywords* to investigate further.
---
In the 2D world I, like both triangular neighbourhood and square neighbourhood, because:
* they are both **regular**, which means to me:
+ there is always *same distance* between two close neighbours (say, 1)
+ there is always the *same angle* between directions towards two closest neighbours (60° for the triangle, 90° for the square)
[](https://i.stack.imgur.com/9xPfm.jpg)[](https://i.stack.imgur.com/Uh0S8.gif)
**But** I like triangular best, because:
* it offers more neighbours than the square (6 against 4 only)
* 2 closest neighbours are also neighbours themselves (whereas in the square world, if your he-friend goes one step north and your she-friend goes one step east, they are now *more* than 1 step away)
---
In the 3D world, I only know the square neighborhood well.
[](https://i.stack.imgur.com/r0suj.png)
But I don't like how it only offers 6 neighbours and how this last "neighbours neighbouring" feature is not respected.
Is there another regular 3D neighbourhood with more than 6 neigbours per node and featuring "close-neighbours-neighbouring"? | 2017/10/26 | ['https://math.stackexchange.com/questions/2491023', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/165143/'] | My interpretation of the close-neighbours-neighbouring property is as follows:
>
> For each node, the minimum separation among all distinct pairs of its neighbours is the same as the distance between the node and its neighbours.
>
>
>
Then the [fcc lattice](https://en.wikipedia.org/wiki/Close-packing_of_equal_spheres) (right side of the diagram below) satisfies the two properties, having 12 neighbours per node.

The spaces between the nodes then form the [alternated cubic/tetrahedral–octahedral honeycomb](https://en.m.wikipedia.org/wiki/Tetrahedral-octahedral_honeycomb).
 | No; my understanding of the "close neighbors neighboring" property is that the cells would have to be tetrahedra, and there is no regular tetrahedral tiling of space.
You can get something close to a tesselation that you want by [computing](http://A%20Hierarchical%20Approach%20for%20Regular%20Centroidal%20Voronoi%20Tessellations) a (dual of a) cetroidal Voronoi tesselation of a region of space. It will be irregular (so will not have perfectly equal distances and angles) of course.
[](https://i.stack.imgur.com/7ruSB.jpg) |
2,491,023 | I am interested in properties of regular neighbourhood meshes, but I feel like
I'm missing *keywords* to investigate further.
---
In the 2D world I, like both triangular neighbourhood and square neighbourhood, because:
* they are both **regular**, which means to me:
+ there is always *same distance* between two close neighbours (say, 1)
+ there is always the *same angle* between directions towards two closest neighbours (60° for the triangle, 90° for the square)
[](https://i.stack.imgur.com/9xPfm.jpg)[](https://i.stack.imgur.com/Uh0S8.gif)
**But** I like triangular best, because:
* it offers more neighbours than the square (6 against 4 only)
* 2 closest neighbours are also neighbours themselves (whereas in the square world, if your he-friend goes one step north and your she-friend goes one step east, they are now *more* than 1 step away)
---
In the 3D world, I only know the square neighborhood well.
[](https://i.stack.imgur.com/r0suj.png)
But I don't like how it only offers 6 neighbours and how this last "neighbours neighbouring" feature is not respected.
Is there another regular 3D neighbourhood with more than 6 neigbours per node and featuring "close-neighbours-neighbouring"? | 2017/10/26 | ['https://math.stackexchange.com/questions/2491023', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/165143/'] | My interpretation of the close-neighbours-neighbouring property is as follows:
>
> For each node, the minimum separation among all distinct pairs of its neighbours is the same as the distance between the node and its neighbours.
>
>
>
Then the [fcc lattice](https://en.wikipedia.org/wiki/Close-packing_of_equal_spheres) (right side of the diagram below) satisfies the two properties, having 12 neighbours per node.

The spaces between the nodes then form the [alternated cubic/tetrahedral–octahedral honeycomb](https://en.m.wikipedia.org/wiki/Tetrahedral-octahedral_honeycomb).
 | Consider that a rhombic dodecahedron tiles Euclidean 3 space. |
36,254,414 | I have a Prism Shell with two modules. One module is supposed to be the main application mock, `MainAppMock`, and the other module is supposed to be whatever that main system is using as a region, `ModuleOne`. Could be one, could be a million module.
The issue is understanding how Prism works. The `MainAppModule` initializes properly unless I call it's namespace in the `Bootstrapper` `MainWindow.xaml` file.
My question: Is this because it is loading the module at run time when I am calling that namespace and therefore `Prism` doesn't load it because it is already loaded? What is actually happening behind the scenes?
Shell:
```
class Bootstrapper : NinjectBootstrapper
{
protected override DependencyObject CreateShell()
{
return Kernel.Get<MainWindow>();
}
protected override void InitializeShell()
{
Application.Current.MainWindow = (Window)Shell;
Application.Current.MainWindow.Show();
}
protected override IModuleCatalog CreateModuleCatalog()
{
return new DirectoryModuleCatalog
{
ModulePath = AppDomain.CurrentDomain.BaseDirectory
};
}
}
```
MainAppMock and ModuleOne are the same except for the name.
ModuleOne Class:
```
[Module(ModuleName = "ModuleOne.Module")]
public class Module : IModule
{
private readonly IRegionManager _regionManager;
private readonly IKernel _kernel;
public Module(IRegionManager regionManager, IKernel kernel)
{
_regionManager = regionManager;
_kernel = kernel;
}
public void Initialize()
{
}
}
```
The problem is here. In the `Bootstrapper` `MainWindow`:
```
<Window x:Class="PrismTest.MainWindow"
xmlns:mainAppMock="clr-namespace:MainAppMock;assembly=MainAppMock"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<mainAppMock:MainUserControl />
</Grid>
```
Note: It works fine if I remove the `mainAppMock` namespace as mentioned above. | 2016/03/28 | ['https://Stackoverflow.com/questions/36254414', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3029887/'] | As this question has now changed so much since I first asked it (i.e. first I thought this was a memory/ struct issue, then it became a compiler issue, then I finally figured out it was a IDE issue), therefore I decided to create a new question altogether: [Output for CLion IDE sometimes cuts off when executing a program](https://stackoverflow.com/questions/36270122/clion-output-cuts-off).
The answer for this specific question is that this is an issue with the CLion IDE. To fix this issue, compile and run the code using a terminal and the output works fine.
Thanks to @Dominik Gebhar & @Jonathan Leffler for the help!!! | **fscanf()** returns the number of characters read or zero at end of file, while **fgetc(fp)** returns a character or EOF when end of file is reached.
You are mixing the two methods of eof detection. |
63,154,860 | ```
table_name='Customer$'
if table_name.startswith('$'):
table_name=table_name[1:]
if table_name.endswith('$'):
table_name=table_name[:-1]
```
I tried with the above code it gives me correct result as
```
Customer
```
Is there any optimized way of doing it? please reply | 2020/07/29 | ['https://Stackoverflow.com/questions/63154860', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13818054/'] | Use `.strip()`:
```
table_name = '$Customer$'.strip('$')
```
This will remove all `$`s from the start and end and do nothing if there aren't dollars surrounding the string. | ```
'$Customer$'.strip('$')
```
`strip()` method removes any leading (spaces at the beginning) and trailing (spaces at the end) characters (space is the default leading character to remove). By default trailing and leading spaces are removed. If an argument of character/s should be removed has been passed, then that character/s will be removed from leading and trailing poistions |
63,154,860 | ```
table_name='Customer$'
if table_name.startswith('$'):
table_name=table_name[1:]
if table_name.endswith('$'):
table_name=table_name[:-1]
```
I tried with the above code it gives me correct result as
```
Customer
```
Is there any optimized way of doing it? please reply | 2020/07/29 | ['https://Stackoverflow.com/questions/63154860', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13818054/'] | Use `.strip()`:
```
table_name = '$Customer$'.strip('$')
```
This will remove all `$`s from the start and end and do nothing if there aren't dollars surrounding the string. | just use `.strip()` it works like `trim()`
```
table_name = '$Cu$$stomer$'
ans = table_name.strip('$')
print(ans) # output Cu$$stomer
```
The `strip()` method returns a copy of the string by removing both the leading and the trailing characters (based on the string argument passed).
you can learn more about `strip()` from here: <https://www.programiz.com/python-programming/methods/string/strip> |
22,361,630 | It's a small piece of code, but I can't get it to work.
I have a menu which is filled dynamically with javascript, and I add an eventlistener on click for every button.
Now every button needs a different function, so I loop through them
```
var list = $("a");
for (var i=0; i<list.length; i++) {
$(list[i]).on("click",function(){alert(i);});
}
```
With this code every button will give me an alert with 5, instead of 1,2,3,...
How do I fix this? | 2014/03/12 | ['https://Stackoverflow.com/questions/22361630', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] | Use [each()](https://api.jquery.com/each/) that's what it's for:
```
var list = $("a");
list.each(function(index){
$(this).on("click", function(){alert(index);});
});
```
[DEMO](http://jsfiddle.net/7HeeA/) | The value of i changes in the loop, but after the loop is finished the value of i is 5. Whenever you call the alert, it is looking for the variable i, whose value is now 5. You need to store the increment value of i somewhere for each thing. In this example, I give each button an HTML5 data attribute called `data-myvalue`.
```
for (var i=0;i<ins.length;i++){
ins[i].setAttribute('data-myvalue',i);
ins[i].addEventListener('click',
function(){alert(this.getAttribute('data-myvalue'));});
}
```
[jsfiddle](http://jsfiddle.net/PgYaz/)
But you can also store the information in javascript array. |
22,361,630 | It's a small piece of code, but I can't get it to work.
I have a menu which is filled dynamically with javascript, and I add an eventlistener on click for every button.
Now every button needs a different function, so I loop through them
```
var list = $("a");
for (var i=0; i<list.length; i++) {
$(list[i]).on("click",function(){alert(i);});
}
```
With this code every button will give me an alert with 5, instead of 1,2,3,...
How do I fix this? | 2014/03/12 | ['https://Stackoverflow.com/questions/22361630', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] | Use [each()](https://api.jquery.com/each/) that's what it's for:
```
var list = $("a");
list.each(function(index){
$(this).on("click", function(){alert(index);});
});
```
[DEMO](http://jsfiddle.net/7HeeA/) | in your html code call a function favbrowser whenever a item is selected using onchange event by writting
```
<select id="myList" onchange="favBrowser()">
<option></option>
</select>
```
and then in javascript do this to print the name of menu item
```
<script>
function favBrowser()
{
var mylist=document.getElementById("myList");
alert(mylist.options[mylist.selectedIndex].text);
}
</script>
``` |
581,274 | I've just completed a custom board that uses an STM32 F4 chip and to program it I have implemented the JTAG 10-pin connecter as seen here:
[](https://i.stack.imgur.com/0qpVo.png)
Now, this works fine and I can program the chip with it using the included ST-LINK V2 on the various Nucleo boards using jumpers. To make my life easier, I decided to purchase an ST-LINK V2 clone so I can just insert the debugger straight in to the connector without the hassle of using jumper wires and remembering which wires go to which pin. However, the pinout on the ST-LINK clones is different and this is true for **all** of the clones I have seen. The pinout is here:
[](https://i.stack.imgur.com/zJagj.png)
Why is this so different? Why does the pinout of these clones differ to the pinout of the common 10-pin JTAG? Is this a separate pinout standard or just something unique to these common clone debuggers? | 2021/08/12 | ['https://electronics.stackexchange.com/questions/581274', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/121457/'] | The ST-Link comes with an 20 pin connector. None of shown clones actually cloned this.
ST recommends buying the [TC2050-ARM2010](https://www.tag-connect.com/wp-content/uploads/bsk-pdf-manager/2021/02/TC2050-ARM2010-2021.pdf) adapter for the 10 pin connector. (segger has some as well)
Which has a pinout according to your diagram.
You clones don't even have SWO. And they also offer 5V and 3V, as typical on cheap programmers.
A feature that kills chips by powering them with the wrong voltage!
Don't buy clones. A genuine ST Link V2 is €30, or a V3 for €40.
*To make your life truly easy, get those tag connect pogo pin cables. You don't even need an expensive header anymore.* | They are clones that most likely are using ripped off original firmware and they are trying to allure the hobbyist market with hobbyist-friendly features not present in the original product.
So they can do whatever they want with their products. The clones actually provide various supply voltages **to** the programmed target board, which means some pins need to be repurposed for that, instead of using a suggested pinout with a suggested standard connector.
So yes, they are not identical clones and may not replace an original product in all purposes.
And since the official products are meant to only receive a reference IO supply from the target, it means that powering the target and also connecting power line to clone programmer means the supplies are shorted together. As it is so easy to do that accidentally, there is a risk of damaging the target board, clone programmer, USB port or the whole PC, getting them cheaply is not worth it, and buying clones basically means you might be rewarding the cloners for potentially ripping the original product firmware. |
10,565,752 | For example, suppose I have `std::string` containing UNIX-style path to some file:
```
string path("/first/second/blah/myfile");
```
Suppose now I want to throw away file-related information and get path to 'blah' folder from this string. So is there an efficient (saying 'efficient' I mean 'without any copies') way of truncating this string so that it contains `"/first/second/blah"` only?
Thanks in advance. | 2012/05/12 | ['https://Stackoverflow.com/questions/10565752', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1096537/'] | If N is known, you can use
```
path.erase(N, std::string::npos);
```
If N is not known and you want to find it, you can use any of the search functions. In this case you 'll want to find the last slash, so you can use [`rfind`](http://en.cppreference.com/w/cpp/string/basic_string/rfind) or [`find_last_of`](http://en.cppreference.com/w/cpp/string/basic_string/find_last_of):
```
path.erase(path.rfind('/'), std::string::npos);
path.erase(path.find_last_of('/'), std::string::npos);
```
There's even a variation of this based on iterators:
```
path.erase (path.begin() + path.rfind('/'), path.end());
```
That said, if you are going to be manipulating paths for a living it's better to use a library designed for this task, such as [Boost Filesystem](http://www.boost.org/doc/libs/1_49_0/libs/filesystem/v3/doc/index.htm). | While the accepted answer for sure works, the most efficient way to throw away the end of a string is to call the `resize` method, in your case just:
```
path.resize(N);
``` |
35,736,070 | Using `asp.net 5` I'd like my controller to be injected with a `Func<T>`instead of `T`
For example:
```cs
public HomeController(Func<Interfaces.IUnitOfWork> uow)
```
Instead of
```cs
public HomeController(Interfaces.IUnitOfWork uow)
```
Is it possible with the built-in DI or am I forced to move to an external DI? | 2016/03/02 | ['https://Stackoverflow.com/questions/35736070', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/20335/'] | As far as I'm aware deferring dependencies like this isn't possible using the current default IoC container within ASP.NET Core. I've not been able to get it working anyway!
To defer the initialisation of dependencies like this you'll need to implement an existing, more feature rich IoC container. | While there is no built in Func building support in the default dependency injection for .net core we can build an extension method to add in all the missing funcs. We just need to make sure we call it at the end of registration.
```
public static class ServiceCollectionExtensions
{
private static MethodInfo GetServiceMethod;
static ServiceCollectionExtensions()
{
Func<IServiceProvider, object> getServiceMethod = ServiceProviderServiceExtensions.GetService<object>;
GetServiceMethod = getServiceMethod.Method.GetGenericMethodDefinition();
}
/// <summary>
/// Registers all Funcs in constructors to the ServiceCollection - important to call after all registrations
/// </summary>
/// <param name="collection"></param>
/// <returns></returns>
public static IServiceCollection AddFactories(this IServiceCollection collection)
{
// Get a list of all Funcs used in constructors of regigstered types
var funcTypes = new HashSet<Type>(collection.Where(x => x.ImplementationType != null)
.Select(x => x.ImplementationType)
.SelectMany(x => x.GetConstructors(BindingFlags.Public | BindingFlags.Instance))
.SelectMany(x => x.GetParameters())
.Select(x => x.ParameterType)
.Where(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(Func<>)));
// Get a list of already registered Func<> and remove them from the hashset
var registeredFuncs = collection.Select(x => x.ServiceType)
.Where(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(Func<>));
funcTypes.ExceptWith(registeredFuncs);
// Each func build the factory for it
foreach (var funcType in funcTypes)
{
var type = funcType.GetGenericArguments().First();
collection.AddTransient(funcType, FuncBuilder(type));
}
return collection;
}
/// <summary>
/// This build expression tree for a func that is equivalent to
/// Func<IServiceProvider, Func<TType>> factory = serviceProvider => new Func<TType>(serviceProvider.GetService<TType>);
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
private static Func<IServiceProvider, object> FuncBuilder(Type type)
{
var serviceProvider = Expression.Parameter(typeof(IServiceProvider), "serviceProvider");
var method = GetServiceMethod.MakeGenericMethod(type);
var call = Expression.Call(method, serviceProvider);
var returnType = typeof(Func<>).MakeGenericType(type);
var returnFunc = Expression.Lambda(returnType, call);
var func = Expression.Lambda(typeof(Func<,>).MakeGenericType(typeof(IServiceProvider), returnType), returnFunc, serviceProvider);
var factory = func.Compile() as Func<IServiceProvider, object>;
return factory;
}
}
```
In AddFactories we get a list of all the concreate types that are registered then check their constructors for any Func<>. From that list remove any Func that has been registered before. Using some expressiontrees we build the needed Funcs.
The code is also over in [codereview](https://codereview.stackexchange.com/q/210507/52662), minus the check for already registered funcs. |
35,736,070 | Using `asp.net 5` I'd like my controller to be injected with a `Func<T>`instead of `T`
For example:
```cs
public HomeController(Func<Interfaces.IUnitOfWork> uow)
```
Instead of
```cs
public HomeController(Interfaces.IUnitOfWork uow)
```
Is it possible with the built-in DI or am I forced to move to an external DI? | 2016/03/02 | ['https://Stackoverflow.com/questions/35736070', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/20335/'] | `Func<T>` does not get registered or resolved by default but there is nothing stopping you from registering it yourself.
e.g.
```
services.AddSingleton(provider =>
new Func<IUnitOfWork>(() => provider.GetService<IUnitOfWork>()));
```
Note that you will also need to register IUnitOfWork itself in the usual way. | I wrote a little **extension method** that registres the service and the factory (`Func<T>`):
```cs
public static class IServiceCollectionExtension
{
public static IServiceCollection AddFactory<TService, TServiceImplementation>(this IServiceCollection serviceCollection)
where TService : class
where TServiceImplementation : class, TService
{
return serviceCollection
.AddTransient<TService, TServiceImplementation>();
.AddSingleton<Func<TService>>(sp => sp.GetRequiredService<TService>);
}
}
```
**Usage**:
```cs
serviceCollection
.AddFactory<IMyInterface, MyImplementation>()
``` |
35,736,070 | Using `asp.net 5` I'd like my controller to be injected with a `Func<T>`instead of `T`
For example:
```cs
public HomeController(Func<Interfaces.IUnitOfWork> uow)
```
Instead of
```cs
public HomeController(Interfaces.IUnitOfWork uow)
```
Is it possible with the built-in DI or am I forced to move to an external DI? | 2016/03/02 | ['https://Stackoverflow.com/questions/35736070', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/20335/'] | `Func<T>` does not get registered or resolved by default but there is nothing stopping you from registering it yourself.
e.g.
```
services.AddSingleton(provider =>
new Func<IUnitOfWork>(() => provider.GetService<IUnitOfWork>()));
```
Note that you will also need to register IUnitOfWork itself in the usual way. | There are a few options available to you, the first is you can switch over to use the incredible [Lamar](https://jasperfx.github.io/lamar/getting_started/) (with it's [ASP.NET Core integration](https://jasperfx.github.io/lamar/getting_started/#sec1)).
For the most part, switching to Lamar is a few lines of code, and you'll be able to resolve `Func<>` and `Lazy<>` all day long.
I've been using it at scale for a while on a large microservices based platform and we're completely happy with it \*.
If you don't want to move over to Lamar, you can use this for resolving `Lazy<>` (sorry, I've tried and tried, and I can't get it to work with `Func<>`:
```
// Add to your Service Collection.
services.AddTransient(typeof(Lazy<>), typeof(LazyServiceFactory<>));
class LazyServiceFactory<T> : Lazy<T>
{
public LazyServiceFactory(IServiceProvider serviceProvider)
: base(() => serviceProvider.GetRequiredService<T>())
{
}
}
```
And just for completeness, here's a test too.
```
// And some tests...
[TestMethod]
[DataTestMethod]
[DataRow(ServiceLifetime.Transient)]
[DataRow(ServiceLifetime.Scoped)]
[DataRow(ServiceLifetime.Singleton)]
public void Resolve_GivenLazyilyRegisteredService_CanResolve(ServiceLifetime serviceLifetime)
{
// Arrange
IServiceProvider serviceProvider = CreateServiceProvider(serviceLifetime);
using IServiceScope scope = serviceProvider.CreateScope();
// Act
Func<Lazy<ClassHello>> result = () => scope.ServiceProvider.GetRequiredService<Lazy<ClassHello>>();
// Assert
result
.Should()
.NotThrow()
.And
.Subject()
.Value
.Should()
.NotBeNull();
}
static IServiceProvider CreateServiceProvider(ServiceLifetime serviceLifetime)
{
IServiceCollection services = new ServiceCollection();
services.Add(new ServiceDescriptor(typeof(Lazy<>), typeof(LazyServiceFactory<>), serviceLifetime));
services.Add(new ServiceDescriptor(typeof(ClassHello), typeof(ClassHello), serviceLifetime));
return services.BuildServiceProvider(true);
}
```
I've not put this through it's paces as I use Lamar pretty much exclusivly now, but this has come in handy for smaller/ disposable projects.
\* My only minor issue is that it doesn't support `IAsyncDisposable` [yet](https://github.com/JasperFx/lamar/issues/243). |
35,736,070 | Using `asp.net 5` I'd like my controller to be injected with a `Func<T>`instead of `T`
For example:
```cs
public HomeController(Func<Interfaces.IUnitOfWork> uow)
```
Instead of
```cs
public HomeController(Interfaces.IUnitOfWork uow)
```
Is it possible with the built-in DI or am I forced to move to an external DI? | 2016/03/02 | ['https://Stackoverflow.com/questions/35736070', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/20335/'] | `Func<T>` does not get registered or resolved by default but there is nothing stopping you from registering it yourself.
e.g.
```
services.AddSingleton(provider =>
new Func<IUnitOfWork>(() => provider.GetService<IUnitOfWork>()));
```
Note that you will also need to register IUnitOfWork itself in the usual way. | You can register a `Func<T>` or a delegate with a `ServiceCollection`. I recommend a delegate because it allows you to distinguish between different methods with identical signatures.
Here's an example.
```
public interface IThingINeed {}
public class ThingINeed : IThingINeed { }
public delegate IThingINeed ThingINeedFactory();
public class DelegateRegistrationTests
{
[Test]
public void RegisterDelegateFromDependency()
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddTransient<IThingINeed, ThingINeed>();
serviceCollection.AddTransient<ThingINeedFactory>(
provider => provider.GetService<IThingINeed>);
var serviceProvider = serviceCollection.BuildServiceProvider();
var factoryMethod = serviceProvider.GetService<ThingINeedFactory>();
var output = factoryMethod();
Assert.IsInstanceOf<ThingINeed>(output);
}
}
```
This almost looks like a service locator because the function we're resolving is actually `IServiceCollection.GetService<ThingINeedFactory>()`. But that's hidden in the composition root. A class that injects this delegate depends on the delegate, not on the implementation.
You can use the same approach if the method you want to return belongs to a class that the container must resolve.
```
public interface IThingINeed
{
string SayHello();
}
public class ThingINeed : IThingINeed
{
private readonly string _greeting;
public ThingINeed(string greeting)
{
_greeting = greeting;
}
public string SayHello() => _greeting;
}
public class ThingINeedFactory
{
public IThingINeed Create(string input) => new ThingINeed(input);
}
public delegate IThingINeed ThingINeedFactoryMethod(string input);
public class DelegateRegistrationTests
{
[Test]
public void RegisterDelegateFromDependency()
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton<IThingINeed, ThingINeed>();
serviceCollection.AddSingleton<ThingINeedFactory>();
serviceCollection.AddSingleton<ThingINeedFactoryMethod>(provider =>
provider.GetService<ThingINeedFactory>().Create);
var serviceProvider = serviceCollection.BuildServiceProvider();
var factoryMethod = serviceProvider.GetService<ThingINeedFactoryMethod>();
var created = factoryMethod("abc");
var greeting = created.SayHello();
Assert.AreEqual("abc", greeting);
}
}
```
Here's an extension method to (maybe) make it a little bit easier:
```
public static class ServiceCollectionExtensions
{
public static IServiceCollection RegisterDelegate<TSource, TDelegate>(
this IServiceCollection serviceCollection,
Func<TSource, TDelegate> getDelegateFromSource)
where TDelegate : class
{
return serviceCollection.AddSingleton(provider =>
getDelegateFromSource(provider.GetService<TSource>()));
}
}
serviceCollection
.RegisterDelegate<ThingINeedFactory, ThingINeedFactoryMethod>(
factory => factory.Create);
``` |
35,736,070 | Using `asp.net 5` I'd like my controller to be injected with a `Func<T>`instead of `T`
For example:
```cs
public HomeController(Func<Interfaces.IUnitOfWork> uow)
```
Instead of
```cs
public HomeController(Interfaces.IUnitOfWork uow)
```
Is it possible with the built-in DI or am I forced to move to an external DI? | 2016/03/02 | ['https://Stackoverflow.com/questions/35736070', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/20335/'] | You can register a `Func<T>` or a delegate with a `ServiceCollection`. I recommend a delegate because it allows you to distinguish between different methods with identical signatures.
Here's an example.
```
public interface IThingINeed {}
public class ThingINeed : IThingINeed { }
public delegate IThingINeed ThingINeedFactory();
public class DelegateRegistrationTests
{
[Test]
public void RegisterDelegateFromDependency()
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddTransient<IThingINeed, ThingINeed>();
serviceCollection.AddTransient<ThingINeedFactory>(
provider => provider.GetService<IThingINeed>);
var serviceProvider = serviceCollection.BuildServiceProvider();
var factoryMethod = serviceProvider.GetService<ThingINeedFactory>();
var output = factoryMethod();
Assert.IsInstanceOf<ThingINeed>(output);
}
}
```
This almost looks like a service locator because the function we're resolving is actually `IServiceCollection.GetService<ThingINeedFactory>()`. But that's hidden in the composition root. A class that injects this delegate depends on the delegate, not on the implementation.
You can use the same approach if the method you want to return belongs to a class that the container must resolve.
```
public interface IThingINeed
{
string SayHello();
}
public class ThingINeed : IThingINeed
{
private readonly string _greeting;
public ThingINeed(string greeting)
{
_greeting = greeting;
}
public string SayHello() => _greeting;
}
public class ThingINeedFactory
{
public IThingINeed Create(string input) => new ThingINeed(input);
}
public delegate IThingINeed ThingINeedFactoryMethod(string input);
public class DelegateRegistrationTests
{
[Test]
public void RegisterDelegateFromDependency()
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton<IThingINeed, ThingINeed>();
serviceCollection.AddSingleton<ThingINeedFactory>();
serviceCollection.AddSingleton<ThingINeedFactoryMethod>(provider =>
provider.GetService<ThingINeedFactory>().Create);
var serviceProvider = serviceCollection.BuildServiceProvider();
var factoryMethod = serviceProvider.GetService<ThingINeedFactoryMethod>();
var created = factoryMethod("abc");
var greeting = created.SayHello();
Assert.AreEqual("abc", greeting);
}
}
```
Here's an extension method to (maybe) make it a little bit easier:
```
public static class ServiceCollectionExtensions
{
public static IServiceCollection RegisterDelegate<TSource, TDelegate>(
this IServiceCollection serviceCollection,
Func<TSource, TDelegate> getDelegateFromSource)
where TDelegate : class
{
return serviceCollection.AddSingleton(provider =>
getDelegateFromSource(provider.GetService<TSource>()));
}
}
serviceCollection
.RegisterDelegate<ThingINeedFactory, ThingINeedFactoryMethod>(
factory => factory.Create);
``` | I have solution below
```cs
public static IServiceCollection WithFunc<TService>(this IServiceCollection serviceCollection) where TService : class {
var serviceType = typeof(TService);
var serviceDescriptor = serviceCollection.LastOrDefault(x => x.ServiceType == serviceType);
Debug.Assert(serviceDescriptor != null);
serviceCollection.Add(ServiceDescriptor.Describe(typeof(Func<TService>),
scope => new Func<TService>(scope.GetRequiredService<TService>),
serviceDescriptor.Lifetime));
return serviceCollection;
}
```
usage
```cs
[Fact]
void with_func() {
var services = new ServiceCollection()
.AddTransient<IFoo, Foo>().WithFunc<IFoo>()
.BuildServiceProvider();
var fooFunc = services.GetRequiredService<Func<IFoo>>();
Assert.NotNull(fooFunc);
}
```
more detail in gist <https://gist.github.com/leoninew/d2f174fe1422e453c60fb78e69342310> |
35,736,070 | Using `asp.net 5` I'd like my controller to be injected with a `Func<T>`instead of `T`
For example:
```cs
public HomeController(Func<Interfaces.IUnitOfWork> uow)
```
Instead of
```cs
public HomeController(Interfaces.IUnitOfWork uow)
```
Is it possible with the built-in DI or am I forced to move to an external DI? | 2016/03/02 | ['https://Stackoverflow.com/questions/35736070', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/20335/'] | You can register a `Func<T>` or a delegate with a `ServiceCollection`. I recommend a delegate because it allows you to distinguish between different methods with identical signatures.
Here's an example.
```
public interface IThingINeed {}
public class ThingINeed : IThingINeed { }
public delegate IThingINeed ThingINeedFactory();
public class DelegateRegistrationTests
{
[Test]
public void RegisterDelegateFromDependency()
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddTransient<IThingINeed, ThingINeed>();
serviceCollection.AddTransient<ThingINeedFactory>(
provider => provider.GetService<IThingINeed>);
var serviceProvider = serviceCollection.BuildServiceProvider();
var factoryMethod = serviceProvider.GetService<ThingINeedFactory>();
var output = factoryMethod();
Assert.IsInstanceOf<ThingINeed>(output);
}
}
```
This almost looks like a service locator because the function we're resolving is actually `IServiceCollection.GetService<ThingINeedFactory>()`. But that's hidden in the composition root. A class that injects this delegate depends on the delegate, not on the implementation.
You can use the same approach if the method you want to return belongs to a class that the container must resolve.
```
public interface IThingINeed
{
string SayHello();
}
public class ThingINeed : IThingINeed
{
private readonly string _greeting;
public ThingINeed(string greeting)
{
_greeting = greeting;
}
public string SayHello() => _greeting;
}
public class ThingINeedFactory
{
public IThingINeed Create(string input) => new ThingINeed(input);
}
public delegate IThingINeed ThingINeedFactoryMethod(string input);
public class DelegateRegistrationTests
{
[Test]
public void RegisterDelegateFromDependency()
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton<IThingINeed, ThingINeed>();
serviceCollection.AddSingleton<ThingINeedFactory>();
serviceCollection.AddSingleton<ThingINeedFactoryMethod>(provider =>
provider.GetService<ThingINeedFactory>().Create);
var serviceProvider = serviceCollection.BuildServiceProvider();
var factoryMethod = serviceProvider.GetService<ThingINeedFactoryMethod>();
var created = factoryMethod("abc");
var greeting = created.SayHello();
Assert.AreEqual("abc", greeting);
}
}
```
Here's an extension method to (maybe) make it a little bit easier:
```
public static class ServiceCollectionExtensions
{
public static IServiceCollection RegisterDelegate<TSource, TDelegate>(
this IServiceCollection serviceCollection,
Func<TSource, TDelegate> getDelegateFromSource)
where TDelegate : class
{
return serviceCollection.AddSingleton(provider =>
getDelegateFromSource(provider.GetService<TSource>()));
}
}
serviceCollection
.RegisterDelegate<ThingINeedFactory, ThingINeedFactoryMethod>(
factory => factory.Create);
``` | I wrote a little **extension method** that registres the service and the factory (`Func<T>`):
```cs
public static class IServiceCollectionExtension
{
public static IServiceCollection AddFactory<TService, TServiceImplementation>(this IServiceCollection serviceCollection)
where TService : class
where TServiceImplementation : class, TService
{
return serviceCollection
.AddTransient<TService, TServiceImplementation>();
.AddSingleton<Func<TService>>(sp => sp.GetRequiredService<TService>);
}
}
```
**Usage**:
```cs
serviceCollection
.AddFactory<IMyInterface, MyImplementation>()
``` |
35,736,070 | Using `asp.net 5` I'd like my controller to be injected with a `Func<T>`instead of `T`
For example:
```cs
public HomeController(Func<Interfaces.IUnitOfWork> uow)
```
Instead of
```cs
public HomeController(Interfaces.IUnitOfWork uow)
```
Is it possible with the built-in DI or am I forced to move to an external DI? | 2016/03/02 | ['https://Stackoverflow.com/questions/35736070', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/20335/'] | As far as I'm aware deferring dependencies like this isn't possible using the current default IoC container within ASP.NET Core. I've not been able to get it working anyway!
To defer the initialisation of dependencies like this you'll need to implement an existing, more feature rich IoC container. | I wrote a little **extension method** that registres the service and the factory (`Func<T>`):
```cs
public static class IServiceCollectionExtension
{
public static IServiceCollection AddFactory<TService, TServiceImplementation>(this IServiceCollection serviceCollection)
where TService : class
where TServiceImplementation : class, TService
{
return serviceCollection
.AddTransient<TService, TServiceImplementation>();
.AddSingleton<Func<TService>>(sp => sp.GetRequiredService<TService>);
}
}
```
**Usage**:
```cs
serviceCollection
.AddFactory<IMyInterface, MyImplementation>()
``` |
35,736,070 | Using `asp.net 5` I'd like my controller to be injected with a `Func<T>`instead of `T`
For example:
```cs
public HomeController(Func<Interfaces.IUnitOfWork> uow)
```
Instead of
```cs
public HomeController(Interfaces.IUnitOfWork uow)
```
Is it possible with the built-in DI or am I forced to move to an external DI? | 2016/03/02 | ['https://Stackoverflow.com/questions/35736070', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/20335/'] | As far as I'm aware deferring dependencies like this isn't possible using the current default IoC container within ASP.NET Core. I've not been able to get it working anyway!
To defer the initialisation of dependencies like this you'll need to implement an existing, more feature rich IoC container. | I have solution below
```cs
public static IServiceCollection WithFunc<TService>(this IServiceCollection serviceCollection) where TService : class {
var serviceType = typeof(TService);
var serviceDescriptor = serviceCollection.LastOrDefault(x => x.ServiceType == serviceType);
Debug.Assert(serviceDescriptor != null);
serviceCollection.Add(ServiceDescriptor.Describe(typeof(Func<TService>),
scope => new Func<TService>(scope.GetRequiredService<TService>),
serviceDescriptor.Lifetime));
return serviceCollection;
}
```
usage
```cs
[Fact]
void with_func() {
var services = new ServiceCollection()
.AddTransient<IFoo, Foo>().WithFunc<IFoo>()
.BuildServiceProvider();
var fooFunc = services.GetRequiredService<Func<IFoo>>();
Assert.NotNull(fooFunc);
}
```
more detail in gist <https://gist.github.com/leoninew/d2f174fe1422e453c60fb78e69342310> |
35,736,070 | Using `asp.net 5` I'd like my controller to be injected with a `Func<T>`instead of `T`
For example:
```cs
public HomeController(Func<Interfaces.IUnitOfWork> uow)
```
Instead of
```cs
public HomeController(Interfaces.IUnitOfWork uow)
```
Is it possible with the built-in DI or am I forced to move to an external DI? | 2016/03/02 | ['https://Stackoverflow.com/questions/35736070', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/20335/'] | `Func<T>` does not get registered or resolved by default but there is nothing stopping you from registering it yourself.
e.g.
```
services.AddSingleton(provider =>
new Func<IUnitOfWork>(() => provider.GetService<IUnitOfWork>()));
```
Note that you will also need to register IUnitOfWork itself in the usual way. | As far as I'm aware deferring dependencies like this isn't possible using the current default IoC container within ASP.NET Core. I've not been able to get it working anyway!
To defer the initialisation of dependencies like this you'll need to implement an existing, more feature rich IoC container. |
35,736,070 | Using `asp.net 5` I'd like my controller to be injected with a `Func<T>`instead of `T`
For example:
```cs
public HomeController(Func<Interfaces.IUnitOfWork> uow)
```
Instead of
```cs
public HomeController(Interfaces.IUnitOfWork uow)
```
Is it possible with the built-in DI or am I forced to move to an external DI? | 2016/03/02 | ['https://Stackoverflow.com/questions/35736070', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/20335/'] | You can register a `Func<T>` or a delegate with a `ServiceCollection`. I recommend a delegate because it allows you to distinguish between different methods with identical signatures.
Here's an example.
```
public interface IThingINeed {}
public class ThingINeed : IThingINeed { }
public delegate IThingINeed ThingINeedFactory();
public class DelegateRegistrationTests
{
[Test]
public void RegisterDelegateFromDependency()
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddTransient<IThingINeed, ThingINeed>();
serviceCollection.AddTransient<ThingINeedFactory>(
provider => provider.GetService<IThingINeed>);
var serviceProvider = serviceCollection.BuildServiceProvider();
var factoryMethod = serviceProvider.GetService<ThingINeedFactory>();
var output = factoryMethod();
Assert.IsInstanceOf<ThingINeed>(output);
}
}
```
This almost looks like a service locator because the function we're resolving is actually `IServiceCollection.GetService<ThingINeedFactory>()`. But that's hidden in the composition root. A class that injects this delegate depends on the delegate, not on the implementation.
You can use the same approach if the method you want to return belongs to a class that the container must resolve.
```
public interface IThingINeed
{
string SayHello();
}
public class ThingINeed : IThingINeed
{
private readonly string _greeting;
public ThingINeed(string greeting)
{
_greeting = greeting;
}
public string SayHello() => _greeting;
}
public class ThingINeedFactory
{
public IThingINeed Create(string input) => new ThingINeed(input);
}
public delegate IThingINeed ThingINeedFactoryMethod(string input);
public class DelegateRegistrationTests
{
[Test]
public void RegisterDelegateFromDependency()
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton<IThingINeed, ThingINeed>();
serviceCollection.AddSingleton<ThingINeedFactory>();
serviceCollection.AddSingleton<ThingINeedFactoryMethod>(provider =>
provider.GetService<ThingINeedFactory>().Create);
var serviceProvider = serviceCollection.BuildServiceProvider();
var factoryMethod = serviceProvider.GetService<ThingINeedFactoryMethod>();
var created = factoryMethod("abc");
var greeting = created.SayHello();
Assert.AreEqual("abc", greeting);
}
}
```
Here's an extension method to (maybe) make it a little bit easier:
```
public static class ServiceCollectionExtensions
{
public static IServiceCollection RegisterDelegate<TSource, TDelegate>(
this IServiceCollection serviceCollection,
Func<TSource, TDelegate> getDelegateFromSource)
where TDelegate : class
{
return serviceCollection.AddSingleton(provider =>
getDelegateFromSource(provider.GetService<TSource>()));
}
}
serviceCollection
.RegisterDelegate<ThingINeedFactory, ThingINeedFactoryMethod>(
factory => factory.Create);
``` | While there is no built in Func building support in the default dependency injection for .net core we can build an extension method to add in all the missing funcs. We just need to make sure we call it at the end of registration.
```
public static class ServiceCollectionExtensions
{
private static MethodInfo GetServiceMethod;
static ServiceCollectionExtensions()
{
Func<IServiceProvider, object> getServiceMethod = ServiceProviderServiceExtensions.GetService<object>;
GetServiceMethod = getServiceMethod.Method.GetGenericMethodDefinition();
}
/// <summary>
/// Registers all Funcs in constructors to the ServiceCollection - important to call after all registrations
/// </summary>
/// <param name="collection"></param>
/// <returns></returns>
public static IServiceCollection AddFactories(this IServiceCollection collection)
{
// Get a list of all Funcs used in constructors of regigstered types
var funcTypes = new HashSet<Type>(collection.Where(x => x.ImplementationType != null)
.Select(x => x.ImplementationType)
.SelectMany(x => x.GetConstructors(BindingFlags.Public | BindingFlags.Instance))
.SelectMany(x => x.GetParameters())
.Select(x => x.ParameterType)
.Where(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(Func<>)));
// Get a list of already registered Func<> and remove them from the hashset
var registeredFuncs = collection.Select(x => x.ServiceType)
.Where(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(Func<>));
funcTypes.ExceptWith(registeredFuncs);
// Each func build the factory for it
foreach (var funcType in funcTypes)
{
var type = funcType.GetGenericArguments().First();
collection.AddTransient(funcType, FuncBuilder(type));
}
return collection;
}
/// <summary>
/// This build expression tree for a func that is equivalent to
/// Func<IServiceProvider, Func<TType>> factory = serviceProvider => new Func<TType>(serviceProvider.GetService<TType>);
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
private static Func<IServiceProvider, object> FuncBuilder(Type type)
{
var serviceProvider = Expression.Parameter(typeof(IServiceProvider), "serviceProvider");
var method = GetServiceMethod.MakeGenericMethod(type);
var call = Expression.Call(method, serviceProvider);
var returnType = typeof(Func<>).MakeGenericType(type);
var returnFunc = Expression.Lambda(returnType, call);
var func = Expression.Lambda(typeof(Func<,>).MakeGenericType(typeof(IServiceProvider), returnType), returnFunc, serviceProvider);
var factory = func.Compile() as Func<IServiceProvider, object>;
return factory;
}
}
```
In AddFactories we get a list of all the concreate types that are registered then check their constructors for any Func<>. From that list remove any Func that has been registered before. Using some expressiontrees we build the needed Funcs.
The code is also over in [codereview](https://codereview.stackexchange.com/q/210507/52662), minus the check for already registered funcs. |
13,140,659 | I have developed an app using Phonegap for Android and IPhone. Is there how to programm the functionality with the Phonegap Framework to share a URL to twitter and Facebook for Android and IPhone?
Thanks | 2012/10/30 | ['https://Stackoverflow.com/questions/13140659', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1551880/'] | You have a couple of hybrid plugins for Phonegap which cover twitter and facebook among other social services:
* [ShareKit for iOs](https://github.com/mohamedfasil/ShareKitPlugin-for-Phonegap-3.0)
* [Share for Android, iOs & WinPhone](https://github.com/EddyVerbruggen/SocialSharing-PhoneGap-Plugin) | The canonical Facebook plugin for Phonegap is here: <https://github.com/davejohnson/phonegap-plugin-facebook-connect>
It is being updated (by Facebook) to be compatible with the latest iOS and Android SDKs, and so would be recommended... |
13,140,659 | I have developed an app using Phonegap for Android and IPhone. Is there how to programm the functionality with the Phonegap Framework to share a URL to twitter and Facebook for Android and IPhone?
Thanks | 2012/10/30 | ['https://Stackoverflow.com/questions/13140659', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1551880/'] | You have a couple of hybrid plugins for Phonegap which cover twitter and facebook among other social services:
* [ShareKit for iOs](https://github.com/mohamedfasil/ShareKitPlugin-for-Phonegap-3.0)
* [Share for Android, iOs & WinPhone](https://github.com/EddyVerbruggen/SocialSharing-PhoneGap-Plugin) | You can use the following link for twitter on IOS: <https://github.com/phonegap/phonegap-plugins/tree/master/iPhone/Twitter>
For Android: <http://www.mobiledevelopersolutions.com/home/start/twominutetutorials/tmt5p1> |
13,140,659 | I have developed an app using Phonegap for Android and IPhone. Is there how to programm the functionality with the Phonegap Framework to share a URL to twitter and Facebook for Android and IPhone?
Thanks | 2012/10/30 | ['https://Stackoverflow.com/questions/13140659', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1551880/'] | You have a couple of hybrid plugins for Phonegap which cover twitter and facebook among other social services:
* [ShareKit for iOs](https://github.com/mohamedfasil/ShareKitPlugin-for-Phonegap-3.0)
* [Share for Android, iOs & WinPhone](https://github.com/EddyVerbruggen/SocialSharing-PhoneGap-Plugin) | This is really amazing for iOS. Its working with Phonegap Cordova 2.3
<https://github.com/bfcam/phonegap-ios-social-plugin>
For Android I'm using Android Share Plugin
<https://github.com/phonegap/phonegap-plugins/tree/master/Android/Share> |
13,140,659 | I have developed an app using Phonegap for Android and IPhone. Is there how to programm the functionality with the Phonegap Framework to share a URL to twitter and Facebook for Android and IPhone?
Thanks | 2012/10/30 | ['https://Stackoverflow.com/questions/13140659', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1551880/'] | You have a couple of hybrid plugins for Phonegap which cover twitter and facebook among other social services:
* [ShareKit for iOs](https://github.com/mohamedfasil/ShareKitPlugin-for-Phonegap-3.0)
* [Share for Android, iOs & WinPhone](https://github.com/EddyVerbruggen/SocialSharing-PhoneGap-Plugin) | Currently the best cross-platform social share widget is [this one](https://github.com/EddyVerbruggen/SocialSharing-PhoneGap-Plugin) which is also [available on PhoneGap Build!](https://build.phonegap.com/plugins/382)
It not only supports sharing via the native share widget, but you can also share directly to Facebook, Twitter, Pinterest, etc. |
13,140,659 | I have developed an app using Phonegap for Android and IPhone. Is there how to programm the functionality with the Phonegap Framework to share a URL to twitter and Facebook for Android and IPhone?
Thanks | 2012/10/30 | ['https://Stackoverflow.com/questions/13140659', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1551880/'] | This is really amazing for iOS. Its working with Phonegap Cordova 2.3
<https://github.com/bfcam/phonegap-ios-social-plugin>
For Android I'm using Android Share Plugin
<https://github.com/phonegap/phonegap-plugins/tree/master/Android/Share> | The canonical Facebook plugin for Phonegap is here: <https://github.com/davejohnson/phonegap-plugin-facebook-connect>
It is being updated (by Facebook) to be compatible with the latest iOS and Android SDKs, and so would be recommended... |
13,140,659 | I have developed an app using Phonegap for Android and IPhone. Is there how to programm the functionality with the Phonegap Framework to share a URL to twitter and Facebook for Android and IPhone?
Thanks | 2012/10/30 | ['https://Stackoverflow.com/questions/13140659', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1551880/'] | This is really amazing for iOS. Its working with Phonegap Cordova 2.3
<https://github.com/bfcam/phonegap-ios-social-plugin>
For Android I'm using Android Share Plugin
<https://github.com/phonegap/phonegap-plugins/tree/master/Android/Share> | You can use the following link for twitter on IOS: <https://github.com/phonegap/phonegap-plugins/tree/master/iPhone/Twitter>
For Android: <http://www.mobiledevelopersolutions.com/home/start/twominutetutorials/tmt5p1> |