qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
191,981 | Can a civilization be highly evolved as far as culture, ethics, societal norms, laws, language, literature and arts, but not ever come to develop any sort of advanced technology besides main practical techniques for construction and agriculture?
They have a culture-religion that is fully integrated with nature, and they are naturally frugal as they are isolated from the other cultures in their world, and live in a continent that is able to provide all they need to prosper.
EDIT:
Thanks all for all your amazing inputs. I sort of figured out by myself how to solve this issue I had with this civilization. I will explain it in the end.
First, the clarifications:
1. They are not human. They are an intelligent species that evolved from warm-blooded reptiles.
2. They have math (a senary numeric system), literacy (their language is based on clicks like Khoisan), highly developed agriculture, steam, the wheel, levers, pumps, cranes, concrete, highly developed civil engineering and architecture, highly developed metalworks, mining, etc. What I meant by advanced technology was basically war machines, electricity, airplanes, ships, computers, post first industrial revolution technologies.
3. Their philosophical and ethical level is comparable to Ancient Athens/Ancient China but a little more advanced. So, they are basically very enlightened empiricists by nature observation BUT don't have a full empirical scientific method fully developed (and they can't have a western-like scientific method developed, or they will turn to imperialism, conquest and war. That was the main concern behind my question).
4. They have another reptilian species of "companions" (they are "slaves" in the economic sense - work for food and shelter -, but are not slaves in the sense we Americans think of slaves, like some people with another skin color that we can rape, abuse, force to work to death, and beat at will, whenever our White European selves feel frustrated and/or down). That reptilian species has an intelligence comparable to a combination of crows, chimpanzees and dogs. So, they are not able to develop abstract thinking, but are able to learn and execute any sort of tasks the main species need then to do. They also have sets of opposable fingers and toes like the main species.
5. The main species is integrated with nature through their culture/religion as they were essentially hunters gatherers before "the great cataclysm' (something like 70 million years BP). A little before that they had what they call "The 500,000 year march", when they left their original dying (due to basically extinction of resources caused by their own predatory actions) homeland and moved West and then South to this new continent where they been living for 70 million years, totally isolated from the rest of the world. During that "march", their culture of elders/scientists/priests ruling evolved, and they created their literary tradition of passing to the youngsters the knowledge of their whole history, and their nature worshipping religion. One of the main legends is that nature is a live and sentient organism that helps their species by providing and nourishing them.
6. This is another point. They have a culture (like us humans), so instructions needed for survival are not necessarily coded in their DNA like the other animals. They still have some basic survival needs and skills encoded in their DNA (as we still have too, like, for example, fear of spiders, which is not cultural, as all cultures in the world fear spiders), but most of the skills and needs are passed from the elders to the youngsters as culture.
So, I basically figured out how to make them highly culturally advanced while keeping them without developing advanced technology and war machines what would have their culture necessarily changing to expansionism, imperialism, conquest and warmongering.
I basically used two features from their lore, one geographic (their continent is rich in resources, as well as very isolated) and another cultural (their nature-worship religion).
As result, like in Chinese Confucianism, to want to leave their parents/clan homeland is really frowned upon. Whoever leaves their original homeland becomes an outcast and a pariah.
As they have all the resources they need, there is no need to trade for resources with other cultures. And as they worship nature, their local rivers, forests, mines, mountains, so forth, are very important to them, so they cannot be faraway from it, and must respect that nature, so not bring destruction or building anything that does not look able to fit into the natural environment.
As Ming China, they can have a very advanced civilization, but without any need to contact the exterior world. And, unlike Ming China, they don't need to keep a strong military to protect their borders, because they are separated from the other cultures in their world by thousands of miles of open ocean.
Thanks again for all your ideas. And if you have any other ideas that you think would provide any improvement to this way I found to solve this issue I had, I will be really happy to hear them. | 2020/12/14 | [
"https://worldbuilding.stackexchange.com/questions/191981",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/81238/"
] | Maybe in the sea
----------------
I think it is possible, with aquatic species. Ocean is different from land in all the ways that makes rise of sapience possible (hello dolphins), but limits severely what kind of technology they can use. There's no fire, no metals, so your species population density might reach those critical stages where it kickstarts the necessity for regulations, etiquette and so on, in terms of the technology they would be restricted to hunter gatherers or early agriculture at best, since the easy paths that were available for us to start doing stuff like metal smelting would be closed off for them.
Do keep in mind though that we really have little idea about how intricate were social and cultural interactions in our prehistoric ancestors. Nothing except physical artifacts remained, and writing was invented only seven thousand years later. I do not think that before "civilization" they were dumb brutes as they often depicted in media. | Yes, technology and advanced civilisation are not related. The most advanced civilisations may have no recognisable technology and be completely integrated with nature, working with it instead of against it, without war, crime, poverty or hatred.
Other cultures will sneer at them as mere hippies, or decry the entire concept as a reversion to the 'noble savage stereotype' ...while secretly envying their relaxed lifestyle. |
191,981 | Can a civilization be highly evolved as far as culture, ethics, societal norms, laws, language, literature and arts, but not ever come to develop any sort of advanced technology besides main practical techniques for construction and agriculture?
They have a culture-religion that is fully integrated with nature, and they are naturally frugal as they are isolated from the other cultures in their world, and live in a continent that is able to provide all they need to prosper.
EDIT:
Thanks all for all your amazing inputs. I sort of figured out by myself how to solve this issue I had with this civilization. I will explain it in the end.
First, the clarifications:
1. They are not human. They are an intelligent species that evolved from warm-blooded reptiles.
2. They have math (a senary numeric system), literacy (their language is based on clicks like Khoisan), highly developed agriculture, steam, the wheel, levers, pumps, cranes, concrete, highly developed civil engineering and architecture, highly developed metalworks, mining, etc. What I meant by advanced technology was basically war machines, electricity, airplanes, ships, computers, post first industrial revolution technologies.
3. Their philosophical and ethical level is comparable to Ancient Athens/Ancient China but a little more advanced. So, they are basically very enlightened empiricists by nature observation BUT don't have a full empirical scientific method fully developed (and they can't have a western-like scientific method developed, or they will turn to imperialism, conquest and war. That was the main concern behind my question).
4. They have another reptilian species of "companions" (they are "slaves" in the economic sense - work for food and shelter -, but are not slaves in the sense we Americans think of slaves, like some people with another skin color that we can rape, abuse, force to work to death, and beat at will, whenever our White European selves feel frustrated and/or down). That reptilian species has an intelligence comparable to a combination of crows, chimpanzees and dogs. So, they are not able to develop abstract thinking, but are able to learn and execute any sort of tasks the main species need then to do. They also have sets of opposable fingers and toes like the main species.
5. The main species is integrated with nature through their culture/religion as they were essentially hunters gatherers before "the great cataclysm' (something like 70 million years BP). A little before that they had what they call "The 500,000 year march", when they left their original dying (due to basically extinction of resources caused by their own predatory actions) homeland and moved West and then South to this new continent where they been living for 70 million years, totally isolated from the rest of the world. During that "march", their culture of elders/scientists/priests ruling evolved, and they created their literary tradition of passing to the youngsters the knowledge of their whole history, and their nature worshipping religion. One of the main legends is that nature is a live and sentient organism that helps their species by providing and nourishing them.
6. This is another point. They have a culture (like us humans), so instructions needed for survival are not necessarily coded in their DNA like the other animals. They still have some basic survival needs and skills encoded in their DNA (as we still have too, like, for example, fear of spiders, which is not cultural, as all cultures in the world fear spiders), but most of the skills and needs are passed from the elders to the youngsters as culture.
So, I basically figured out how to make them highly culturally advanced while keeping them without developing advanced technology and war machines what would have their culture necessarily changing to expansionism, imperialism, conquest and warmongering.
I basically used two features from their lore, one geographic (their continent is rich in resources, as well as very isolated) and another cultural (their nature-worship religion).
As result, like in Chinese Confucianism, to want to leave their parents/clan homeland is really frowned upon. Whoever leaves their original homeland becomes an outcast and a pariah.
As they have all the resources they need, there is no need to trade for resources with other cultures. And as they worship nature, their local rivers, forests, mines, mountains, so forth, are very important to them, so they cannot be faraway from it, and must respect that nature, so not bring destruction or building anything that does not look able to fit into the natural environment.
As Ming China, they can have a very advanced civilization, but without any need to contact the exterior world. And, unlike Ming China, they don't need to keep a strong military to protect their borders, because they are separated from the other cultures in their world by thousands of miles of open ocean.
Thanks again for all your ideas. And if you have any other ideas that you think would provide any improvement to this way I found to solve this issue I had, I will be really happy to hear them. | 2020/12/14 | [
"https://worldbuilding.stackexchange.com/questions/191981",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/81238/"
] | **Maybe, if they can overcome population density issues.**
The key way to develop all of those civilization issues is to have a very high density of people working together on shared ideas, without them needing to mine the landscape and so gaining greater technology as they get better at mining.
As such, you need natural skyscrapers.
One way to do this is with [Inosculation](https://en.wikipedia.org/wiki/Inosculation) where you can grow trees together. This civilization could have very advanced tree growing techniques where they can grow trees together to form houses and homes and platforms for their homes. The trees could naturally provide a large bounty for them. As such, they could have huge cities of tens or hundreds of thousands on shared trees, without having any technology that is useful on a scale of less than years.
**The main problem is working out how they handle conflict and danger.**
They can be peace loving sure, but what happens when a hostile pest destroys their food stocks, or a natural disaster wrecks their home, or a plague kills their people? When times are tough, people often resort to war to get new resources, no matter how peace loving. For this I would suggest [flower war.](https://en.wikipedia.org/wiki/Flower_war)
Rather than having costly and large engagements, small fights between mostly nobles and some commoners would be the norm. You meet on a set date, fight with proven weapons, and whoever is more skilled in melee combat wins. You can trade resources based off this. This would prevent the need for large scale costly wars which would advance technology. | ### Maybe, in a magically-powered fantasy universe with inconsistent physics.
In fantasy world where the laws of physics behave in an inconsistent fashion but there is sufficient amounts of magic to allow life to function despite that, it might be possible that a society doesn't develop much if any technology if it relies primarily on magic instead. For instance, if smelting iron ore into a consistently usable form isn't possible without magic, then they probably won't use non-magical iron tools. If gears randomly jam up and break, then you won't have clockwork or watermills. If refining flammable oil is as likely to result in an explosive as lantern fuel, then you won't see any oil lanterns. |
52,199,086 | I am working with sas to manipulate some dataset.
I am using the data step to apply some condition to keep columns and filter on some values.
The problem is that I would like to filter on columns that in the end I will not need, so I would like to apply, first, the where clause, and then the keep clause.
The problem is that sas executes, first the keep clause and then where, so when it is trying to apply the where instruction it doesn't find the columns on which it should be applied on. This is my code:
```
data newtable;
set mytable(where=(var1<value)
keep var2);
end;
```
In this case the error is the var1 cannot be found since I decided to keep only var2. I know I can do two data steps, but I would like to do everything in one step only.
How can I achieve this? | 2018/09/06 | [
"https://Stackoverflow.com/questions/52199086",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4332914/"
] | This can be achieved by using the `keep` data set option on the output data set, e.g.(untested):
```
data newtable(keep=var2);
set mytable(where=(var1<value));
end;
```
Alternatively a `keep` statement can be used, e.g. (untested):
```
data newtable;
set mytable(where=(var1<value));
keep var2;
end;
``` | @Amir has the right of it. @Quentin is worried about the efficiency of it all. Unless your where clause is highly involved, then this will be your most efficient method.
```
data newtable;
set mytable(where=(var1<value) keep=var1 var2);
keep var2;
end;
```
Yes, `var1` is read into the PDV, but you have limited the PDV to only the variables wanted in the output and needed in the where clause.
If you just want to run a where and do no other data step logic, then PROC SQL is just as efficient as the method above.
```
proc sql noprint;
create table newtable as
select var2
from mytable
where var1<value;
quit;
``` |
31,696,681 | In mathematics we can assume that `sin(t1)` is equal to `t1` for very small angles. How to do that in Matlab?
```
syms t1;
res = sin(t1);
res2= MAGIC(res,t1);
```
I need `MAGIC`to change `res`, such that it becomes `t1`.
Thanks | 2015/07/29 | [
"https://Stackoverflow.com/questions/31696681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5168730/"
] | It is `Input` and not `input`.
[This commit](https://github.com/laravel/laravel/commit/2adbbbd91e9d6e2d569cc56f138b7273efe25651) removed `Input` facade definition from `config/app.php` hence you have to manually add that in to `aliases` array as below,
```
'Input' => Illuminate\Support\Facades\Input::class,
```
Or You can import `Input` facade directly as required,
```
use Illuminate\Support\Facades\Input;
``` | It's changed in laravel 6. [See for more info here](https://laravel.com/docs/6.x/upgrade#the-input-facade)
Don't do anything in app.php and anywhere else, just replace
input::get() with Request::input()
and
on top where you declare Input,Validator,Hash etc., remove **Input** and add **Request**
use something like :
Config,DB,File,Hash,**Input**,Redirect,Session,View,Validator,**Request**; |
31,696,681 | In mathematics we can assume that `sin(t1)` is equal to `t1` for very small angles. How to do that in Matlab?
```
syms t1;
res = sin(t1);
res2= MAGIC(res,t1);
```
I need `MAGIC`to change `res`, such that it becomes `t1`.
Thanks | 2015/07/29 | [
"https://Stackoverflow.com/questions/31696681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5168730/"
] | In first your problem is about the spelling of the input class, should be Input instead of input. And you have to import the class with the good namespace.
```
use Illuminate\Support\Facades\Input;
```
If you want it called 'input' not 'Input', add this :
```
use Illuminate\Support\Facades\Input as input;
```
Second, It's a dirty way to store into the database via route.php,
and you're not processing data validation.
If a sent parameter isn't what you expected, maybe an SQL error will appear, its caused by the data type.
You should use controller to interact with information and store via the model in the controller method.
The route.php file handles routing.
It is designed to make the link between the controller and the asked route.
To learn about controller, middleware, model, service ...
<http://laravel.com/docs/5.1/>
If you need some more information, solution about problem you can join the community : <https://laracasts.com/>
Regards. | Declaration in config/app.php under aliases:-
```
'Input' => Illuminate\Support\Facades\Input::class,
```
Or You can import Input facade directly as required,
```
use Illuminate\Support\Facades\Input;
```
or
```
use Illuminate\Support\Facades\Input as input;
``` |
31,696,681 | In mathematics we can assume that `sin(t1)` is equal to `t1` for very small angles. How to do that in Matlab?
```
syms t1;
res = sin(t1);
res2= MAGIC(res,t1);
```
I need `MAGIC`to change `res`, such that it becomes `t1`.
Thanks | 2015/07/29 | [
"https://Stackoverflow.com/questions/31696681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5168730/"
] | In first your problem is about the spelling of the input class, should be Input instead of input. And you have to import the class with the good namespace.
```
use Illuminate\Support\Facades\Input;
```
If you want it called 'input' not 'Input', add this :
```
use Illuminate\Support\Facades\Input as input;
```
Second, It's a dirty way to store into the database via route.php,
and you're not processing data validation.
If a sent parameter isn't what you expected, maybe an SQL error will appear, its caused by the data type.
You should use controller to interact with information and store via the model in the controller method.
The route.php file handles routing.
It is designed to make the link between the controller and the asked route.
To learn about controller, middleware, model, service ...
<http://laravel.com/docs/5.1/>
If you need some more information, solution about problem you can join the community : <https://laracasts.com/>
Regards. | ```
#config/app.php
'aliases' => [
...
'Input' => Illuminate\Support\Facades\Input::class,
...
],
#Use Controller file
use Illuminate\Support\Facades\Input;
==OR==
use Input;
```
Read full example: <https://devnote.in/laravel-class-input-not-found> |
31,696,681 | In mathematics we can assume that `sin(t1)` is equal to `t1` for very small angles. How to do that in Matlab?
```
syms t1;
res = sin(t1);
res2= MAGIC(res,t1);
```
I need `MAGIC`to change `res`, such that it becomes `t1`.
Thanks | 2015/07/29 | [
"https://Stackoverflow.com/questions/31696681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5168730/"
] | **In larvel => 6 Version:**
Input no longer exists In larvel 6,7,8 Version. Use `Request` instead of `Input`.
**Based on the Laravel [docs](https://laravel.com/docs/6.x/upgrade#the-input-facade), since version 6.x Input has been removed.**
**The Input Facade**
*Likelihood Of Impact: Medium*
>
> The `Input` facade, which was primarily a duplicate of the `Request`
> facade, has been removed. If you are using the `Input::get` method, you
> should now call the `Request::input` method. All other calls to the
> Input facade may simply be updated to use the `Request` facade.
>
>
>
```
use Illuminate\Support\Facades\Request;
..
..
..
public function functionName(Request $request)
{
$searchInput = $request->q;
}
``` | `'Input' => Illuminate\Support\Facades\Input::class`, add it to App.php. |
31,696,681 | In mathematics we can assume that `sin(t1)` is equal to `t1` for very small angles. How to do that in Matlab?
```
syms t1;
res = sin(t1);
res2= MAGIC(res,t1);
```
I need `MAGIC`to change `res`, such that it becomes `t1`.
Thanks | 2015/07/29 | [
"https://Stackoverflow.com/questions/31696681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5168730/"
] | You can add a facade in your `folder\config\app.php`
```
'Input' => Illuminate\Support\Facades\Input::class,
``` | ```
#config/app.php
'aliases' => [
...
'Input' => Illuminate\Support\Facades\Input::class,
...
],
#Use Controller file
use Illuminate\Support\Facades\Input;
==OR==
use Input;
```
Read full example: <https://devnote.in/laravel-class-input-not-found> |
31,696,681 | In mathematics we can assume that `sin(t1)` is equal to `t1` for very small angles. How to do that in Matlab?
```
syms t1;
res = sin(t1);
res2= MAGIC(res,t1);
```
I need `MAGIC`to change `res`, such that it becomes `t1`.
Thanks | 2015/07/29 | [
"https://Stackoverflow.com/questions/31696681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5168730/"
] | Declaration in config/app.php under aliases:-
```
'Input' => Illuminate\Support\Facades\Input::class,
```
Or You can import Input facade directly as required,
```
use Illuminate\Support\Facades\Input;
```
or
```
use Illuminate\Support\Facades\Input as input;
``` | Add this in config/app.php under aliases:-
```
'Input' => Illuminate\Support\Facades\Input::class,
``` |
31,696,681 | In mathematics we can assume that `sin(t1)` is equal to `t1` for very small angles. How to do that in Matlab?
```
syms t1;
res = sin(t1);
res2= MAGIC(res,t1);
```
I need `MAGIC`to change `res`, such that it becomes `t1`.
Thanks | 2015/07/29 | [
"https://Stackoverflow.com/questions/31696681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5168730/"
] | For laravel `<` **5.2**:
Open `config/app.php` and add the `Input` class to `aliases`:
```
'aliases' => [
// ...
'Input' => Illuminate\Support\Facades\Input::class,
// ...
],
```
---
For laravel `>=` **5.2**
Change `Input::` to `Request::` | Miscall of Class it should be `Input` not `input` |
31,696,681 | In mathematics we can assume that `sin(t1)` is equal to `t1` for very small angles. How to do that in Matlab?
```
syms t1;
res = sin(t1);
res2= MAGIC(res,t1);
```
I need `MAGIC`to change `res`, such that it becomes `t1`.
Thanks | 2015/07/29 | [
"https://Stackoverflow.com/questions/31696681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5168730/"
] | if You use Laravel version 5.2 Review this: <https://laravel.com/docs/5.2/requests#accessing-the-request>
```
use Illuminate\Http\Request;//Access able for All requests
...
class myController extends Controller{
public function myfunction(Request $request){
$name = $request->input('username');
}
}
``` | `'Input' => Illuminate\Support\Facades\Input::class`, add it to App.php. |
31,696,681 | In mathematics we can assume that `sin(t1)` is equal to `t1` for very small angles. How to do that in Matlab?
```
syms t1;
res = sin(t1);
res2= MAGIC(res,t1);
```
I need `MAGIC`to change `res`, such that it becomes `t1`.
Thanks | 2015/07/29 | [
"https://Stackoverflow.com/questions/31696681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5168730/"
] | **In larvel => 6 Version:**
Input no longer exists In larvel 6,7,8 Version. Use `Request` instead of `Input`.
**Based on the Laravel [docs](https://laravel.com/docs/6.x/upgrade#the-input-facade), since version 6.x Input has been removed.**
**The Input Facade**
*Likelihood Of Impact: Medium*
>
> The `Input` facade, which was primarily a duplicate of the `Request`
> facade, has been removed. If you are using the `Input::get` method, you
> should now call the `Request::input` method. All other calls to the
> Input facade may simply be updated to use the `Request` facade.
>
>
>
```
use Illuminate\Support\Facades\Request;
..
..
..
public function functionName(Request $request)
{
$searchInput = $request->q;
}
``` | Miscall of Class it should be `Input` not `input` |
31,696,681 | In mathematics we can assume that `sin(t1)` is equal to `t1` for very small angles. How to do that in Matlab?
```
syms t1;
res = sin(t1);
res2= MAGIC(res,t1);
```
I need `MAGIC`to change `res`, such that it becomes `t1`.
Thanks | 2015/07/29 | [
"https://Stackoverflow.com/questions/31696681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5168730/"
] | In Laravel 5.2 Input:: is replaced with Request::
use
```
Request::
```
Add to the top of Controller or any other Class
```
use Illuminate\Http\Request;
``` | `'Input' => Illuminate\Support\Facades\Input::class`, add it to App.php. |
58,370,647 | I am using Windows 10 and Windows subsystem for linux.
I have started creating my own Operating System in Assembly and C.
I am following a tutorial.
I got stuck into 2 problems.
Error 1:
When I Link and create bin files, i am getting a warning:
"ld: warning: cannot find entry symbol \_start; defaulting to 0000000000001000"
Does this matter?
Error 2:
After compiling my code, there was no error. But when i boot my operating system, it shows an error: Disk read error!
Please help me.
Boot.asm
```
[org 0x7c00]
KERNEL_OFFSET equ 0x1000
mov [BOOT_DRIVE], dl
mov bp, 0x9000
mov sp, bp
mov si, MSG_REAL_MODE
call print
call load_kernel
call switch_to_pm
jmp $
%include "printstr.asm"
%include "diskload.asm"
[bits 16]
load_kernel :
mov si, MSG_LOAD_KERNEL
call print
mov bx, KERNEL_OFFSET
mov dh, 15
mov dl, [ BOOT_DRIVE ]
call disk_load
ret
[bits 32]
BEGIN_PM :
mov ebx, MSG_PROT_MODE
call print_string_pm
call KERNEL_OFFSET
jmp $
BOOT_DRIVE db 0
MSG_REAL_MODE db " Started in 16 - bit Real Mode " , 0
MSG_PROT_MODE db " Successfully landed in 32 - bit Protected Mode " , 0
MSG_LOAD_KERNEL db " Loading kernel into memory. " , 0
times 510 -( $ - $$ ) db 0
dw 0xaa55
```
diskload.asm
```
disk_load :
push dx
mov ah , 0x02
mov al , dh ;
mov ch , 0x00
mov dh , 0x00
mov cl , 0x02
int 0x13
jc disk_error
pop dx
cmp dh , al
jne disk_error
ret
disk_error :
mov si , DISK_ERROR_MSG
call prints
jmp $
; Variables
DISK_ERROR_MSG db " Disk read error !" , 0
prints:
lodsb
or al, al
jz printdones
mov ah, 0eh
int 10h
jmp prints
printdones:
ret
```
Compiling commands:
```
nasm boot.asm -f bin -o boot.bin
nasm kernel_entry.asm -f elf64 -o kernel_entry.o
gcc -ffreestanding -c kernel.c -o kernel.o
ld -o kernel.bin -Ttext 0x1000 kernel_entry.o kernel.o --oformat binary
cat boot.bin kernel.bin > os.iso
``` | 2019/10/14 | [
"https://Stackoverflow.com/questions/58370647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | try the following code:
```
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField.text?.count ?? 0 <= 7{
if textField.text?.count ?? 0 == 7{
DispatchQueue.main.async {
textField.resignFirstResponder()
}
}
return true
}
textField.resignFirstResponder()
return false
}
```
set your customTextField's delegate to self in your viewController's `viewDidLoad` method, and confirm to `UITextFieldDelegate` protocol | What happen if you try this code?
```
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
{
if range.location < 8 {
return true
}
// return NO to not change text
return false
}
``` |
58,370,647 | I am using Windows 10 and Windows subsystem for linux.
I have started creating my own Operating System in Assembly and C.
I am following a tutorial.
I got stuck into 2 problems.
Error 1:
When I Link and create bin files, i am getting a warning:
"ld: warning: cannot find entry symbol \_start; defaulting to 0000000000001000"
Does this matter?
Error 2:
After compiling my code, there was no error. But when i boot my operating system, it shows an error: Disk read error!
Please help me.
Boot.asm
```
[org 0x7c00]
KERNEL_OFFSET equ 0x1000
mov [BOOT_DRIVE], dl
mov bp, 0x9000
mov sp, bp
mov si, MSG_REAL_MODE
call print
call load_kernel
call switch_to_pm
jmp $
%include "printstr.asm"
%include "diskload.asm"
[bits 16]
load_kernel :
mov si, MSG_LOAD_KERNEL
call print
mov bx, KERNEL_OFFSET
mov dh, 15
mov dl, [ BOOT_DRIVE ]
call disk_load
ret
[bits 32]
BEGIN_PM :
mov ebx, MSG_PROT_MODE
call print_string_pm
call KERNEL_OFFSET
jmp $
BOOT_DRIVE db 0
MSG_REAL_MODE db " Started in 16 - bit Real Mode " , 0
MSG_PROT_MODE db " Successfully landed in 32 - bit Protected Mode " , 0
MSG_LOAD_KERNEL db " Loading kernel into memory. " , 0
times 510 -( $ - $$ ) db 0
dw 0xaa55
```
diskload.asm
```
disk_load :
push dx
mov ah , 0x02
mov al , dh ;
mov ch , 0x00
mov dh , 0x00
mov cl , 0x02
int 0x13
jc disk_error
pop dx
cmp dh , al
jne disk_error
ret
disk_error :
mov si , DISK_ERROR_MSG
call prints
jmp $
; Variables
DISK_ERROR_MSG db " Disk read error !" , 0
prints:
lodsb
or al, al
jz printdones
mov ah, 0eh
int 10h
jmp prints
printdones:
ret
```
Compiling commands:
```
nasm boot.asm -f bin -o boot.bin
nasm kernel_entry.asm -f elf64 -o kernel_entry.o
gcc -ffreestanding -c kernel.c -o kernel.o
ld -o kernel.bin -Ttext 0x1000 kernel_entry.o kernel.o --oformat binary
cat boot.bin kernel.bin > os.iso
``` | 2019/10/14 | [
"https://Stackoverflow.com/questions/58370647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I solved the problem by changing the kern after the last character. So now, instead of jumping 40pt, cursor jumps only 1pt (or whatever you set on below method)
```
@objc private func textFieldDidChange() {
guard let text = textField.text else { return }
if text.count == Constant.deviceCodeCharacterCount {
let attributedString = NSMutableAttributedString(string: text)
attributedString.addAttribute(.kern, value: Constant.deviceCodeCharacterSpacing, range: NSRange(location: 0, length: text.count - 1))
attributedString.addAttribute(.kern, value: 1, range: NSRange(location: Constant.deviceCodeCharacterCount - 1, length: 1))
textField.attributedText = attributedString
}
}
```
[](https://i.stack.imgur.com/0mSae.gif) | What happen if you try this code?
```
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
{
if range.location < 8 {
return true
}
// return NO to not change text
return false
}
``` |
58,370,647 | I am using Windows 10 and Windows subsystem for linux.
I have started creating my own Operating System in Assembly and C.
I am following a tutorial.
I got stuck into 2 problems.
Error 1:
When I Link and create bin files, i am getting a warning:
"ld: warning: cannot find entry symbol \_start; defaulting to 0000000000001000"
Does this matter?
Error 2:
After compiling my code, there was no error. But when i boot my operating system, it shows an error: Disk read error!
Please help me.
Boot.asm
```
[org 0x7c00]
KERNEL_OFFSET equ 0x1000
mov [BOOT_DRIVE], dl
mov bp, 0x9000
mov sp, bp
mov si, MSG_REAL_MODE
call print
call load_kernel
call switch_to_pm
jmp $
%include "printstr.asm"
%include "diskload.asm"
[bits 16]
load_kernel :
mov si, MSG_LOAD_KERNEL
call print
mov bx, KERNEL_OFFSET
mov dh, 15
mov dl, [ BOOT_DRIVE ]
call disk_load
ret
[bits 32]
BEGIN_PM :
mov ebx, MSG_PROT_MODE
call print_string_pm
call KERNEL_OFFSET
jmp $
BOOT_DRIVE db 0
MSG_REAL_MODE db " Started in 16 - bit Real Mode " , 0
MSG_PROT_MODE db " Successfully landed in 32 - bit Protected Mode " , 0
MSG_LOAD_KERNEL db " Loading kernel into memory. " , 0
times 510 -( $ - $$ ) db 0
dw 0xaa55
```
diskload.asm
```
disk_load :
push dx
mov ah , 0x02
mov al , dh ;
mov ch , 0x00
mov dh , 0x00
mov cl , 0x02
int 0x13
jc disk_error
pop dx
cmp dh , al
jne disk_error
ret
disk_error :
mov si , DISK_ERROR_MSG
call prints
jmp $
; Variables
DISK_ERROR_MSG db " Disk read error !" , 0
prints:
lodsb
or al, al
jz printdones
mov ah, 0eh
int 10h
jmp prints
printdones:
ret
```
Compiling commands:
```
nasm boot.asm -f bin -o boot.bin
nasm kernel_entry.asm -f elf64 -o kernel_entry.o
gcc -ffreestanding -c kernel.c -o kernel.o
ld -o kernel.bin -Ttext 0x1000 kernel_entry.o kernel.o --oformat binary
cat boot.bin kernel.bin > os.iso
``` | 2019/10/14 | [
"https://Stackoverflow.com/questions/58370647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I solved the problem by changing the kern after the last character. So now, instead of jumping 40pt, cursor jumps only 1pt (or whatever you set on below method)
```
@objc private func textFieldDidChange() {
guard let text = textField.text else { return }
if text.count == Constant.deviceCodeCharacterCount {
let attributedString = NSMutableAttributedString(string: text)
attributedString.addAttribute(.kern, value: Constant.deviceCodeCharacterSpacing, range: NSRange(location: 0, length: text.count - 1))
attributedString.addAttribute(.kern, value: 1, range: NSRange(location: Constant.deviceCodeCharacterCount - 1, length: 1))
textField.attributedText = attributedString
}
}
```
[](https://i.stack.imgur.com/0mSae.gif) | try the following code:
```
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField.text?.count ?? 0 <= 7{
if textField.text?.count ?? 0 == 7{
DispatchQueue.main.async {
textField.resignFirstResponder()
}
}
return true
}
textField.resignFirstResponder()
return false
}
```
set your customTextField's delegate to self in your viewController's `viewDidLoad` method, and confirm to `UITextFieldDelegate` protocol |
4,605,722 | What does the notation $[G : H]$ mean in group theory? Does it mean the same as quotient group? I have seen the above notation a lot while studying group theory but it still remains unclear to me about the meaning of this notation? | 2022/12/26 | [
"https://math.stackexchange.com/questions/4605722",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/1129649/"
] | The index $[G:H]$ is the number of left cosets of $H$ in $G$ and it is the number of right cosets of $H$ in $G$. That those numbers are equal is obvious when $G$ is abelian, but it is true for all groups and this does *not* require $G$ to be finite, so the equality is not fully explained by relying on Lagrange’s theorem for finite groups.
For each left $H$-coset $gH = \{gh : h \in H\}$, inverting its elements gives us
$$\{h^{-1}g^{-1} : h \in H\} = \{hg^{-1} : h \in H\} = Hg^{-1},
$$
which is a right $H$-coset, and sending each $gH$ to $Hg^{-1}$ is a well-defined bijection from the left $H$-cosets to the right $H$-cosets, even if the number of cosets is infinite.
For example, $[\mathbf Z: m\mathbf Z] = m$ for positive integers $m$, $[\mathbf R^\times:\{\pm 1\}]$ is infinite, the positive reals $\mathbf R\_{>0}$ have index $2$ in $\mathbf R^\times$, and the group of real $2\times 2$ matrices with positive determinant ${\rm GL}\_2^+(\mathbf R)$ has index $2$ in the group of real invertible $2\times 2$ matrices ${\rm GL}\_2(\mathbf R)$. That a subgroup of index $2$ is a normal subgroup holds for infinite groups, not just finite groups.
The index, when infinite, should properly be considered as a cardinal number, but typically in a first group theory course you may do very little with subgroup indices when they are infinite, so you might just lump all cases of infinite index together as “$[G:H]=\infty$” in the same way infinite sets $S$ are all lumped together as “$\# S = \infty$” unless there is a good reason to use the more careful notion of cardinal numbers. | We understand mathematics through examples, we appropriate notions through examples that we construct.
Let's take an example that is simple enough to be understood by everyone.
Let $G:=(\mathbb Z/6\mathbb Z,+)=(\{\bar0,\bar1,\bar2,\bar3,\bar4,\bar5,\},+)$ and $H:=\{\bar0,\bar3\}$.
$G/H=\{H,\bar1+H,\bar2+H\}=\{\{\bar0,\bar3\},\{\bar1,\bar4\},\{\bar2,\bar5\}\}$.
Each coset has two elements, the same number of elements as $H$. We also know that $G/H$ is a partition of $G$. So the number of elements of $G$ is equal to the number of cosets, which we denote by $$[G:H]$$(here, $[G:H]=3$).
This notion is interesting and deserves to be introduced: for example, we deduce from the above reasoning easily extendable to the general case that$$|G|=|H|\times[G:H]$$
In particular, for any subgroup of a given group, the order of the subgroup divides that of the group.
Here, 2|6. |
4,605,722 | What does the notation $[G : H]$ mean in group theory? Does it mean the same as quotient group? I have seen the above notation a lot while studying group theory but it still remains unclear to me about the meaning of this notation? | 2022/12/26 | [
"https://math.stackexchange.com/questions/4605722",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/1129649/"
] | The index $[G:H]$ is the number of left cosets of $H$ in $G$ and it is the number of right cosets of $H$ in $G$. That those numbers are equal is obvious when $G$ is abelian, but it is true for all groups and this does *not* require $G$ to be finite, so the equality is not fully explained by relying on Lagrange’s theorem for finite groups.
For each left $H$-coset $gH = \{gh : h \in H\}$, inverting its elements gives us
$$\{h^{-1}g^{-1} : h \in H\} = \{hg^{-1} : h \in H\} = Hg^{-1},
$$
which is a right $H$-coset, and sending each $gH$ to $Hg^{-1}$ is a well-defined bijection from the left $H$-cosets to the right $H$-cosets, even if the number of cosets is infinite.
For example, $[\mathbf Z: m\mathbf Z] = m$ for positive integers $m$, $[\mathbf R^\times:\{\pm 1\}]$ is infinite, the positive reals $\mathbf R\_{>0}$ have index $2$ in $\mathbf R^\times$, and the group of real $2\times 2$ matrices with positive determinant ${\rm GL}\_2^+(\mathbf R)$ has index $2$ in the group of real invertible $2\times 2$ matrices ${\rm GL}\_2(\mathbf R)$. That a subgroup of index $2$ is a normal subgroup holds for infinite groups, not just finite groups.
The index, when infinite, should properly be considered as a cardinal number, but typically in a first group theory course you may do very little with subgroup indices when they are infinite, so you might just lump all cases of infinite index together as “$[G:H]=\infty$” in the same way infinite sets $S$ are all lumped together as “$\# S = \infty$” unless there is a good reason to use the more careful notion of cardinal numbers. | The notation is about a subgroup $H$ of $G$. It is the number of cosets of $H$ in $G$, called the *index of $H$ in $G$*. For example, in $G=\Bbb Z\_6$, we have a subgroup $H=\{ [0]\_6, [2]\_6, [4]\_6\}$; then $H$ and $[1]\_6+H$ are the only cosets (exercise), so $[G:H]=2$. |
4,605,722 | What does the notation $[G : H]$ mean in group theory? Does it mean the same as quotient group? I have seen the above notation a lot while studying group theory but it still remains unclear to me about the meaning of this notation? | 2022/12/26 | [
"https://math.stackexchange.com/questions/4605722",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/1129649/"
] | The index $[G:H]$ is the number of left cosets of $H$ in $G$ and it is the number of right cosets of $H$ in $G$. That those numbers are equal is obvious when $G$ is abelian, but it is true for all groups and this does *not* require $G$ to be finite, so the equality is not fully explained by relying on Lagrange’s theorem for finite groups.
For each left $H$-coset $gH = \{gh : h \in H\}$, inverting its elements gives us
$$\{h^{-1}g^{-1} : h \in H\} = \{hg^{-1} : h \in H\} = Hg^{-1},
$$
which is a right $H$-coset, and sending each $gH$ to $Hg^{-1}$ is a well-defined bijection from the left $H$-cosets to the right $H$-cosets, even if the number of cosets is infinite.
For example, $[\mathbf Z: m\mathbf Z] = m$ for positive integers $m$, $[\mathbf R^\times:\{\pm 1\}]$ is infinite, the positive reals $\mathbf R\_{>0}$ have index $2$ in $\mathbf R^\times$, and the group of real $2\times 2$ matrices with positive determinant ${\rm GL}\_2^+(\mathbf R)$ has index $2$ in the group of real invertible $2\times 2$ matrices ${\rm GL}\_2(\mathbf R)$. That a subgroup of index $2$ is a normal subgroup holds for infinite groups, not just finite groups.
The index, when infinite, should properly be considered as a cardinal number, but typically in a first group theory course you may do very little with subgroup indices when they are infinite, so you might just lump all cases of infinite index together as “$[G:H]=\infty$” in the same way infinite sets $S$ are all lumped together as “$\# S = \infty$” unless there is a good reason to use the more careful notion of cardinal numbers. | $[G:H]$ is very similar to the usual notation of a division. It kind of stands for the number of how many times $H$ fits into $G.$ It is the number of elements of $\left|G/H\right|$ and
\begin{align\*}
G/H=\{g\cdot H\,|\,g\in G\}&=\{1\cdot H, g\_2\cdot H, g\_3\cdot H, g\_4\cdot H,\ldots,g\_{[G:H]}H\}\\
&=H\,\dot\cup\, g\_2H \dot\cup\,\ldots\dot\cup\,g\_{[G:H]}H.
\end{align\*}
The equations are those of sets. If $aH=bH$ then it counts only as one element. It should be noted that $H$ does not have to be a normal subgroup. Subgroup is a sufficient condition to create the equivalence classes $[gH]=\{g\cdot h\,|\,h \in H\}$ that exhaust the group $G.$
$H \trianglelefteq G$ being a normal subgroup is equivalent to $G/H=\{[gH]\,|\,g\in G\} $ carrying a group structure again, or $H$ being the kernel of a group homomorphism $\varphi : G \rightarrow G'.$ However, it is not necessary for $G/H$ to be a group again. It already makes sense to speak of $G/H$ as a set of equivalences classes, modulo $H$ so to say. |
32,774,235 | My customers are not receiving SMS to verify their OTP. We have integrated Twilio with Parse and is using it for OTP Authentication. We are based out of India.
We faced this during test account. It never used to send SMS in the night and received all SMS next day morning. Now we are using a paid account and still the same issue i.e. my customer did not get any SMS during night and also not in the morning. Kindly help.
We will not be able to do business if our customers do not receive OTP SMS.
Is this a known issue ? | 2015/09/25 | [
"https://Stackoverflow.com/questions/32774235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5373344/"
] | India is difficult to get text messages to, there are lots of rules and restrictions
Completed a project recently using a Twilio competitor (Clickatell) and it was the very same problem.
Frow Twilio's website:
**Are there limitations on sending SMS messages to Indian mobile devices?**
>
> **3. They are only delivered between the hours of 9 A.M. and 9 P.M. local Indian time**
>
>
> If you’ve been seeing delivery delays when sending to Indian numbers,
> make sure you are making the requests during the operational hours of
> 9 A.M. to 9 P.M., as overnight messages are likely to be cached until
> the next day.
>
>
>
<https://www.twilio.com/help/faq/sms/are-there-limitations-on-sending-sms-messages-to-indian-mobile-devices> | As E.J. said above, India has a lot of regulations to follow when sending SMS.
This is not a Twilio specific issue.. Other SMS APIs will have the same outcome.
For example, as stated on Nexmo's Country Specific Rules & Regulations webpage:
"We can only guarantee message delivery between 9am to 9pm. Messages submitted after 9pm ***we will attempt to send***, but due to local regulations, these messages will be queued until the morning and you will be charged for them as usual."
Here is some more in-detailed information: [India: Features & Restrictions](https://help.nexmo.com/hc/en-us/articles/204017423-India-Features-Restrictions) |
35,455,281 | As per [this document](http://docs.aws.amazon.com/lambda/latest/dg/vpc.html), if I need to access internet resources from my Lambda function with VPC access, I need to set up a NAT gateway.
So I followed [this guide](http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/vpc-nat-gateway.html) to set up a NAT gateway. However, at the stage when I need to edit the route tables of my subnet to add an entry with destination: 0.0.0.0/0 and target as my NAT gateway's id, I got an error that
```
An entry with this destination already exists
```
I checked and noticed that for that existing entry, the target was an internet gateway for my VPC. If I replace that entry with the NAT gateway id, I cannot access any of the EC2 instances in that VPC through SSH from the outside world. How can I achieve a solution where all the EC2 instances in this VPC:
* Are accessible only via SSH and the rest of the traffic is blocked
* Are able to completely access other EC2 instances in the same VPC
* Lambda function having access to this VPC can access outside resources like SQS and Kinesis. | 2016/02/17 | [
"https://Stackoverflow.com/questions/35455281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3097807/"
] | I found a good detailed tutorial on how to allow your lambda to connect to both VPC ressources and the internet here: <https://gist.github.com/reggi/dc5f2620b7b4f515e68e46255ac042a7>
A quick walk-through:
* setup new subnets for your lambda (with CIDRs not overlapping your existing subnets). You need:
+ one subnet which will be pointing to an Internet Gateway (IGW) to be used by the NAT (let's call it A)
+ several pointing to the NAT to be used by your lambda (B, C and D)
* add a NAT gateway: set the subnet to A
* set your lambda VPC subnets to B, C and D
* create 2 routes table:
+ one that points to your NAT with destination 0.0.0.0/0
+ one that points to your IGW (should already exists) with destination 0.0.0.0/0
* update the subnet A to use the route table pointing to the IGW
* update the subnets B, C and D to use the route table pointing to the NAT
Hope this helps. | You need two different subnets. It sounds as if you only have one.
Lambda can only use *private* subnets inside VPC.
Definition of a private subnet: the default route is a NAT instance (which most be on a different, public subnet) or a NAT Gateway, and *no* machines in the subnet have a public IP address. Machines with public IP addresses are allowed on a private subnet, but for the most part, they will not work properly, because this is technically a misconfiguration.
Definition of a public subnet: the default route is the `igw-xxxxxxxx` Internet Gateway object, and machines have public IP addresses assigned. Machines without public IP addresses are allowed on a public subnet, but they will not be able to access the Internet, because this is a misconfiguration.
It sounds like you are trying to change your existing subnet from public to private by changing the default route. As expected, this breaks other things.
See also [Why do we need private subnet in VPC?](https://stackoverflow.com/a/22212017/1695906) |
35,455,281 | As per [this document](http://docs.aws.amazon.com/lambda/latest/dg/vpc.html), if I need to access internet resources from my Lambda function with VPC access, I need to set up a NAT gateway.
So I followed [this guide](http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/vpc-nat-gateway.html) to set up a NAT gateway. However, at the stage when I need to edit the route tables of my subnet to add an entry with destination: 0.0.0.0/0 and target as my NAT gateway's id, I got an error that
```
An entry with this destination already exists
```
I checked and noticed that for that existing entry, the target was an internet gateway for my VPC. If I replace that entry with the NAT gateway id, I cannot access any of the EC2 instances in that VPC through SSH from the outside world. How can I achieve a solution where all the EC2 instances in this VPC:
* Are accessible only via SSH and the rest of the traffic is blocked
* Are able to completely access other EC2 instances in the same VPC
* Lambda function having access to this VPC can access outside resources like SQS and Kinesis. | 2016/02/17 | [
"https://Stackoverflow.com/questions/35455281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3097807/"
] | Hey guys I developed a step by step tutorial with explicit screenshots about it:
Part I
1. Create a lambda function in AWS
2. Create an API Gateway to redirect all the requests to your AWS Lambda Function
<https://medium.com/@shontauro/how-can-i-turn-my-restful-api-into-a-serverless-application-and-deploy-it-to-aws-lambda-step-by-ec7ce38e18be>
Part II
3. Configure a VPC for your lambda function
4. Grant internet access to the lambda function in a safety way
5. Deploy the Node.js Restful API into your Lambda Function
<https://medium.com/@shontauro/how-can-i-turn-my-restful-api-into-a-serverless-application-and-deploy-it-to-aws-lambda-step-by-8ff6cc97780f> | You actually don't need to create Internet and NAT gateways anymore:<https://aws.amazon.com/blogs/security/how-to-connect-to-aws-secrets-manager-service-within-a-virtual-private-cloud/> |
35,455,281 | As per [this document](http://docs.aws.amazon.com/lambda/latest/dg/vpc.html), if I need to access internet resources from my Lambda function with VPC access, I need to set up a NAT gateway.
So I followed [this guide](http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/vpc-nat-gateway.html) to set up a NAT gateway. However, at the stage when I need to edit the route tables of my subnet to add an entry with destination: 0.0.0.0/0 and target as my NAT gateway's id, I got an error that
```
An entry with this destination already exists
```
I checked and noticed that for that existing entry, the target was an internet gateway for my VPC. If I replace that entry with the NAT gateway id, I cannot access any of the EC2 instances in that VPC through SSH from the outside world. How can I achieve a solution where all the EC2 instances in this VPC:
* Are accessible only via SSH and the rest of the traffic is blocked
* Are able to completely access other EC2 instances in the same VPC
* Lambda function having access to this VPC can access outside resources like SQS and Kinesis. | 2016/02/17 | [
"https://Stackoverflow.com/questions/35455281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3097807/"
] | You need both the IGW and the NAT gateway for this to work.
In the public subnets (ones you want to reach from outside) point the 0.0.0.0/0 traffic to the IGW gateway. The NAT gateway itself needs to sit in one of these public subnets.
In the private subnets that you want to NAT point 0.0.0.0/0 traffic to the NAT gateway elastic network interface.
If 0.0.0.0/0 is aleady bound to the gateway you need to remove that and add it pointing the NAT gateway.
See:
<http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/vpc-nat-gateway.html> | You actually don't need to create Internet and NAT gateways anymore:<https://aws.amazon.com/blogs/security/how-to-connect-to-aws-secrets-manager-service-within-a-virtual-private-cloud/> |
35,455,281 | As per [this document](http://docs.aws.amazon.com/lambda/latest/dg/vpc.html), if I need to access internet resources from my Lambda function with VPC access, I need to set up a NAT gateway.
So I followed [this guide](http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/vpc-nat-gateway.html) to set up a NAT gateway. However, at the stage when I need to edit the route tables of my subnet to add an entry with destination: 0.0.0.0/0 and target as my NAT gateway's id, I got an error that
```
An entry with this destination already exists
```
I checked and noticed that for that existing entry, the target was an internet gateway for my VPC. If I replace that entry with the NAT gateway id, I cannot access any of the EC2 instances in that VPC through SSH from the outside world. How can I achieve a solution where all the EC2 instances in this VPC:
* Are accessible only via SSH and the rest of the traffic is blocked
* Are able to completely access other EC2 instances in the same VPC
* Lambda function having access to this VPC can access outside resources like SQS and Kinesis. | 2016/02/17 | [
"https://Stackoverflow.com/questions/35455281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3097807/"
] | For using your Lambda inside of your VPC and internet access:
I believe, most of you already have IGW ,that you're working with inside of your VPC and working with internet,so no need create a new one.
Steps worked for me:
1. Create a new subnets (recommended 2 or more) under your main VPC. Give it new CIDR with a mask ,you think it'll be count of network interfaces use in your Lambda.(I did X.X.X.X/28 , because for us it's enough)
2. Create NAT Gateway , add to it Elastic IP or create new EIP and add it to your main Subnet under your VPC. (remember it'll work if you already have Internet Gateway)
3. Create Route table and add 0.0.0.0/0 route to Target - Nat Gateway ID (nat-xxxxxxxxxxxxxxxxx)that we've created (step 2)
4. Create new Security Groups (ALL to ALL) for your lambda to work with internet. I believe it's secure to add 0.0.0.0/0 to lambda for internet.
5. Open lambda - choose your VPC, add SG that's you're working with and add new created from the step 4 to work with internet. press Save and Test. | You actually don't need to create Internet and NAT gateways anymore:<https://aws.amazon.com/blogs/security/how-to-connect-to-aws-secrets-manager-service-within-a-virtual-private-cloud/> |
35,455,281 | As per [this document](http://docs.aws.amazon.com/lambda/latest/dg/vpc.html), if I need to access internet resources from my Lambda function with VPC access, I need to set up a NAT gateway.
So I followed [this guide](http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/vpc-nat-gateway.html) to set up a NAT gateway. However, at the stage when I need to edit the route tables of my subnet to add an entry with destination: 0.0.0.0/0 and target as my NAT gateway's id, I got an error that
```
An entry with this destination already exists
```
I checked and noticed that for that existing entry, the target was an internet gateway for my VPC. If I replace that entry with the NAT gateway id, I cannot access any of the EC2 instances in that VPC through SSH from the outside world. How can I achieve a solution where all the EC2 instances in this VPC:
* Are accessible only via SSH and the rest of the traffic is blocked
* Are able to completely access other EC2 instances in the same VPC
* Lambda function having access to this VPC can access outside resources like SQS and Kinesis. | 2016/02/17 | [
"https://Stackoverflow.com/questions/35455281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3097807/"
] | You need both the IGW and the NAT gateway for this to work.
In the public subnets (ones you want to reach from outside) point the 0.0.0.0/0 traffic to the IGW gateway. The NAT gateway itself needs to sit in one of these public subnets.
In the private subnets that you want to NAT point 0.0.0.0/0 traffic to the NAT gateway elastic network interface.
If 0.0.0.0/0 is aleady bound to the gateway you need to remove that and add it pointing the NAT gateway.
See:
<http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/vpc-nat-gateway.html> | For using your Lambda inside of your VPC and internet access:
I believe, most of you already have IGW ,that you're working with inside of your VPC and working with internet,so no need create a new one.
Steps worked for me:
1. Create a new subnets (recommended 2 or more) under your main VPC. Give it new CIDR with a mask ,you think it'll be count of network interfaces use in your Lambda.(I did X.X.X.X/28 , because for us it's enough)
2. Create NAT Gateway , add to it Elastic IP or create new EIP and add it to your main Subnet under your VPC. (remember it'll work if you already have Internet Gateway)
3. Create Route table and add 0.0.0.0/0 route to Target - Nat Gateway ID (nat-xxxxxxxxxxxxxxxxx)that we've created (step 2)
4. Create new Security Groups (ALL to ALL) for your lambda to work with internet. I believe it's secure to add 0.0.0.0/0 to lambda for internet.
5. Open lambda - choose your VPC, add SG that's you're working with and add new created from the step 4 to work with internet. press Save and Test. |
35,455,281 | As per [this document](http://docs.aws.amazon.com/lambda/latest/dg/vpc.html), if I need to access internet resources from my Lambda function with VPC access, I need to set up a NAT gateway.
So I followed [this guide](http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/vpc-nat-gateway.html) to set up a NAT gateway. However, at the stage when I need to edit the route tables of my subnet to add an entry with destination: 0.0.0.0/0 and target as my NAT gateway's id, I got an error that
```
An entry with this destination already exists
```
I checked and noticed that for that existing entry, the target was an internet gateway for my VPC. If I replace that entry with the NAT gateway id, I cannot access any of the EC2 instances in that VPC through SSH from the outside world. How can I achieve a solution where all the EC2 instances in this VPC:
* Are accessible only via SSH and the rest of the traffic is blocked
* Are able to completely access other EC2 instances in the same VPC
* Lambda function having access to this VPC can access outside resources like SQS and Kinesis. | 2016/02/17 | [
"https://Stackoverflow.com/questions/35455281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3097807/"
] | You need two different subnets. It sounds as if you only have one.
Lambda can only use *private* subnets inside VPC.
Definition of a private subnet: the default route is a NAT instance (which most be on a different, public subnet) or a NAT Gateway, and *no* machines in the subnet have a public IP address. Machines with public IP addresses are allowed on a private subnet, but for the most part, they will not work properly, because this is technically a misconfiguration.
Definition of a public subnet: the default route is the `igw-xxxxxxxx` Internet Gateway object, and machines have public IP addresses assigned. Machines without public IP addresses are allowed on a public subnet, but they will not be able to access the Internet, because this is a misconfiguration.
It sounds like you are trying to change your existing subnet from public to private by changing the default route. As expected, this breaks other things.
See also [Why do we need private subnet in VPC?](https://stackoverflow.com/a/22212017/1695906) | You actually don't need to create Internet and NAT gateways anymore:<https://aws.amazon.com/blogs/security/how-to-connect-to-aws-secrets-manager-service-within-a-virtual-private-cloud/> |
35,455,281 | As per [this document](http://docs.aws.amazon.com/lambda/latest/dg/vpc.html), if I need to access internet resources from my Lambda function with VPC access, I need to set up a NAT gateway.
So I followed [this guide](http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/vpc-nat-gateway.html) to set up a NAT gateway. However, at the stage when I need to edit the route tables of my subnet to add an entry with destination: 0.0.0.0/0 and target as my NAT gateway's id, I got an error that
```
An entry with this destination already exists
```
I checked and noticed that for that existing entry, the target was an internet gateway for my VPC. If I replace that entry with the NAT gateway id, I cannot access any of the EC2 instances in that VPC through SSH from the outside world. How can I achieve a solution where all the EC2 instances in this VPC:
* Are accessible only via SSH and the rest of the traffic is blocked
* Are able to completely access other EC2 instances in the same VPC
* Lambda function having access to this VPC can access outside resources like SQS and Kinesis. | 2016/02/17 | [
"https://Stackoverflow.com/questions/35455281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3097807/"
] | You need both the IGW and the NAT gateway for this to work.
In the public subnets (ones you want to reach from outside) point the 0.0.0.0/0 traffic to the IGW gateway. The NAT gateway itself needs to sit in one of these public subnets.
In the private subnets that you want to NAT point 0.0.0.0/0 traffic to the NAT gateway elastic network interface.
If 0.0.0.0/0 is aleady bound to the gateway you need to remove that and add it pointing the NAT gateway.
See:
<http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/vpc-nat-gateway.html> | I found a good detailed tutorial on how to allow your lambda to connect to both VPC ressources and the internet here: <https://gist.github.com/reggi/dc5f2620b7b4f515e68e46255ac042a7>
A quick walk-through:
* setup new subnets for your lambda (with CIDRs not overlapping your existing subnets). You need:
+ one subnet which will be pointing to an Internet Gateway (IGW) to be used by the NAT (let's call it A)
+ several pointing to the NAT to be used by your lambda (B, C and D)
* add a NAT gateway: set the subnet to A
* set your lambda VPC subnets to B, C and D
* create 2 routes table:
+ one that points to your NAT with destination 0.0.0.0/0
+ one that points to your IGW (should already exists) with destination 0.0.0.0/0
* update the subnet A to use the route table pointing to the IGW
* update the subnets B, C and D to use the route table pointing to the NAT
Hope this helps. |
35,455,281 | As per [this document](http://docs.aws.amazon.com/lambda/latest/dg/vpc.html), if I need to access internet resources from my Lambda function with VPC access, I need to set up a NAT gateway.
So I followed [this guide](http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/vpc-nat-gateway.html) to set up a NAT gateway. However, at the stage when I need to edit the route tables of my subnet to add an entry with destination: 0.0.0.0/0 and target as my NAT gateway's id, I got an error that
```
An entry with this destination already exists
```
I checked and noticed that for that existing entry, the target was an internet gateway for my VPC. If I replace that entry with the NAT gateway id, I cannot access any of the EC2 instances in that VPC through SSH from the outside world. How can I achieve a solution where all the EC2 instances in this VPC:
* Are accessible only via SSH and the rest of the traffic is blocked
* Are able to completely access other EC2 instances in the same VPC
* Lambda function having access to this VPC can access outside resources like SQS and Kinesis. | 2016/02/17 | [
"https://Stackoverflow.com/questions/35455281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3097807/"
] | Hey guys I developed a step by step tutorial with explicit screenshots about it:
Part I
1. Create a lambda function in AWS
2. Create an API Gateway to redirect all the requests to your AWS Lambda Function
<https://medium.com/@shontauro/how-can-i-turn-my-restful-api-into-a-serverless-application-and-deploy-it-to-aws-lambda-step-by-ec7ce38e18be>
Part II
3. Configure a VPC for your lambda function
4. Grant internet access to the lambda function in a safety way
5. Deploy the Node.js Restful API into your Lambda Function
<https://medium.com/@shontauro/how-can-i-turn-my-restful-api-into-a-serverless-application-and-deploy-it-to-aws-lambda-step-by-8ff6cc97780f> | For using your Lambda inside of your VPC and internet access:
I believe, most of you already have IGW ,that you're working with inside of your VPC and working with internet,so no need create a new one.
Steps worked for me:
1. Create a new subnets (recommended 2 or more) under your main VPC. Give it new CIDR with a mask ,you think it'll be count of network interfaces use in your Lambda.(I did X.X.X.X/28 , because for us it's enough)
2. Create NAT Gateway , add to it Elastic IP or create new EIP and add it to your main Subnet under your VPC. (remember it'll work if you already have Internet Gateway)
3. Create Route table and add 0.0.0.0/0 route to Target - Nat Gateway ID (nat-xxxxxxxxxxxxxxxxx)that we've created (step 2)
4. Create new Security Groups (ALL to ALL) for your lambda to work with internet. I believe it's secure to add 0.0.0.0/0 to lambda for internet.
5. Open lambda - choose your VPC, add SG that's you're working with and add new created from the step 4 to work with internet. press Save and Test. |
35,455,281 | As per [this document](http://docs.aws.amazon.com/lambda/latest/dg/vpc.html), if I need to access internet resources from my Lambda function with VPC access, I need to set up a NAT gateway.
So I followed [this guide](http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/vpc-nat-gateway.html) to set up a NAT gateway. However, at the stage when I need to edit the route tables of my subnet to add an entry with destination: 0.0.0.0/0 and target as my NAT gateway's id, I got an error that
```
An entry with this destination already exists
```
I checked and noticed that for that existing entry, the target was an internet gateway for my VPC. If I replace that entry with the NAT gateway id, I cannot access any of the EC2 instances in that VPC through SSH from the outside world. How can I achieve a solution where all the EC2 instances in this VPC:
* Are accessible only via SSH and the rest of the traffic is blocked
* Are able to completely access other EC2 instances in the same VPC
* Lambda function having access to this VPC can access outside resources like SQS and Kinesis. | 2016/02/17 | [
"https://Stackoverflow.com/questions/35455281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3097807/"
] | I found a good detailed tutorial on how to allow your lambda to connect to both VPC ressources and the internet here: <https://gist.github.com/reggi/dc5f2620b7b4f515e68e46255ac042a7>
A quick walk-through:
* setup new subnets for your lambda (with CIDRs not overlapping your existing subnets). You need:
+ one subnet which will be pointing to an Internet Gateway (IGW) to be used by the NAT (let's call it A)
+ several pointing to the NAT to be used by your lambda (B, C and D)
* add a NAT gateway: set the subnet to A
* set your lambda VPC subnets to B, C and D
* create 2 routes table:
+ one that points to your NAT with destination 0.0.0.0/0
+ one that points to your IGW (should already exists) with destination 0.0.0.0/0
* update the subnet A to use the route table pointing to the IGW
* update the subnets B, C and D to use the route table pointing to the NAT
Hope this helps. | For using your Lambda inside of your VPC and internet access:
I believe, most of you already have IGW ,that you're working with inside of your VPC and working with internet,so no need create a new one.
Steps worked for me:
1. Create a new subnets (recommended 2 or more) under your main VPC. Give it new CIDR with a mask ,you think it'll be count of network interfaces use in your Lambda.(I did X.X.X.X/28 , because for us it's enough)
2. Create NAT Gateway , add to it Elastic IP or create new EIP and add it to your main Subnet under your VPC. (remember it'll work if you already have Internet Gateway)
3. Create Route table and add 0.0.0.0/0 route to Target - Nat Gateway ID (nat-xxxxxxxxxxxxxxxxx)that we've created (step 2)
4. Create new Security Groups (ALL to ALL) for your lambda to work with internet. I believe it's secure to add 0.0.0.0/0 to lambda for internet.
5. Open lambda - choose your VPC, add SG that's you're working with and add new created from the step 4 to work with internet. press Save and Test. |
35,455,281 | As per [this document](http://docs.aws.amazon.com/lambda/latest/dg/vpc.html), if I need to access internet resources from my Lambda function with VPC access, I need to set up a NAT gateway.
So I followed [this guide](http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/vpc-nat-gateway.html) to set up a NAT gateway. However, at the stage when I need to edit the route tables of my subnet to add an entry with destination: 0.0.0.0/0 and target as my NAT gateway's id, I got an error that
```
An entry with this destination already exists
```
I checked and noticed that for that existing entry, the target was an internet gateway for my VPC. If I replace that entry with the NAT gateway id, I cannot access any of the EC2 instances in that VPC through SSH from the outside world. How can I achieve a solution where all the EC2 instances in this VPC:
* Are accessible only via SSH and the rest of the traffic is blocked
* Are able to completely access other EC2 instances in the same VPC
* Lambda function having access to this VPC can access outside resources like SQS and Kinesis. | 2016/02/17 | [
"https://Stackoverflow.com/questions/35455281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3097807/"
] | You need two different subnets. It sounds as if you only have one.
Lambda can only use *private* subnets inside VPC.
Definition of a private subnet: the default route is a NAT instance (which most be on a different, public subnet) or a NAT Gateway, and *no* machines in the subnet have a public IP address. Machines with public IP addresses are allowed on a private subnet, but for the most part, they will not work properly, because this is technically a misconfiguration.
Definition of a public subnet: the default route is the `igw-xxxxxxxx` Internet Gateway object, and machines have public IP addresses assigned. Machines without public IP addresses are allowed on a public subnet, but they will not be able to access the Internet, because this is a misconfiguration.
It sounds like you are trying to change your existing subnet from public to private by changing the default route. As expected, this breaks other things.
See also [Why do we need private subnet in VPC?](https://stackoverflow.com/a/22212017/1695906) | For using your Lambda inside of your VPC and internet access:
I believe, most of you already have IGW ,that you're working with inside of your VPC and working with internet,so no need create a new one.
Steps worked for me:
1. Create a new subnets (recommended 2 or more) under your main VPC. Give it new CIDR with a mask ,you think it'll be count of network interfaces use in your Lambda.(I did X.X.X.X/28 , because for us it's enough)
2. Create NAT Gateway , add to it Elastic IP or create new EIP and add it to your main Subnet under your VPC. (remember it'll work if you already have Internet Gateway)
3. Create Route table and add 0.0.0.0/0 route to Target - Nat Gateway ID (nat-xxxxxxxxxxxxxxxxx)that we've created (step 2)
4. Create new Security Groups (ALL to ALL) for your lambda to work with internet. I believe it's secure to add 0.0.0.0/0 to lambda for internet.
5. Open lambda - choose your VPC, add SG that's you're working with and add new created from the step 4 to work with internet. press Save and Test. |
40,823,052 | I need to create the spacing between the two `<i>` tags, and make a vertical line in between them.
Here is my code:
```css
#wrap {
width: 650px;
margin: 0 auto;
}
#left_col {
float: left;
width: 300px;
}
#right_col {
float: right;
width: 300px;
padding-left: 20px;
}
```
```html
<div id="wrap">
<div id="left_col">
<p>Are you a Developer?</p>
<i class="fa fa-facebook" aria-hidden="true" style="padding-left: 10px; padding-top: 20px;">
Register Your Project Online</i>
<br><i class="fa fa-facebook" aria-hidden="true" style="padding-left: 10px;">
Wait for Project Approval </i>
<i class="fa fa-facebook" aria-hidden="true" style="padding-left: 10px;">
Raise funding in 90 days </i>
<i class="fa fa-facebook" aria-hidden="true" style="padding-left: 10px;">
Provide Regular construction updates </i>
<i class="fa fa-facebook" aria-hidden="true" style="padding-left: 10px;">
Complete and Sell Project </i>
<i class="fa fa-facebook" aria-hidden="true" style="padding-left: 10px;">
Destribute funds to Investor </i>
</div>
```
How can I increase the gaping between the `<i>` tag and add a vertical line at the end of every line? | 2016/11/26 | [
"https://Stackoverflow.com/questions/40823052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7183476/"
] | Like this is one way. I think you want a **vertical** line like this :
```css
#wrap {
width: 650px;
margin: 0 auto;
}
#left_col {
float: left;
width: 300px;
}
#right_col {
float: right;
width: 300px;
padding-left: 20px;
}
.cont i {
text-align: center;
margin: 5px;
padding:5px;
line-height: 25px;
}
.divider {
width: 50%;
height: 50px;
border-right:solid;
border-left-color: black;
}
.divider2 {
width: 50px;
height: 50px;
border-left:solid;
border-left-color: black;
}
```
```html
<div id="wrap">
<div id="left_col" class="cont">
<p>Are you a Developer?</p>
<i class="fa fa-facebook" aria-hidden="true" style="padding-left: 10px; padding-top: 20px;">
Register Your Project Online</i>
<div class="divider"></div>
<i class="fa fa-facebook" aria-hidden="true" style="padding-left: 10px;">
Wait for Project Approval </i>
<div class="divider"></div>
<i class="fa fa-facebook" aria-hidden="true" style="padding-left: 10px;">
Raise funding in 90 days </i>
<div class="divider"></div>
<i class="fa fa-facebook" aria-hidden="true" style="padding-left: 10px;">
Provide Regular construction updates </i>
<div class="divider"></div>
<i class="fa fa-facebook" aria-hidden="true" style="padding-left: 10px;">
Complete and Sell Project </i>
<div class="divider"></div>
<i class="fa fa-facebook" aria-hidden="true" style="padding-left: 10px;">
Destribute funds to Investor </i>
</div>
</div>
```
I have put two classes `divider` , `divider2`, change and play with width and height and `border-left` and `border-right` to get your desire line.
BTW, You may also want to check [bootstrap timeline](http://bootsnipp.com/snippets/featured/timeline-responsive) | You can add a line-height to the i and then to get the line under you add a
```
hr
```
tag.
```css
i, cite, em, var, address, dfn {
line-height: 30px;
}
#wrap {
width: 650px;
margin: 0 auto;
}
#left_col {
float: left;
width: 300px;
}
#right_col {
float: right;
width: 300px;
padding-left: 20px;
}
```
```html
<div id="wrap">
<div id="left_col">
<p>Are you a Developer?</p>
<i class="fa fa-facebook" aria-hidden="true" style="padding-left: 10px; padding-top: 20px;">
Register Your Project Online</i>
<i class="fa fa-facebook" aria-hidden="true" style="padding-left: 10px;">
<hr>
Wait for Project Approval </i>
<i class="fa fa-facebook" aria-hidden="true" style="padding-left: 10px;">
<hr>
Raise funding in 90 days </i>
<i class="fa fa-facebook" aria-hidden="true" style="padding-left: 10px;">
<hr>
Provide Regular construction updates </i>
<i class="fa fa-facebook" aria-hidden="true" style="padding-left: 10px;">
<hr>
Complete and Sell Project </i>
<i class="fa fa-facebook" aria-hidden="true" style="padding-left: 10px;">
<hr>
Destribute funds to Investor </i>
</div>
``` |
32,190,870 | I have an AngularJS app that is using node.js and Loopbackjs to communicate with a mysql database. I am able to properly show my GET request on the `partial-home.html` aspect of the page, but when I create a new user it returns the following error:
```
POST http://localhost:3000/api/se_users 422 (Unprocessable Entity)
```
Here is my code:
partial-create.html
```
<div class="row">
<div class="col-md-8">
<h1>Create a User</h1>
</div>
</div>
<div class="container-fluid">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<form name="create" ng-submit="se_user()">
<div class="form-group">
<label for="user_id">ID</label>
<input type="text" class="form-control" ng-model="user.eid" placeholder="Enter EID">
</div>
<div class="form-group">
<label for="first_nm">First Name</label>
<input type="text" class="form-control" ng-model="user.first_nm" placeholder="Enter First Name">
</div>
<div class="form-group">
<label for="last_nm">Last Name</label>
<input type="text" class="form-control" ng-model="user.last_nm" placeholder="Enter Last Name">
</div>
<div class="form-group">
<label for="email_adr">Email Address</label>
<input type="text" class="form-control" ng-model="user.email_adr" placeholder="Enter Item Type">
</div>
<div class="form-group">
<label for="user_role">Role</label>
<input type="text" class="form-control" ng-model="user.role" placeholder="Enter Status Code">
</div>
<div class="form-group">
<label for="user_active">Active</label>
<div class="radio">
<label>
<input type="radio" name="optionsRadios" id="optionsRadios1" value="Yes" ng-model="user.active" checked>Yes
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="optionsRadios" id="optionsRadios2" value="No" ng-model="user.active">No
</label>
</div>
</div>
<div class="form-group">
<label for="mgr_full_nm">Manager Name</label>
<input type="text" class="form-control" ng-model="user.mgr_full_nm" placeholder="Enter Full Name">
</div>
<div class="form-group">
<label for="mgr_eid">Manager EID</label>
<input type="text" class="form-control focus" ng-model="user.mgr_eid" placeholder="Enter Manager EID">
</div>
<div class="form-group">
<label for="insrt_dt">Insert Date</label>
<input type="date" class="form-control" ng-model="user.insrt_dt" placeholder="Enter Date">
</div>
<div class="form-group">
<label for="insrt_user_id">Insert User EID</label>
<input type="text" class="form-control" ng-model="user.insrt_user_id" placeholder="Enter User EID">
</div>
<div class="form-group">
<label for="upd_dt">Update Date</label>
<input type="date" class="form-control" ng-model="user.upd_dt" placeholder="Enter Update User Date">
</div>
<div class="form-group">
<label for="upd_user_id">Update User EID</label>
<input type="text" class="form-control" ng-model="user.upd_user_id" placeholder="Enter Update User EID">
</div>
<button class="btn btn-primary btn-lg" ng-click="addSe_user()">Create User</button>
<br>
<br>
<pre>
{{user | json}}
</pre>
</form>
</div>
</div>
</div>
```
app.js
```
angular.module('userApp', ['ui.router', 'lbServices'])
.controller('UserController', ['$scope', '$state', 'Se_user', function ($scope, $state, Se_user) {
$scope.users = [];
function getSe_users() {
Se_user
.find()
.$promise
.then(function (results) {
$scope.users = results;
});
}
getSe_users();
$scope.addSe_user = function () {
Se_user
.create($scope.user);
alert('You have created a new user!')
$scope.create.$setPristine();
};
$scope.editSe_user = function(user_id) {
Se_user
.editById(user_id)
.$promise
.then(function (user_id) {
getSe_users();
});
};
$scope.removeUser = function (item) {
Se_user
.deleteById(item)
.$promise
.then(function () {
getSe_users();
});
};
}])
.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('');
$stateProvider
.state('home', {
url: '',
templateUrl: 'partial-home.html',
controller: 'UserController'
})
.state('create', {
url: '/create',
templateUrl: 'partial-create.html',
controller: 'UserController'
})
.state('admin', {
url: '/admin',
templateUrl: 'partial-admin.html',
contoller: 'UserController'
})
}]);
``` | 2015/08/24 | [
"https://Stackoverflow.com/questions/32190870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5240486/"
] | Change your create line from
```
Se_user
.create($scope.user);
```
to
```
Se_user
.create($scope.user,
function(newUser) {
console.log(newUser);
// only set pristine here, this
// callback fires on success
$scope.create.$setPristine();
},
function(err) {
console.log(err); // will log the error to the console
}
);
```
The alert shouldn't get in the way of seeing the dev tools output, but this structure makes it easier to get the error response by using the error callback in the call.
The way you have it, the alert that says you have created a new user will fire *immediately after* the ajax call to create the new user is *sent*—not received. There will be some delay for the server to respond so any code you write that depends on the new user being created (or erroring) needs to go inside the callback to the `.create()` method.
See the Loopback Angular $resource docs here: <https://docs.strongloop.com/display/public/LB/AngularJS+JavaScript+SDK#AngularJSJavaScriptSDK-ModelresourceAPI>
**UPDATE:** Chrome console - you should see a stack trace with your 422 error when you inspect the Network call in Chrome Dev tools, like this 401 error:
[](https://i.stack.imgur.com/dANfp.png)
Please edit your original question and post the full text of that trace into it as a code block. | Try changing the content type of the header:
```
header: { 'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8;application/json' }
``` |
414,324 | I have a cloud masked Landsat 7 image collection. For each image I want to [unmask](https://developers.google.com/earth-engine/apidocs/ee-image-unmask) the bands with their respective mean value.
This works fine, unless an image is completely cloud masked and therefore contains no data.
I tried adapting this [related answer (in JavaScript)](https://gis.stackexchange.com/a/341778/128665) to my needs
```py
start_date = "2018-01-01"
end_date = "2021-12-31"
l7 = (ee.ImageCollection("LANDSAT/LE07/C02/T1_L2")
.filterDate(ee.Date(start_date), ee.Date(end_date))
.filterBounds(aoi)
.map(lambda image: image.clip(aoi))
)
band_names = ['SR_B1', 'SR_B2', 'SR_B3', 'SR_B4', 'SR_B5', 'SR_B7', 'QA_PIXEL']
## fn.cloudmask_LS is a wrapper for a cloud masking procedure similar to this: https://gis.stackexchange.com/q/405056/128665
l7 = l7.select(band_names).map(fn.cloudmask_LS('QA_PIXEL'))
## drop QA_PIXEL band
band_names = [b for b in band_names if not b == 'QA_PIXEL']
l7 = l7.select(band_names)
################################################
## function adapted from the other GIS SE answer
################################################
def mask_with_mean(image):
time = image.get("system:time_start")
meanDict = image.reduceRegion(reducer=ee.Reducer.mean(), geometry=aoi)
outImg = ee.Image(ee.Algorithms.If(
meanDict.values(),
image.unmask(ee.Image.constant(meanDict.values(band_names))),
ee.Image(0).selfMask().set('isNull', True)
))
return outImg.set({"system:time_start":time})
## True is an attempt to get the map function to drop nulls but it doesn't appear to be working.
l7 = l7.map(mask_with_mean, True)
```
But I receive the following error:
>
> ee.ee\_exception.EEException: Error in map(ID=LE07\_169068\_20180128):
> Image.constant: Invalid type for constant image value.
>
> Expected type: Number or Array.
>
> Actual type: Object.
>
> Actual value: null
>
>
>
>
I have tried `meanDict` in the `ee.Algorithm.if` true clause also.
I believe the problem arises because `meanDict` is `null` for an empty image but I don't know how to catch that with the `ee.Algorithm.if`. | 2021/10/19 | [
"https://gis.stackexchange.com/questions/414324",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/128665/"
] | Yes, it is absolutely possible using `GDAL/OGR` through `ogr2ogr` by using `-simplify` option. You should pass a `<tolerance>` value as it is described [on their website.](https://gdal.org/programs/ogr2ogr.html#cmdoption-ogr2ogr-simplify)
Another way is to use `osgeo.ogr.Geometry.Buffer(self, *args, **kwargs)` on which supports arguments to control distance and number of segments.
If your shapes are polylines you can use `shapely->parallel_offset` as well. which has a `round` option.
Good Luck. | You could use GRASS GIS:
Create `grass_batch_job.sh` file for GRASS GIS:
```
v.in.ogr min_area=0.0001 snap=-1.0 input="input_file.shp" output="my_vector" --overwrite -o
v.generalize input=my_vector type="line,boundary,area" method="chaiken" threshold=1 look_ahead=7 reduction=50 slide=0.5 angle_thresh=3 degree_thresh=0 closeness_thresh=0 betweeness_thresh=0 alpha=1 beta=1 iterations=1 -l output=my_output --overwrite
v.out.ogr type="auto" input="my_output" output="smooth.gpkg" format="GPKG" --overwrite
```
now run it with `grass --tmp-location EPSG:8353 --exec sh grass_batch_job.sh`
(modify EPSG and `input_file.shp` according to your needs) |
45,241 | I am really unsure about how to go about this question and which circuits to consider.
Here's the question:
Determine the value of the current labeled \$i\$ and the voltage labeled \$v\$ at \$t=0+\$, \$t=1.5ms\$, and \$t = 3.0ms\$.
The circuit is as follows:

[simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fXrbPa.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/)
Relevant equations:
Ohm's law: \$v = iR\$
Decay in source free RC Circuit \$v(t) = v(0) e^{-t/RC}\$
The attempt at a solution:
\$i(0-) = 0.1 A.\$
Therefore,
\$v\$ across 200 ohm: \$200 \* 0.1 = 20 V\$
Since no current flows through capacitor with constant dc current,
\$v\$ across capacitor: \$20 V @ t < 0\$
\$v\$ across capacitor cannot change immediately as it would require infinite power so \$v\$ across capacitor @ \$t = 0\$ is \$20V\$
Here's where the confusion is: Should I include the 200 ohm resistor in my RC circuit? Why or why not? Also, will my circuit be a source free RC circuit?
Also, what will be the current i through the 200 ohm resistor when t>0?
My last question is a theoretical one: Can a current through a resistor change immediately at one instant of time? | 2012/10/22 | [
"https://electronics.stackexchange.com/questions/45241",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/15477/"
] | The voltage across a capacitor discharging into a fixed resistance decays exponentially. The time constant is RC, where C is the capacitance, and R is the resistance between the terminals of the resistor.
$$
V(t)=V(0)e^{\frac{-t}{RC}} \\
$$
You're right that the capacitor starts at 20V, because that's the voltage across the 200 ohm resistor after the capacitor is charged. So you know V(0), and you know C. All you're missing is R. To analyze that properly, think of the switch as a resistor of 0 ohms when closed, and don't worry about the current source. The parallel combination of a 200 ohm resistor and a 0 ohm resistor is 0 ohms. The series combination of a 50 ohm resistor and a 0 ohm resistor is 50 ohms. So the 50 ohm resistor is the only one that matters when determining your discharge constant.
The current through the 200 ohm resistor depends on the voltage across the 200 ohm resistor. The voltage across the 200 ohm resistor is the same as the voltage across the 0 ohm resistor (the closed switch). V=IR, so what's the voltage across that pair of resistors when the switch is closed?
And yes, the voltage across an ideal resistor can change instantaneously. Keep in mind though, there's no such thing as an ideal resistor in the physical world. Everything has capacitance to everything else. | When solving problems like this, it is helpful to draw the two *different* circuits that exist before and after \$t=0\$.
Before, with the switch open, since the circuit is in DC steady state, replace the capacitor with an open circuit and then it is easy to solve for \$v\_C(0)\$, the initial condition.
After, with the switch closed, the current source and 200 \$\Omega \$ resistor are paralleled with a short circuit and so, from the perspective of the capacitor, can be *ignored* (a short circuit in parallel with any other circuit elements is equivalent to a short circuit).
So, the circuit after \$t=0\$ is just the capacitor and the 50 \$\Omega \$ resistor, a simple RC circuit with initial condition \$v\_C(0)\$.
>
> Also, what will be the current i through the 200 ohm resistor when
> t>0?
>
>
>
With a short circuit in parallel, the voltage across the resistor is ?V and, using Ohm's law, the current is ?A.
>
> My last question is a theoretical one: Can a current through a
> resistor change immediately at one instant of time?
>
>
>
Theoretically, within ideal circuit theory, the answer is yes. In reality, the answer is no. for example, physical resistors have associated "parasitic" capacitance and inductance. |
45,241 | I am really unsure about how to go about this question and which circuits to consider.
Here's the question:
Determine the value of the current labeled \$i\$ and the voltage labeled \$v\$ at \$t=0+\$, \$t=1.5ms\$, and \$t = 3.0ms\$.
The circuit is as follows:

[simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fXrbPa.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/)
Relevant equations:
Ohm's law: \$v = iR\$
Decay in source free RC Circuit \$v(t) = v(0) e^{-t/RC}\$
The attempt at a solution:
\$i(0-) = 0.1 A.\$
Therefore,
\$v\$ across 200 ohm: \$200 \* 0.1 = 20 V\$
Since no current flows through capacitor with constant dc current,
\$v\$ across capacitor: \$20 V @ t < 0\$
\$v\$ across capacitor cannot change immediately as it would require infinite power so \$v\$ across capacitor @ \$t = 0\$ is \$20V\$
Here's where the confusion is: Should I include the 200 ohm resistor in my RC circuit? Why or why not? Also, will my circuit be a source free RC circuit?
Also, what will be the current i through the 200 ohm resistor when t>0?
My last question is a theoretical one: Can a current through a resistor change immediately at one instant of time? | 2012/10/22 | [
"https://electronics.stackexchange.com/questions/45241",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/15477/"
] | When solving problems like this, it is helpful to draw the two *different* circuits that exist before and after \$t=0\$.
Before, with the switch open, since the circuit is in DC steady state, replace the capacitor with an open circuit and then it is easy to solve for \$v\_C(0)\$, the initial condition.
After, with the switch closed, the current source and 200 \$\Omega \$ resistor are paralleled with a short circuit and so, from the perspective of the capacitor, can be *ignored* (a short circuit in parallel with any other circuit elements is equivalent to a short circuit).
So, the circuit after \$t=0\$ is just the capacitor and the 50 \$\Omega \$ resistor, a simple RC circuit with initial condition \$v\_C(0)\$.
>
> Also, what will be the current i through the 200 ohm resistor when
> t>0?
>
>
>
With a short circuit in parallel, the voltage across the resistor is ?V and, using Ohm's law, the current is ?A.
>
> My last question is a theoretical one: Can a current through a
> resistor change immediately at one instant of time?
>
>
>
Theoretically, within ideal circuit theory, the answer is yes. In reality, the answer is no. for example, physical resistors have associated "parasitic" capacitance and inductance. | Current in an inductor cannot change suddenly (i.e in zero time). Similarly voltage across a capacitor cannot change suddenly.So \$Vc(0+) = Vc(0-)\$. At \$0-\$ time capacitor is an open circuit (because after a long duration capacitor cannot charge anymore and takes 0 current). So \$Vc(0-)\$ is \$20V\$ which is equal to \$Vc(0+)\$.
Any transient analysis can be done using \$x = A+Be^{-t/timeconstant}\$ formula where \$x\$ can be either voltage or current and A and B are constants which we calculate from known things in the circuit. Comment if you want to know more about how to solve using this method. |
45,241 | I am really unsure about how to go about this question and which circuits to consider.
Here's the question:
Determine the value of the current labeled \$i\$ and the voltage labeled \$v\$ at \$t=0+\$, \$t=1.5ms\$, and \$t = 3.0ms\$.
The circuit is as follows:

[simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fXrbPa.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/)
Relevant equations:
Ohm's law: \$v = iR\$
Decay in source free RC Circuit \$v(t) = v(0) e^{-t/RC}\$
The attempt at a solution:
\$i(0-) = 0.1 A.\$
Therefore,
\$v\$ across 200 ohm: \$200 \* 0.1 = 20 V\$
Since no current flows through capacitor with constant dc current,
\$v\$ across capacitor: \$20 V @ t < 0\$
\$v\$ across capacitor cannot change immediately as it would require infinite power so \$v\$ across capacitor @ \$t = 0\$ is \$20V\$
Here's where the confusion is: Should I include the 200 ohm resistor in my RC circuit? Why or why not? Also, will my circuit be a source free RC circuit?
Also, what will be the current i through the 200 ohm resistor when t>0?
My last question is a theoretical one: Can a current through a resistor change immediately at one instant of time? | 2012/10/22 | [
"https://electronics.stackexchange.com/questions/45241",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/15477/"
] | When solving problems like this, it is helpful to draw the two *different* circuits that exist before and after \$t=0\$.
Before, with the switch open, since the circuit is in DC steady state, replace the capacitor with an open circuit and then it is easy to solve for \$v\_C(0)\$, the initial condition.
After, with the switch closed, the current source and 200 \$\Omega \$ resistor are paralleled with a short circuit and so, from the perspective of the capacitor, can be *ignored* (a short circuit in parallel with any other circuit elements is equivalent to a short circuit).
So, the circuit after \$t=0\$ is just the capacitor and the 50 \$\Omega \$ resistor, a simple RC circuit with initial condition \$v\_C(0)\$.
>
> Also, what will be the current i through the 200 ohm resistor when
> t>0?
>
>
>
With a short circuit in parallel, the voltage across the resistor is ?V and, using Ohm's law, the current is ?A.
>
> My last question is a theoretical one: Can a current through a
> resistor change immediately at one instant of time?
>
>
>
Theoretically, within ideal circuit theory, the answer is yes. In reality, the answer is no. for example, physical resistors have associated "parasitic" capacitance and inductance. | at t=0 the equivalent circuit is very simple.

Since the switch is ideal, it will have 0V drop circulating all the current source and thus closing the path out of the circuit.
Thus the 20V initial condition discharges with an RC time constant of 20uF\*50R=1000 uS.
Did anyone actually guess the answer at 1.5mS and 3mS is 5V(~25%) and 1V(~5%) respectively for the exponential decay from 20V to 0V? |
45,241 | I am really unsure about how to go about this question and which circuits to consider.
Here's the question:
Determine the value of the current labeled \$i\$ and the voltage labeled \$v\$ at \$t=0+\$, \$t=1.5ms\$, and \$t = 3.0ms\$.
The circuit is as follows:

[simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fXrbPa.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/)
Relevant equations:
Ohm's law: \$v = iR\$
Decay in source free RC Circuit \$v(t) = v(0) e^{-t/RC}\$
The attempt at a solution:
\$i(0-) = 0.1 A.\$
Therefore,
\$v\$ across 200 ohm: \$200 \* 0.1 = 20 V\$
Since no current flows through capacitor with constant dc current,
\$v\$ across capacitor: \$20 V @ t < 0\$
\$v\$ across capacitor cannot change immediately as it would require infinite power so \$v\$ across capacitor @ \$t = 0\$ is \$20V\$
Here's where the confusion is: Should I include the 200 ohm resistor in my RC circuit? Why or why not? Also, will my circuit be a source free RC circuit?
Also, what will be the current i through the 200 ohm resistor when t>0?
My last question is a theoretical one: Can a current through a resistor change immediately at one instant of time? | 2012/10/22 | [
"https://electronics.stackexchange.com/questions/45241",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/15477/"
] | When solving problems like this, it is helpful to draw the two *different* circuits that exist before and after \$t=0\$.
Before, with the switch open, since the circuit is in DC steady state, replace the capacitor with an open circuit and then it is easy to solve for \$v\_C(0)\$, the initial condition.
After, with the switch closed, the current source and 200 \$\Omega \$ resistor are paralleled with a short circuit and so, from the perspective of the capacitor, can be *ignored* (a short circuit in parallel with any other circuit elements is equivalent to a short circuit).
So, the circuit after \$t=0\$ is just the capacitor and the 50 \$\Omega \$ resistor, a simple RC circuit with initial condition \$v\_C(0)\$.
>
> Also, what will be the current i through the 200 ohm resistor when
> t>0?
>
>
>
With a short circuit in parallel, the voltage across the resistor is ?V and, using Ohm's law, the current is ?A.
>
> My last question is a theoretical one: Can a current through a
> resistor change immediately at one instant of time?
>
>
>
Theoretically, within ideal circuit theory, the answer is yes. In reality, the answer is no. for example, physical resistors have associated "parasitic" capacitance and inductance. | The original post mentions current 'i' etc, but the current 'i' etc is not shown in the original circuit diagram. Also, the question is not clearly defined because for these kinds of problems, it's necessary to state the position of the switch (open or closed) at time t < 0. If assuming the switch is open at t < 0, then the initial voltage of the capacitor Vc(0-) is 20V, which also equals Vc(0), which also equals Vc(0+) because the capacitor voltage is continuous. Assuming the switch closes at t = 0, you end up with a capacitor in parallel with the 50 Ohm resistor, so the time constant RC will be based on C and the 50 Ohm resistor, and you get the capacitor voltage equation as being: Vc(t) = Vc(0)e^(t/50.C), where Vc(0) is 20V. The current ic(0) will be zero because voltage can't change instantaneously when the switch closes at t = 0. So the voltage remains constant at t = 0, in which case the dvc(t)/dt = 0 at t = 0, so zero capacitor current at t = 0. But at t = 0+ (a touch greater than t=0), ic(t) = CdVc(t)/dt = So knowing the Vc(t) equation will yield the capacitor current equation ic(t) for t >= 0+. And the reference direction for the current is in the same direction as the voltage drop across the resistor.....in other words through the capacitor and 'downwards' (starting from the + terminal of the capacitor and ending at the - terminal of the capacitor).
At t < 0, if the switch is open, then the 200 Ohm resistor and the current source simply produce the 20V at the upper node, which drives the initial capacitor voltage to 20V. Once the switch closes at t = 0, the 200 Ohm resistor disappears because it gets short circuited (and taken out of the picture) by the closed switch. It all depends on what the switch is doing at t < 0 and t = 0, which is why you need to properly define the conditions of the problem/question. |
45,241 | I am really unsure about how to go about this question and which circuits to consider.
Here's the question:
Determine the value of the current labeled \$i\$ and the voltage labeled \$v\$ at \$t=0+\$, \$t=1.5ms\$, and \$t = 3.0ms\$.
The circuit is as follows:

[simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fXrbPa.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/)
Relevant equations:
Ohm's law: \$v = iR\$
Decay in source free RC Circuit \$v(t) = v(0) e^{-t/RC}\$
The attempt at a solution:
\$i(0-) = 0.1 A.\$
Therefore,
\$v\$ across 200 ohm: \$200 \* 0.1 = 20 V\$
Since no current flows through capacitor with constant dc current,
\$v\$ across capacitor: \$20 V @ t < 0\$
\$v\$ across capacitor cannot change immediately as it would require infinite power so \$v\$ across capacitor @ \$t = 0\$ is \$20V\$
Here's where the confusion is: Should I include the 200 ohm resistor in my RC circuit? Why or why not? Also, will my circuit be a source free RC circuit?
Also, what will be the current i through the 200 ohm resistor when t>0?
My last question is a theoretical one: Can a current through a resistor change immediately at one instant of time? | 2012/10/22 | [
"https://electronics.stackexchange.com/questions/45241",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/15477/"
] | The voltage across a capacitor discharging into a fixed resistance decays exponentially. The time constant is RC, where C is the capacitance, and R is the resistance between the terminals of the resistor.
$$
V(t)=V(0)e^{\frac{-t}{RC}} \\
$$
You're right that the capacitor starts at 20V, because that's the voltage across the 200 ohm resistor after the capacitor is charged. So you know V(0), and you know C. All you're missing is R. To analyze that properly, think of the switch as a resistor of 0 ohms when closed, and don't worry about the current source. The parallel combination of a 200 ohm resistor and a 0 ohm resistor is 0 ohms. The series combination of a 50 ohm resistor and a 0 ohm resistor is 50 ohms. So the 50 ohm resistor is the only one that matters when determining your discharge constant.
The current through the 200 ohm resistor depends on the voltage across the 200 ohm resistor. The voltage across the 200 ohm resistor is the same as the voltage across the 0 ohm resistor (the closed switch). V=IR, so what's the voltage across that pair of resistors when the switch is closed?
And yes, the voltage across an ideal resistor can change instantaneously. Keep in mind though, there's no such thing as an ideal resistor in the physical world. Everything has capacitance to everything else. | Current in an inductor cannot change suddenly (i.e in zero time). Similarly voltage across a capacitor cannot change suddenly.So \$Vc(0+) = Vc(0-)\$. At \$0-\$ time capacitor is an open circuit (because after a long duration capacitor cannot charge anymore and takes 0 current). So \$Vc(0-)\$ is \$20V\$ which is equal to \$Vc(0+)\$.
Any transient analysis can be done using \$x = A+Be^{-t/timeconstant}\$ formula where \$x\$ can be either voltage or current and A and B are constants which we calculate from known things in the circuit. Comment if you want to know more about how to solve using this method. |
45,241 | I am really unsure about how to go about this question and which circuits to consider.
Here's the question:
Determine the value of the current labeled \$i\$ and the voltage labeled \$v\$ at \$t=0+\$, \$t=1.5ms\$, and \$t = 3.0ms\$.
The circuit is as follows:

[simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fXrbPa.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/)
Relevant equations:
Ohm's law: \$v = iR\$
Decay in source free RC Circuit \$v(t) = v(0) e^{-t/RC}\$
The attempt at a solution:
\$i(0-) = 0.1 A.\$
Therefore,
\$v\$ across 200 ohm: \$200 \* 0.1 = 20 V\$
Since no current flows through capacitor with constant dc current,
\$v\$ across capacitor: \$20 V @ t < 0\$
\$v\$ across capacitor cannot change immediately as it would require infinite power so \$v\$ across capacitor @ \$t = 0\$ is \$20V\$
Here's where the confusion is: Should I include the 200 ohm resistor in my RC circuit? Why or why not? Also, will my circuit be a source free RC circuit?
Also, what will be the current i through the 200 ohm resistor when t>0?
My last question is a theoretical one: Can a current through a resistor change immediately at one instant of time? | 2012/10/22 | [
"https://electronics.stackexchange.com/questions/45241",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/15477/"
] | The voltage across a capacitor discharging into a fixed resistance decays exponentially. The time constant is RC, where C is the capacitance, and R is the resistance between the terminals of the resistor.
$$
V(t)=V(0)e^{\frac{-t}{RC}} \\
$$
You're right that the capacitor starts at 20V, because that's the voltage across the 200 ohm resistor after the capacitor is charged. So you know V(0), and you know C. All you're missing is R. To analyze that properly, think of the switch as a resistor of 0 ohms when closed, and don't worry about the current source. The parallel combination of a 200 ohm resistor and a 0 ohm resistor is 0 ohms. The series combination of a 50 ohm resistor and a 0 ohm resistor is 50 ohms. So the 50 ohm resistor is the only one that matters when determining your discharge constant.
The current through the 200 ohm resistor depends on the voltage across the 200 ohm resistor. The voltage across the 200 ohm resistor is the same as the voltage across the 0 ohm resistor (the closed switch). V=IR, so what's the voltage across that pair of resistors when the switch is closed?
And yes, the voltage across an ideal resistor can change instantaneously. Keep in mind though, there's no such thing as an ideal resistor in the physical world. Everything has capacitance to everything else. | at t=0 the equivalent circuit is very simple.

Since the switch is ideal, it will have 0V drop circulating all the current source and thus closing the path out of the circuit.
Thus the 20V initial condition discharges with an RC time constant of 20uF\*50R=1000 uS.
Did anyone actually guess the answer at 1.5mS and 3mS is 5V(~25%) and 1V(~5%) respectively for the exponential decay from 20V to 0V? |
45,241 | I am really unsure about how to go about this question and which circuits to consider.
Here's the question:
Determine the value of the current labeled \$i\$ and the voltage labeled \$v\$ at \$t=0+\$, \$t=1.5ms\$, and \$t = 3.0ms\$.
The circuit is as follows:

[simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fXrbPa.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/)
Relevant equations:
Ohm's law: \$v = iR\$
Decay in source free RC Circuit \$v(t) = v(0) e^{-t/RC}\$
The attempt at a solution:
\$i(0-) = 0.1 A.\$
Therefore,
\$v\$ across 200 ohm: \$200 \* 0.1 = 20 V\$
Since no current flows through capacitor with constant dc current,
\$v\$ across capacitor: \$20 V @ t < 0\$
\$v\$ across capacitor cannot change immediately as it would require infinite power so \$v\$ across capacitor @ \$t = 0\$ is \$20V\$
Here's where the confusion is: Should I include the 200 ohm resistor in my RC circuit? Why or why not? Also, will my circuit be a source free RC circuit?
Also, what will be the current i through the 200 ohm resistor when t>0?
My last question is a theoretical one: Can a current through a resistor change immediately at one instant of time? | 2012/10/22 | [
"https://electronics.stackexchange.com/questions/45241",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/15477/"
] | The voltage across a capacitor discharging into a fixed resistance decays exponentially. The time constant is RC, where C is the capacitance, and R is the resistance between the terminals of the resistor.
$$
V(t)=V(0)e^{\frac{-t}{RC}} \\
$$
You're right that the capacitor starts at 20V, because that's the voltage across the 200 ohm resistor after the capacitor is charged. So you know V(0), and you know C. All you're missing is R. To analyze that properly, think of the switch as a resistor of 0 ohms when closed, and don't worry about the current source. The parallel combination of a 200 ohm resistor and a 0 ohm resistor is 0 ohms. The series combination of a 50 ohm resistor and a 0 ohm resistor is 50 ohms. So the 50 ohm resistor is the only one that matters when determining your discharge constant.
The current through the 200 ohm resistor depends on the voltage across the 200 ohm resistor. The voltage across the 200 ohm resistor is the same as the voltage across the 0 ohm resistor (the closed switch). V=IR, so what's the voltage across that pair of resistors when the switch is closed?
And yes, the voltage across an ideal resistor can change instantaneously. Keep in mind though, there's no such thing as an ideal resistor in the physical world. Everything has capacitance to everything else. | The original post mentions current 'i' etc, but the current 'i' etc is not shown in the original circuit diagram. Also, the question is not clearly defined because for these kinds of problems, it's necessary to state the position of the switch (open or closed) at time t < 0. If assuming the switch is open at t < 0, then the initial voltage of the capacitor Vc(0-) is 20V, which also equals Vc(0), which also equals Vc(0+) because the capacitor voltage is continuous. Assuming the switch closes at t = 0, you end up with a capacitor in parallel with the 50 Ohm resistor, so the time constant RC will be based on C and the 50 Ohm resistor, and you get the capacitor voltage equation as being: Vc(t) = Vc(0)e^(t/50.C), where Vc(0) is 20V. The current ic(0) will be zero because voltage can't change instantaneously when the switch closes at t = 0. So the voltage remains constant at t = 0, in which case the dvc(t)/dt = 0 at t = 0, so zero capacitor current at t = 0. But at t = 0+ (a touch greater than t=0), ic(t) = CdVc(t)/dt = So knowing the Vc(t) equation will yield the capacitor current equation ic(t) for t >= 0+. And the reference direction for the current is in the same direction as the voltage drop across the resistor.....in other words through the capacitor and 'downwards' (starting from the + terminal of the capacitor and ending at the - terminal of the capacitor).
At t < 0, if the switch is open, then the 200 Ohm resistor and the current source simply produce the 20V at the upper node, which drives the initial capacitor voltage to 20V. Once the switch closes at t = 0, the 200 Ohm resistor disappears because it gets short circuited (and taken out of the picture) by the closed switch. It all depends on what the switch is doing at t < 0 and t = 0, which is why you need to properly define the conditions of the problem/question. |
37,726,210 | My app simply is not showing for Android 6 devices on the Play Store. I tried Google support and they didn't know the problem either.
My manifest doesn't have any specific limitations on API 23 and only GPS for uses-feature, however no device manages to be able to install the app.
```
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.xx.xx">
<!-- Maps API needs OpenGL ES 2.0. -->
<uses-feature
android:glEsVersion="0x00020000"
android:required="false" />
<uses-sdk android:minSdkVersion="9" android:targetSdkVersion="23" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.BROADCAST_STICKY" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<permission
android:name="${applicationId}.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="${applicationId}.permission.MAPS_RECEIVE" />
<application
android:name=".applicationclass"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:screenOrientation="portrait"
android:theme="@style/AppTheme">
<activity
android:name=".splash.SplashContainer"
android:label="@string/app_name"
android:theme="@style/AppThemeNoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".splash.SplashActivity"
android:label="@string/app_name"
android:screenOrientation="portrait" />
<activity
android:name=".home.HomeActivity"
android:label="@string/app_name"
android:screenOrientation="portrait" />
<activity
android:name=".register.WelcomeActivity"
android:label="@string/app_name"
android:screenOrientation="portrait" />
<activity
android:name=".register.RegisterActivity"
android:label="@string/app_name"
android:screenOrientation="portrait" />
<receiver android:name=".services.Pulse" />
<service
android:name="com.google.android.gms.analytics.AnalyticsService"
android:exported="false" />
<receiver android:name="ServiceWakingReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
<receiver android:name="com.google.android.gms.analytics.AnalyticsReceiver">
<intent-filter>
<action android:name="com.google.android.gms.analytics.ANALYTICS_DISPATCH" />
</intent-filter>
</receiver>
<receiver android:name="com.google.android.gms.analytics.CampaignTrackingReceiver">
<intent-filter>
<action android:name="com.android.vending.INSTALL_REFERRER" />
</intent-filter>
</receiver>
<service android:name="com.google.android.gms.analytics.CampaignTrackingService" />
<!-- Maps key -->
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="key" />
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
<meta-data
android:name="io.fabric.ApiKey"
android:value="key" />
</application>
</manifest>
``` | 2016/06/09 | [
"https://Stackoverflow.com/questions/37726210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3335648/"
] | After chatting with the Google support team, they shared with me the problem.
Their report gave this on a Samsung S5 phone:
```
Missing device feature:
android.hardware.telephony
```
Google Play is marking Android 6.0.x phones as not compatible when using the *android.hardware.telephony*, even if the device has it;
I added this to my manifest and the problem was solved:
```
<uses-permission
android:name="android.permission.CALL_PHONE"
android:required="false" />
<uses-feature
android:name="android.hardware.telephony"
android:required="false" />
``` | Make sure the right SDK version is defined in build.gradle as well.
```
defaultConfig {
/**
* applicationId uniquely identifies the package for publishing.
* However, your source code should still reference the package name
* defined by the package attribute in the main/AndroidManifest.xml file.
*/
applicationId 'com.xx.xx'
// Defines the minimum API level required to run the app.
minSdkVersion 9
// Specifies the API level used to test the app.
targetSdkVersion 23
//Other settings...
}
```
For a more in detail setup of your gradle file check [this example](https://developer.android.com/studio/build/index.html#module-level). |
48,256,681 | I use a open API get the bellow information using its access key:
```
HTTPConnectionPool(host='freeipapi.17mon.cn', port=80): Max retries exceeded with url: /183.11.178.118 (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x103780780>: Failed to establish a new connection: [Errno 8] nodename nor servname provided, or not known',))
{'status': 0, 'address': 'CN|广东|深圳|None|CHINANET|0|0', 'content': {'address_detail': {'province': '广东省', 'city_code': 340, 'street': '', 'city': '深圳市', 'district': '', 'street_number': ''}, 'address': '广东省深圳市', 'point': {'x': '12693451.44', 'y': '2560682.35'}}}
```
You see, the later data `{'status': 0, 'address': 'CN|广东|深圳|None|CHINANET|0|0', 'content': {'address_detail': {'province': '广东省', 'city_code': 340, 'street': '', 'city': '深圳市', 'district': '', 'street_number': ''}, 'address': '广东省深圳市', 'point': {'x': '12693451.44', 'y': '2560682.35'}}}` is my need.
How can I get it?
The code is bellow:
```
import urllib, urllib.request
import json
ak_url="http://api.map.baidu.com/location/ip"
result = requests.get(ak_url,{"ip":"183.11.178.1","ak":BAIDU_IPADDR_AK})
print(result.json()) # There prints the upper data.
``` | 2018/01/15 | [
"https://Stackoverflow.com/questions/48256681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6523163/"
] | Your data is actually returned by `result.json()`.
Perhaps you are confused by the extra `HTTPConnectionPool` details.
That could be an indicator that `result.json()` has a custom representation (as in, it implements `__repr__` or `__str__`) and appends that data behind the scenes when printing. | Use requests. Much easier. `pip install requests`
Then:
```
import requests
ak_url="http://api.map.baidu.com/location/ip"
BAIDU_IPADDR_AK = 'test'
result = requests.get(ak_url,{"ip":"183.11.178.1","ak":BAIDU_IPADDR_AK})
print(result.json())
```
I get this result:
```
{'status': 200, 'message': 'APP不存在,AK有误请检查再重试'}
``` |
25,615,609 | I tried `[[UIScreen mainScreen] bounds]` to get the screen size of a resizable iPhone on `Xcode 6` simulator. But it doesn't take into account the new screen width and screen height I assign to it.
Is there a better way to get the screen size? Even if I set the screen size to **320x800** the `[[UIScreen mainScreen] bounds]` returns me `(CGRect) $0 = origin=(x=0, y=0) size=(width=768, height=1024)`
 | 2014/09/02 | [
"https://Stackoverflow.com/questions/25615609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3256150/"
] | Do following
**CGRect Rect=[[UIScreen mainScreen] bounds];**
So it will preserves the bounds in the rect.
try once. | This gets in iOS8 and iOS9. Not sure about 7 haven't tested:
```
var screenWidth: CGFloat {
if UIInterfaceOrientationIsPortrait(screenOrientation) {
return UIScreen.mainScreen().bounds.size.width
} else {
return UIScreen.mainScreen().bounds.size.height
}
}
var screenHeight: CGFloat {
if UIInterfaceOrientationIsPortrait(screenOrientation) {
return UIScreen.mainScreen().bounds.size.height
} else {
return UIScreen.mainScreen().bounds.size.width
}
}
var screenOrientation: UIInterfaceOrientation {
return UIApplication.sharedApplication().statusBarOrientation
}
```
These are included as a standard function in:
<https://github.com/goktugyil/EZSwiftExtensions> |
25,615,609 | I tried `[[UIScreen mainScreen] bounds]` to get the screen size of a resizable iPhone on `Xcode 6` simulator. But it doesn't take into account the new screen width and screen height I assign to it.
Is there a better way to get the screen size? Even if I set the screen size to **320x800** the `[[UIScreen mainScreen] bounds]` returns me `(CGRect) $0 = origin=(x=0, y=0) size=(width=768, height=1024)`
 | 2014/09/02 | [
"https://Stackoverflow.com/questions/25615609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3256150/"
] | Do following
**CGRect Rect=[[UIScreen mainScreen] bounds];**
So it will preserves the bounds in the rect.
try once. | In Swift 4.0, 3.0
```
let screenRect:CGRect = UIScreen.main.bounds
``` |
25,615,609 | I tried `[[UIScreen mainScreen] bounds]` to get the screen size of a resizable iPhone on `Xcode 6` simulator. But it doesn't take into account the new screen width and screen height I assign to it.
Is there a better way to get the screen size? Even if I set the screen size to **320x800** the `[[UIScreen mainScreen] bounds]` returns me `(CGRect) $0 = origin=(x=0, y=0) size=(width=768, height=1024)`
 | 2014/09/02 | [
"https://Stackoverflow.com/questions/25615609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3256150/"
] | In Swift 4.0, 3.0
```
let screenRect:CGRect = UIScreen.main.bounds
``` | This gets in iOS8 and iOS9. Not sure about 7 haven't tested:
```
var screenWidth: CGFloat {
if UIInterfaceOrientationIsPortrait(screenOrientation) {
return UIScreen.mainScreen().bounds.size.width
} else {
return UIScreen.mainScreen().bounds.size.height
}
}
var screenHeight: CGFloat {
if UIInterfaceOrientationIsPortrait(screenOrientation) {
return UIScreen.mainScreen().bounds.size.height
} else {
return UIScreen.mainScreen().bounds.size.width
}
}
var screenOrientation: UIInterfaceOrientation {
return UIApplication.sharedApplication().statusBarOrientation
}
```
These are included as a standard function in:
<https://github.com/goktugyil/EZSwiftExtensions> |
3,214,701 | Determine the conditions on $b\_1$, $b\_2$, $b\_3$, if any, in order to guarantee that the linear system is consistent.
$x + 3y − 2z = b\_1$
$5x − 5y + 4z = b\_2$
$−3x + 11y − 8z = b\_3$.
Consider the system of equations
$x + y + 2z = a $
$x + z = b$
$2x + y + 3z = c$.
Show that in order for this system to be consistent, $a$, $b$, and $c$ must satisfy $c=a+b$.
I need to determine the conditions of the $b$'s. I tried to solve this by using Gauss elimination to convert it into echelon form, but that seems unnecessarily cumbersome to solve this. I was hoping there would be an easier way to do this as well as for the the second part it seems they need the same concept which I don't know. Thank you in advance. | 2019/05/05 | [
"https://math.stackexchange.com/questions/3214701",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/656407/"
] | In general, the condition you are looking for is known (more often than not) as the [Rouché-Capelli theorem](https://en.m.wikipedia.org/wiki/Rouch%C3%A9%E2%80%93Capelli_theorem).
You construct the matrix of the coefficients of the equations $A$; in the first case:
$$ A = \begin{bmatrix}
1 &3& -2\\
5 &-5&4\\
-3&11&-8
\end{bmatrix}.$$
Then, you impose that the rank of $A$ is equal to the rank of the augmented matrix you get by adding the right-hand sife of each equation to each row of $A$; in the first case:
$$ [A|b] = \begin{bmatrix}
1 &3& -2&b\_1\\
5 &-5&4&b\_2\\
-3&11&-8&b\_3
\end{bmatrix}.$$
If $A$ and $[A|b]$ have the same rank, the system has a solution. | Supplementing [this other answer](https://math.stackexchange.com/a/3214716/265466), a different way of characterizing the equal-rank condition is that $(b\_1,b\_2,b\_3)^T$ must lie in the column space of the coefficient matrix $A$ for there to be any solution at all, so what you’re really looking for is a description of this space. Row-reducing $A^T$ (equivalently, *column*-reducing $A$) will generate a “nice” basis, in the sense that the basis vectors have a simple, regular structure. In this case, $$\begin{bmatrix}1&5&-3\\3&-5&11\\-2&4&-8\end{bmatrix} \to \begin{bmatrix}1&0&2\\0&1&-1\\0&0&0\end{bmatrix},$$ so a basis for $C(A)$ consists of $(1,0,2)^T$ and $(0,1,-1)^T$. In other words, every vector in $C(A)$ is of the form $b\_1(1,0,2)^T+b\_2(0,1,-1)^T = (b\_1,b\_2,2b\_1-b\_2)^T$, which gives you the condition $b\_3=2b\_1-b\_2$. Similarly, in the second problem you can compute the basis $\{(1,0,1)^T,(0,1,1)^T\}$, from which $c=a+b$. |
9,064,298 | I have used initialization lists a great deal in my C++ programs but wasn't aware that you could allocate memory within them.
So you can do something (as a contrived example) like this:
```
class Test
{
private:
int* i;
int* j;
int count;
int* k;
public:
Test(void) : i(new int), j(new int[10]), count(10), k(new int[count])
{
}
~Test(void)
{
delete i;
delete [] j;
delete [] k;
}
};
```
Are there any issues in doing memory allocation in this way? Regarding the order of initialization here is it safe to have a parameter initialized by one initialized in the same list? i.e. as I allocate `count` before I use it is it safe to use or is there some special initialization order I could fall foul of? | 2012/01/30 | [
"https://Stackoverflow.com/questions/9064298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/928502/"
] | This code could leak memory in the presence of an initializer that throws an exception.
Note that this could be made to work correctly if the members of `Test` were smart -- rather than raw -- pointers. | There's no problem with your initialization -- they are guaranteed by the standard to be done in order, however, do remember that if any of those allocations fails, the former ones won't be freed.
So the only downside is if you want to keep safe against a failed allocation -- then you'd rather want to initialize them to `nil` and in the constructor wrap the allocation up in a `try` block. That is usually not needed though, unless your application is in the real danger of running out of memory, and needs to recover from that.
Of course that holds true assuming that only a lack of memory can throw an exception -- if you allocate objects that can throw other exceptions, you should be more worried about it. |
9,064,298 | I have used initialization lists a great deal in my C++ programs but wasn't aware that you could allocate memory within them.
So you can do something (as a contrived example) like this:
```
class Test
{
private:
int* i;
int* j;
int count;
int* k;
public:
Test(void) : i(new int), j(new int[10]), count(10), k(new int[count])
{
}
~Test(void)
{
delete i;
delete [] j;
delete [] k;
}
};
```
Are there any issues in doing memory allocation in this way? Regarding the order of initialization here is it safe to have a parameter initialized by one initialized in the same list? i.e. as I allocate `count` before I use it is it safe to use or is there some special initialization order I could fall foul of? | 2012/01/30 | [
"https://Stackoverflow.com/questions/9064298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/928502/"
] | You are allocating memory in your initialiser-list; this is totally fine, but you are then assigning the pointers to that memory to raw pointers.
These raw pointers do not imply any sort of memory ownership or deletion of the pointers that they point to, and as a result, the code contains several memory leaks, does not follow the "Rule of Five", and is generally bad.
A far better way to write `Test` would be:
```
class Test
{
private:
//Assuming you actually want dynamic memory allocation:
std::unique_ptr<int> i;
std::unique_ptr<int[]> j;
int count;
std::unique_ptr<int[]> k;
public:
Test(void) : i(new int), j(new int[10]), count(10), k(new int[count])
{
}
};
``` | Steve Jessop's answer presents pitfalls.
About the order, which I think is what your question addressed:
>
> 12.6.2/4
>
>
> Initialization shall proceed in the following order:
>
>
> [...]
>
>
> * Then, nonstatic data members shall be initialized in the order they were declared in the class definition (again regardless of the order
> of the mem-initializers).
>
>
>
Since in your class, `count` is declared before `k`, you're ok. |
9,064,298 | I have used initialization lists a great deal in my C++ programs but wasn't aware that you could allocate memory within them.
So you can do something (as a contrived example) like this:
```
class Test
{
private:
int* i;
int* j;
int count;
int* k;
public:
Test(void) : i(new int), j(new int[10]), count(10), k(new int[count])
{
}
~Test(void)
{
delete i;
delete [] j;
delete [] k;
}
};
```
Are there any issues in doing memory allocation in this way? Regarding the order of initialization here is it safe to have a parameter initialized by one initialized in the same list? i.e. as I allocate `count` before I use it is it safe to use or is there some special initialization order I could fall foul of? | 2012/01/30 | [
"https://Stackoverflow.com/questions/9064298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/928502/"
] | It's not exception-safe. If the `new` for `j` throws an exception then the destructor for `Test` is not called, and so the memory for `i` is not freed.
The destructor of `i` is called if the initializer for `j` throws, it's just that a raw pointer has no destructor. So you could make it exception-safe by replacing `i` with a suitable smart pointer. In this case, `unique_ptr<int>` for `i` and `unique_ptr<int[]>` for `j` would do.
You can rely on the initializers to be executed in their correct order (the order the members are defined, not necessarily the order in the list). They can safely use data members that have already been initialized, so there's no problem with using `count` in the initializer for `k`. | You are allocating memory in your initialiser-list; this is totally fine, but you are then assigning the pointers to that memory to raw pointers.
These raw pointers do not imply any sort of memory ownership or deletion of the pointers that they point to, and as a result, the code contains several memory leaks, does not follow the "Rule of Five", and is generally bad.
A far better way to write `Test` would be:
```
class Test
{
private:
//Assuming you actually want dynamic memory allocation:
std::unique_ptr<int> i;
std::unique_ptr<int[]> j;
int count;
std::unique_ptr<int[]> k;
public:
Test(void) : i(new int), j(new int[10]), count(10), k(new int[count])
{
}
};
``` |
9,064,298 | I have used initialization lists a great deal in my C++ programs but wasn't aware that you could allocate memory within them.
So you can do something (as a contrived example) like this:
```
class Test
{
private:
int* i;
int* j;
int count;
int* k;
public:
Test(void) : i(new int), j(new int[10]), count(10), k(new int[count])
{
}
~Test(void)
{
delete i;
delete [] j;
delete [] k;
}
};
```
Are there any issues in doing memory allocation in this way? Regarding the order of initialization here is it safe to have a parameter initialized by one initialized in the same list? i.e. as I allocate `count` before I use it is it safe to use or is there some special initialization order I could fall foul of? | 2012/01/30 | [
"https://Stackoverflow.com/questions/9064298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/928502/"
] | It's not exception-safe. If the `new` for `j` throws an exception then the destructor for `Test` is not called, and so the memory for `i` is not freed.
The destructor of `i` is called if the initializer for `j` throws, it's just that a raw pointer has no destructor. So you could make it exception-safe by replacing `i` with a suitable smart pointer. In this case, `unique_ptr<int>` for `i` and `unique_ptr<int[]>` for `j` would do.
You can rely on the initializers to be executed in their correct order (the order the members are defined, not necessarily the order in the list). They can safely use data members that have already been initialized, so there's no problem with using `count` in the initializer for `k`. | This code could leak memory in the presence of an initializer that throws an exception.
Note that this could be made to work correctly if the members of `Test` were smart -- rather than raw -- pointers. |
9,064,298 | I have used initialization lists a great deal in my C++ programs but wasn't aware that you could allocate memory within them.
So you can do something (as a contrived example) like this:
```
class Test
{
private:
int* i;
int* j;
int count;
int* k;
public:
Test(void) : i(new int), j(new int[10]), count(10), k(new int[count])
{
}
~Test(void)
{
delete i;
delete [] j;
delete [] k;
}
};
```
Are there any issues in doing memory allocation in this way? Regarding the order of initialization here is it safe to have a parameter initialized by one initialized in the same list? i.e. as I allocate `count` before I use it is it safe to use or is there some special initialization order I could fall foul of? | 2012/01/30 | [
"https://Stackoverflow.com/questions/9064298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/928502/"
] | It's not exception-safe. If the `new` for `j` throws an exception then the destructor for `Test` is not called, and so the memory for `i` is not freed.
The destructor of `i` is called if the initializer for `j` throws, it's just that a raw pointer has no destructor. So you could make it exception-safe by replacing `i` with a suitable smart pointer. In this case, `unique_ptr<int>` for `i` and `unique_ptr<int[]>` for `j` would do.
You can rely on the initializers to be executed in their correct order (the order the members are defined, not necessarily the order in the list). They can safely use data members that have already been initialized, so there's no problem with using `count` in the initializer for `k`. | There's no specific issue with calling `new` from the initializer list.
However, if you do it for multiple members, it won't be exception-safe, and you risk leaking memory (what if the first `new` call succeeds, but the second throws an exception? Then the first allocation is leaked).
As for relying on the initialization order, that's perfectly safe. Members are initialized in the order in which they're listed in the class declaration. So you can use the value of members initialized early, to initialize "later" members.
Just keep in mind that it's their declaration order inside the class, and *not* their order in the initialization list that determines their initialization order. :) |
9,064,298 | I have used initialization lists a great deal in my C++ programs but wasn't aware that you could allocate memory within them.
So you can do something (as a contrived example) like this:
```
class Test
{
private:
int* i;
int* j;
int count;
int* k;
public:
Test(void) : i(new int), j(new int[10]), count(10), k(new int[count])
{
}
~Test(void)
{
delete i;
delete [] j;
delete [] k;
}
};
```
Are there any issues in doing memory allocation in this way? Regarding the order of initialization here is it safe to have a parameter initialized by one initialized in the same list? i.e. as I allocate `count` before I use it is it safe to use or is there some special initialization order I could fall foul of? | 2012/01/30 | [
"https://Stackoverflow.com/questions/9064298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/928502/"
] | This code could leak memory in the presence of an initializer that throws an exception.
Note that this could be made to work correctly if the members of `Test` were smart -- rather than raw -- pointers. | There's no specific issue with calling `new` from the initializer list.
However, if you do it for multiple members, it won't be exception-safe, and you risk leaking memory (what if the first `new` call succeeds, but the second throws an exception? Then the first allocation is leaked).
As for relying on the initialization order, that's perfectly safe. Members are initialized in the order in which they're listed in the class declaration. So you can use the value of members initialized early, to initialize "later" members.
Just keep in mind that it's their declaration order inside the class, and *not* their order in the initialization list that determines their initialization order. :) |
9,064,298 | I have used initialization lists a great deal in my C++ programs but wasn't aware that you could allocate memory within them.
So you can do something (as a contrived example) like this:
```
class Test
{
private:
int* i;
int* j;
int count;
int* k;
public:
Test(void) : i(new int), j(new int[10]), count(10), k(new int[count])
{
}
~Test(void)
{
delete i;
delete [] j;
delete [] k;
}
};
```
Are there any issues in doing memory allocation in this way? Regarding the order of initialization here is it safe to have a parameter initialized by one initialized in the same list? i.e. as I allocate `count` before I use it is it safe to use or is there some special initialization order I could fall foul of? | 2012/01/30 | [
"https://Stackoverflow.com/questions/9064298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/928502/"
] | It's not exception-safe. If the `new` for `j` throws an exception then the destructor for `Test` is not called, and so the memory for `i` is not freed.
The destructor of `i` is called if the initializer for `j` throws, it's just that a raw pointer has no destructor. So you could make it exception-safe by replacing `i` with a suitable smart pointer. In this case, `unique_ptr<int>` for `i` and `unique_ptr<int[]>` for `j` would do.
You can rely on the initializers to be executed in their correct order (the order the members are defined, not necessarily the order in the list). They can safely use data members that have already been initialized, so there's no problem with using `count` in the initializer for `k`. | There's no problem with your initialization -- they are guaranteed by the standard to be done in order, however, do remember that if any of those allocations fails, the former ones won't be freed.
So the only downside is if you want to keep safe against a failed allocation -- then you'd rather want to initialize them to `nil` and in the constructor wrap the allocation up in a `try` block. That is usually not needed though, unless your application is in the real danger of running out of memory, and needs to recover from that.
Of course that holds true assuming that only a lack of memory can throw an exception -- if you allocate objects that can throw other exceptions, you should be more worried about it. |
9,064,298 | I have used initialization lists a great deal in my C++ programs but wasn't aware that you could allocate memory within them.
So you can do something (as a contrived example) like this:
```
class Test
{
private:
int* i;
int* j;
int count;
int* k;
public:
Test(void) : i(new int), j(new int[10]), count(10), k(new int[count])
{
}
~Test(void)
{
delete i;
delete [] j;
delete [] k;
}
};
```
Are there any issues in doing memory allocation in this way? Regarding the order of initialization here is it safe to have a parameter initialized by one initialized in the same list? i.e. as I allocate `count` before I use it is it safe to use or is there some special initialization order I could fall foul of? | 2012/01/30 | [
"https://Stackoverflow.com/questions/9064298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/928502/"
] | There's no specific issue with calling `new` from the initializer list.
However, if you do it for multiple members, it won't be exception-safe, and you risk leaking memory (what if the first `new` call succeeds, but the second throws an exception? Then the first allocation is leaked).
As for relying on the initialization order, that's perfectly safe. Members are initialized in the order in which they're listed in the class declaration. So you can use the value of members initialized early, to initialize "later" members.
Just keep in mind that it's their declaration order inside the class, and *not* their order in the initialization list that determines their initialization order. :) | Suppose that you have:
```
class Foo
{
public:
T* p1;
T* p2;
Foo()
: p1(new T),
p2(new T)
{
}
};
```
If initializing `p2` fails (either because `new` throws an out of memory exception or because the `T` constructor fails), then `p1` will be leaked. To combat this, C++ allows using `try`/`catch` in initialization lists, but it's usually pretty gross. |
9,064,298 | I have used initialization lists a great deal in my C++ programs but wasn't aware that you could allocate memory within them.
So you can do something (as a contrived example) like this:
```
class Test
{
private:
int* i;
int* j;
int count;
int* k;
public:
Test(void) : i(new int), j(new int[10]), count(10), k(new int[count])
{
}
~Test(void)
{
delete i;
delete [] j;
delete [] k;
}
};
```
Are there any issues in doing memory allocation in this way? Regarding the order of initialization here is it safe to have a parameter initialized by one initialized in the same list? i.e. as I allocate `count` before I use it is it safe to use or is there some special initialization order I could fall foul of? | 2012/01/30 | [
"https://Stackoverflow.com/questions/9064298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/928502/"
] | This code could leak memory in the presence of an initializer that throws an exception.
Note that this could be made to work correctly if the members of `Test` were smart -- rather than raw -- pointers. | Suppose that you have:
```
class Foo
{
public:
T* p1;
T* p2;
Foo()
: p1(new T),
p2(new T)
{
}
};
```
If initializing `p2` fails (either because `new` throws an out of memory exception or because the `T` constructor fails), then `p1` will be leaked. To combat this, C++ allows using `try`/`catch` in initialization lists, but it's usually pretty gross. |
9,064,298 | I have used initialization lists a great deal in my C++ programs but wasn't aware that you could allocate memory within them.
So you can do something (as a contrived example) like this:
```
class Test
{
private:
int* i;
int* j;
int count;
int* k;
public:
Test(void) : i(new int), j(new int[10]), count(10), k(new int[count])
{
}
~Test(void)
{
delete i;
delete [] j;
delete [] k;
}
};
```
Are there any issues in doing memory allocation in this way? Regarding the order of initialization here is it safe to have a parameter initialized by one initialized in the same list? i.e. as I allocate `count` before I use it is it safe to use or is there some special initialization order I could fall foul of? | 2012/01/30 | [
"https://Stackoverflow.com/questions/9064298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/928502/"
] | This code could leak memory in the presence of an initializer that throws an exception.
Note that this could be made to work correctly if the members of `Test` were smart -- rather than raw -- pointers. | You are allocating memory in your initialiser-list; this is totally fine, but you are then assigning the pointers to that memory to raw pointers.
These raw pointers do not imply any sort of memory ownership or deletion of the pointers that they point to, and as a result, the code contains several memory leaks, does not follow the "Rule of Five", and is generally bad.
A far better way to write `Test` would be:
```
class Test
{
private:
//Assuming you actually want dynamic memory allocation:
std::unique_ptr<int> i;
std::unique_ptr<int[]> j;
int count;
std::unique_ptr<int[]> k;
public:
Test(void) : i(new int), j(new int[10]), count(10), k(new int[count])
{
}
};
``` |
59,357,350 | I have list of codes which are separated by comma, the code contains min of 3 and max of 6 characters including numbers. I have written regex for this. How can I expand my regex to work with 1 or more codes as array or list?
Here is my regex for codes
```
const checkCodes = new RegExp('^[A-Z]+[A-Z0-9]{2,5}$');
```
The above regex works well with single codes
```
codes - "BCD"
```
but not for below line, which I am trying to achieve
```
codes - ["BCD", "VOC123",....1 or more codes]
``` | 2019/12/16 | [
"https://Stackoverflow.com/questions/59357350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11671255/"
] | ```js
const checkCodes = new RegExp('^[A-Z]+[A-Z0-9]{2,5}$');
let input = ["CODE1", "NOT.A.CODE", "CODE42"];
console.log(input.filter(str => checkCodes.test(str)))
``` | ```js
const checkCodesMulti = /^([A-Z]+[A-Z0-9]{2,5})(?:\s*,\s*([A-Z]+[A-Z0-9]{2,5}))*$/
let input = "BCD, VOC123, ETC";
let array_of_codes = checkCodesMulti.exec(input).splice(1)
``` |
3,403 | I'm developing a dashboard for a client, and we have some users who fit into multiple roles within the company, ie. a Project Manager and a Department Manager. In this case they function as two separate roles in the company.
Screen real estate is at a premium, so it is getting VERY difficult to squeeze the dashboard sections from both roles into one dashboard for these mutiple-role users.
What is the best way to deal with this type of situation? Should we give them a toggle to view their dashboard as either a PM or a DM? To me that sort of defeats the purpose of a dashboard, an at-a-glance lazy view of all your pertinent information. | 2011/02/08 | [
"https://ux.stackexchange.com/questions/3403",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/3473/"
] | If it is possible in this case I would try to use tab navigation with which these users can change the view between PM or DM view.
So they only have 1 user, with acces to more dashboard styles.
I wouldn't really try to mix them. If there are only two available
 | Figure out what the most important information is for somebody with these two roles and create a dashboard with just that information. On that dashboard, provide links to the dashboard for each specific role. To them these links would function as a drill-down to more detailed information. |
3,403 | I'm developing a dashboard for a client, and we have some users who fit into multiple roles within the company, ie. a Project Manager and a Department Manager. In this case they function as two separate roles in the company.
Screen real estate is at a premium, so it is getting VERY difficult to squeeze the dashboard sections from both roles into one dashboard for these mutiple-role users.
What is the best way to deal with this type of situation? Should we give them a toggle to view their dashboard as either a PM or a DM? To me that sort of defeats the purpose of a dashboard, an at-a-glance lazy view of all your pertinent information. | 2011/02/08 | [
"https://ux.stackexchange.com/questions/3403",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/3473/"
] | The point of a dashboard is to give the user pertinent information at a glance. The user's role is a good starting point however there is much more information you could collect to determine what dashboard elements are important to the user.
For example your users may have two roles however seeing both dashboards may not be appropriate for them. They may be a Project Manager 90% of the time and a Department Manager 10%. So to show dashboard elements for both roles with the same importance on screen would not be ideal.
It would be better to give the user the choice of what dashboard elements they wanted to see. For example you could allow them to select a profile from a predefined list or/and they could cherry pick elements form a central store. This approach allows the user to choose what elements are important to them.
Another approach would be for the application to learn about the users habits and build the dashboard elements based on that information. For example the user goes to the Project Manager pages all the time but has never gone to the Department Manager screens. Therefore the application could tailor the dashboard more to a Project Manager with maybe a 'see more' link off to the other dashboard elements.
A combination of all these would also work, allowing the user to pick and choose as they please but also the application suggesting dashboard elements based on their habits. For example if the user is always visiting the Project Manager pages as above but they have not chosen a Project Manager dashboard element the system could suggest that they add one. | Figure out what the most important information is for somebody with these two roles and create a dashboard with just that information. On that dashboard, provide links to the dashboard for each specific role. To them these links would function as a drill-down to more detailed information. |
3,403 | I'm developing a dashboard for a client, and we have some users who fit into multiple roles within the company, ie. a Project Manager and a Department Manager. In this case they function as two separate roles in the company.
Screen real estate is at a premium, so it is getting VERY difficult to squeeze the dashboard sections from both roles into one dashboard for these mutiple-role users.
What is the best way to deal with this type of situation? Should we give them a toggle to view their dashboard as either a PM or a DM? To me that sort of defeats the purpose of a dashboard, an at-a-glance lazy view of all your pertinent information. | 2011/02/08 | [
"https://ux.stackexchange.com/questions/3403",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/3473/"
] | The point of a dashboard is to give the user pertinent information at a glance. The user's role is a good starting point however there is much more information you could collect to determine what dashboard elements are important to the user.
For example your users may have two roles however seeing both dashboards may not be appropriate for them. They may be a Project Manager 90% of the time and a Department Manager 10%. So to show dashboard elements for both roles with the same importance on screen would not be ideal.
It would be better to give the user the choice of what dashboard elements they wanted to see. For example you could allow them to select a profile from a predefined list or/and they could cherry pick elements form a central store. This approach allows the user to choose what elements are important to them.
Another approach would be for the application to learn about the users habits and build the dashboard elements based on that information. For example the user goes to the Project Manager pages all the time but has never gone to the Department Manager screens. Therefore the application could tailor the dashboard more to a Project Manager with maybe a 'see more' link off to the other dashboard elements.
A combination of all these would also work, allowing the user to pick and choose as they please but also the application suggesting dashboard elements based on their habits. For example if the user is always visiting the Project Manager pages as above but they have not chosen a Project Manager dashboard element the system could suggest that they add one. | If it is possible in this case I would try to use tab navigation with which these users can change the view between PM or DM view.
So they only have 1 user, with acces to more dashboard styles.
I wouldn't really try to mix them. If there are only two available
 |
15,838,495 | I've implemented a `OnPreferenceChangeListener` on two preference object in my preference page ( extends `PreferenceActivity`)
But ever since the preference value isn't updated upon change,
I even tried using :
```
SharedPreferences sharedPreferences = getSharedPreferences("myCustomSharedPrefs",
Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(preference.getKey(), Integer.parseInt(newValue.toString()));
editor.commit();
```
Where `preference` is the changed preference and `newValue` is the new value...
What am I missing ?
Thanks | 2013/04/05 | [
"https://Stackoverflow.com/questions/15838495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1405268/"
] | You need to return true to get the value updated, see the [Android documentation](http://developer.android.com/reference/android/preference/Preference.OnPreferenceChangeListener.html). | Can you see if preference.getKey() is giving the correct name? Can you print in your console and see. Code looks clean to me. May be the name is different than what is expected.
Also make sure that the value is also having the correct value. |
61,456,647 | I am using the code below:
```
$global:accountArray = New-Object -TypeName "System.Collections.ArrayList"
$global:accountArray.Add("0001")
$global:accountArray.Add("0002")
$global:accountArray.Add("0003")
$global:accountArray.Add("0004")
$global:accountArray.Add("0005")
Function Remove-Numbers
{
// This loop only iterates one time
foreach ($n in $global:accountArray) {
$global:accountArray.Remove($n)
}
}
Remove-Numbers
```
I have globally declared `accountArray` variable but when I try to modify that variable in `Function` it only iterates once and loop ends(i.e. it only removes one element), what I am doing wrong? | 2020/04/27 | [
"https://Stackoverflow.com/questions/61456647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6818685/"
] | You cannot change a collection like ArrayList while iterating its items like that.
If all you want to do is empty the list, use `$global:accountArray.Clear()`
If you want to use a loop, do that by using the element index and go from bottom to top:
```
Function Remove-Numbers {
# use a loop to remove the items. go from last to first
for ($i = $global:accountArray.Count -1; $i -ge 0; $i--) {
$global:accountArray.RemoveAt($i)
}
}
```
Or use the `Remove` method slightly different by letting `$n` not being a member of the list itself, but merely the value it stores:
```
Function Remove-Numbers {
# use a loop to remove the items. Iterate using the value of the item, not the item itself.
foreach ($n in $global:accountArray.ToArray()) {
$global:accountArray.Remove($n)
}
}
```
P.S. the comment character in PowerShell is `#`, not `//` | You can't modify a list you are iterating through. The collection is modified so it's not the same one it started with. You can call ToArray() on the list to fix this.
```bsh
Function Remove-Numbers
{
foreach ($n in $global:accountArray.ToArray()) {
$global:accountArray.Remove($n)
}
}
``` |
65,283,926 | I'm working on ejs-grid and I want to toggle(Expand/Collapse) a **child grid** when I click on a row in the grid.
I was able to get the row click functionality working using (rowSelected) attribute but I don't really know how to get the **current state** of a child grid(collapsed or expanded).
My Current Code
```html
toggleChildGrid(event){
const rowIndex = event.rowIndex;
const isCollapsed = true;
if(isCollapsed){
this.grid.detailRowModule.expand(rowIndex);
}
else{
this.grid.detailRowModule.collapse(rowIndex)
}
}
```
I just made the **isCollapsed** variable true but I will like that to be derived dynamically based on the state of the child grid. | 2020/12/14 | [
"https://Stackoverflow.com/questions/65283926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14821156/"
] | Looks like you need to track answers for each monster, and if the are incorrect, do not allow the user to click the monster again. To do this with your current architecture, below I setup an array of answers initially set to null, meaning no answer has been given. Within the click event, we will set the monsterAnswer to be true or false based on the user's response. Hope this helps and welcome!
```js
var monsters = ["slug", "zombie", "wasp"];
var randomForMon = Math.floor(Math.random() * monsters.length);
var randMonster = monsters[randomForMon];
var user_answer = getNumber("answer_input");
var monstersAnswers = [null, null, null];
//when monster clicked, show fighting symbol and change screen
onEvent(randMonster, "click", function() {
const monsterAnswer = monstersAnswers[randomForMon];
if (monsterAnswer === false) {
// don't do anything
return;
}
hideElement("clickMonster_label");
showSymbol();
setTimeout(function() {
setScreen("equation_screen");
}, 1300);
newEquation();
var userAnswer = /* something */
monstersAnswers[randomForMon] = correctAnswer === userAnswer;
});
``` | Maybe you can just return in the click listener when the "answer\_input" !== "user\_answer". |
47,431,649 | I am a deep learning and Tensorflow beginner and I am trying to implement the algorithm in this [paper](https://arxiv.org/abs/1611.06345) using Tensorflow. This paper uses Matconvnet+Matlab to implement it, and I am curious if Tensorflow has the equivalent functions to achieve the same thing. The paper said:
>
> The network parameters were initialized using the Xavier method [14]. We used the regression loss across four wavelet subbands under l2 penalty and the proposed network was trained by using the stochastic gradient descent (SGD). The regularization parameter (λ) was 0.0001 and the momentum was 0.9. The learning rate was set from 10−1 to 10−4 which was reduced in log scale at each epoch.
>
>
>
This paper uses wavelet transform (WT) and residual learning method (where the residual image = WT(HR) - WT(HR'), and the HR' are used for training). Xavier method suggests to initialize the variables normal distribution with
```
stddev=sqrt(2/(filter_size*filter_size*num_filters)
```
**Q1. How should I initialize the variables? Is the code below correct?**
```
weights = tf.Variable(tf.random_normal[img_size, img_size, 1, num_filters], stddev=stddev)
```
---
This paper does not explain how to construct the loss function in details . I am unable to find the equivalent Tensorflow function to set the learning rate in log scale (only `exponential_decay`). I understand `MomentumOptimizer` is equivalent to Stochastic Gradient Descent with momentum.
**Q2: Is it possible to set the learning rate in log scale?**
**Q3: How to create the loss function described above?**
I followed this [website](http://www.ritchieng.com/machine-learning/deep-learning/tensorflow/regularization/) to write the code below. Assume model() function returns the network mentioned in this paper and lamda=0.0001,
```
inputs = tf.placeholder(tf.float32, shape=[None, patch_size, patch_size, num_channels])
labels = tf.placeholder(tf.float32, [None, patch_size, patch_size, num_channels])
# get the model output and weights for each conv
pred, weights = model()
# define loss function
loss = tf.nn.softmax_cross_entropy_with_logits_v2(labels=labels, logits=pred)
for weight in weights:
regularizers += tf.nn.l2_loss(weight)
loss = tf.reduce_mean(loss + 0.0001 * regularizers)
learning_rate = tf.train.exponential_decay(???) # Not sure if we can have custom learning rate for log scale
optimizer = tf.train.MomentumOptimizer(learning_rate, momentum).minimize(loss, global_step)
```
NOTE: As I am a deep learning/Tensorflow beginner, I copy-paste code here and there so please feel free to correct it if you can ;) | 2017/11/22 | [
"https://Stackoverflow.com/questions/47431649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2910704/"
] | Other answers are very detailed and helpful. Here is a code example that uses placeholder to decay learning rate at log scale. HTH.
```
import tensorflow as tf
import numpy as np
# data simulation
N = 10000
D = 10
x = np.random.rand(N, D)
w = np.random.rand(D,1)
y = np.dot(x, w)
print y.shape
#modeling
batch_size = 100
tni = tf.truncated_normal_initializer()
X = tf.placeholder(tf.float32, [batch_size, D])
Y = tf.placeholder(tf.float32, [batch_size,1])
W = tf.get_variable("w", shape=[D,1], initializer=tni)
B = tf.zeros([1])
lr = tf.placeholder(tf.float32)
pred = tf.add(tf.matmul(X,W), B)
print pred.shape
mse = tf.reduce_sum(tf.losses.mean_squared_error(Y, pred))
opt = tf.train.MomentumOptimizer(lr, 0.9)
train_op = opt.minimize(mse)
learning_rate = 0.0001
do_train = True
acc_err = 0.0
sess = tf.Session()
sess.run(tf.global_variables_initializer())
while do_train:
for i in range (100000):
if i > 0 and i % N == 0:
# epoch done, decrease learning rate by 2
learning_rate /= 2
print "Epoch completed. LR =", learning_rate
idx = i/batch_size + i%batch_size
f = {X:x[idx:idx+batch_size,:], Y:y[idx:idx+batch_size,:], lr: learning_rate}
_, err = sess.run([train_op, mse], feed_dict = f)
acc_err += err
if i%5000 == 0:
print "Average error = {}".format(acc_err/5000)
acc_err = 0.0
``` | Q1. How should I initialize the variables? Is the code below correct?
=====================================================================
That's correct (although missing an opening parentheses). You could also look into `tf.get_variable` if the variables are going to be reused.
Q2: Is it possible to set the learning rate in log scale?
=========================================================
Exponential decay decreases the learning rate at every step. I think what you want is [`tf.train.piecewise_constant`](https://www.tensorflow.org/api_docs/python/tf/train/piecewise_constant), and set boundaries at each epoch.
**EDIT: Look at the other answer, use the `staircase=True` argument!**
Q3: How to create the loss function described above?
====================================================
Your loss function looks correct. |
47,431,649 | I am a deep learning and Tensorflow beginner and I am trying to implement the algorithm in this [paper](https://arxiv.org/abs/1611.06345) using Tensorflow. This paper uses Matconvnet+Matlab to implement it, and I am curious if Tensorflow has the equivalent functions to achieve the same thing. The paper said:
>
> The network parameters were initialized using the Xavier method [14]. We used the regression loss across four wavelet subbands under l2 penalty and the proposed network was trained by using the stochastic gradient descent (SGD). The regularization parameter (λ) was 0.0001 and the momentum was 0.9. The learning rate was set from 10−1 to 10−4 which was reduced in log scale at each epoch.
>
>
>
This paper uses wavelet transform (WT) and residual learning method (where the residual image = WT(HR) - WT(HR'), and the HR' are used for training). Xavier method suggests to initialize the variables normal distribution with
```
stddev=sqrt(2/(filter_size*filter_size*num_filters)
```
**Q1. How should I initialize the variables? Is the code below correct?**
```
weights = tf.Variable(tf.random_normal[img_size, img_size, 1, num_filters], stddev=stddev)
```
---
This paper does not explain how to construct the loss function in details . I am unable to find the equivalent Tensorflow function to set the learning rate in log scale (only `exponential_decay`). I understand `MomentumOptimizer` is equivalent to Stochastic Gradient Descent with momentum.
**Q2: Is it possible to set the learning rate in log scale?**
**Q3: How to create the loss function described above?**
I followed this [website](http://www.ritchieng.com/machine-learning/deep-learning/tensorflow/regularization/) to write the code below. Assume model() function returns the network mentioned in this paper and lamda=0.0001,
```
inputs = tf.placeholder(tf.float32, shape=[None, patch_size, patch_size, num_channels])
labels = tf.placeholder(tf.float32, [None, patch_size, patch_size, num_channels])
# get the model output and weights for each conv
pred, weights = model()
# define loss function
loss = tf.nn.softmax_cross_entropy_with_logits_v2(labels=labels, logits=pred)
for weight in weights:
regularizers += tf.nn.l2_loss(weight)
loss = tf.reduce_mean(loss + 0.0001 * regularizers)
learning_rate = tf.train.exponential_decay(???) # Not sure if we can have custom learning rate for log scale
optimizer = tf.train.MomentumOptimizer(learning_rate, momentum).minimize(loss, global_step)
```
NOTE: As I am a deep learning/Tensorflow beginner, I copy-paste code here and there so please feel free to correct it if you can ;) | 2017/11/22 | [
"https://Stackoverflow.com/questions/47431649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2910704/"
] | Other answers are very detailed and helpful. Here is a code example that uses placeholder to decay learning rate at log scale. HTH.
```
import tensorflow as tf
import numpy as np
# data simulation
N = 10000
D = 10
x = np.random.rand(N, D)
w = np.random.rand(D,1)
y = np.dot(x, w)
print y.shape
#modeling
batch_size = 100
tni = tf.truncated_normal_initializer()
X = tf.placeholder(tf.float32, [batch_size, D])
Y = tf.placeholder(tf.float32, [batch_size,1])
W = tf.get_variable("w", shape=[D,1], initializer=tni)
B = tf.zeros([1])
lr = tf.placeholder(tf.float32)
pred = tf.add(tf.matmul(X,W), B)
print pred.shape
mse = tf.reduce_sum(tf.losses.mean_squared_error(Y, pred))
opt = tf.train.MomentumOptimizer(lr, 0.9)
train_op = opt.minimize(mse)
learning_rate = 0.0001
do_train = True
acc_err = 0.0
sess = tf.Session()
sess.run(tf.global_variables_initializer())
while do_train:
for i in range (100000):
if i > 0 and i % N == 0:
# epoch done, decrease learning rate by 2
learning_rate /= 2
print "Epoch completed. LR =", learning_rate
idx = i/batch_size + i%batch_size
f = {X:x[idx:idx+batch_size,:], Y:y[idx:idx+batch_size,:], lr: learning_rate}
_, err = sess.run([train_op, mse], feed_dict = f)
acc_err += err
if i%5000 == 0:
print "Average error = {}".format(acc_err/5000)
acc_err = 0.0
``` | Q1. How should I initialize the variables? Is the code below correct?
=====================================================================
Use tf.get\_variable or switch to slim (it does the initialization automatically for you). [example](https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/slim)
Q2: Is it possible to set the learning rate in log scale?
=========================================================
You can but do you need it? This is not the first thing that you need to solve in this network. Please check #3
However, just for reference, use following notation.
>
> learning\_rate\_node = tf.train.exponential\_decay(learning\_rate=0.001, decay\_steps=10000, decay\_rate=0.98, staircase=True)
>
>
> optimizer = tf.train.AdamOptimizer(learning\_rate=learning\_rate\_node).minimize(loss)
>
>
>
Q3: How to create the loss function described above?
====================================================
At first, you have not written "pred" to "image" conversion to this message(Based on the paper you need to apply subtraction and IDWT to obtain final image).
There is one problem here, logits have to be calculated based on your label data. i.e. if you will use marked data as "Y : Label", you need to write
>
> pred = model()
>
>
> pred = tf.matmul(pred, weights) + biases
>
>
> logits = tf.nn.softmax(pred)
>
>
> loss = tf.reduce\_mean(tf.abs(logits - labels))
>
>
>
This will give you the output of Y : Label to be used
If your dataset's labeled images are denoised ones, in this case you need to follow this one:
>
> pred = model()
>
>
> pred = tf.matmul(image, weights) + biases
>
>
> logits = tf.nn.softmax(pred)
>
>
> image = apply\_IDWT("X : input", logits) # this will apply IDWT(x\_label - y\_label)
>
>
> loss = tf.reduce\_mean(tf.abs(image - labels))
>
>
>
Logits are the output of your network. You will use this one as result to calculate the rest. Instead of matmul, you can add a conv2d layer in here without a batch normalization and an activation function and set output feature count as 4. Example:
>
> pred = model()
>
>
> pred = slim.conv2d(pred, 4, [3, 3], activation\_fn=None, padding='SAME', scope='output')
>
>
> logits = tf.nn.softmax(pred)
>
>
> image = apply\_IDWT("X : input", logits) # this will apply IDWT(x\_label - y\_label)
>
>
> loss = tf.reduce\_mean(tf.abs(logits - labels))
>
>
>
This loss function will give you basic training capabilities. However, this is L1 distance and it may suffer from some issues ([check](http://www.chioka.in/differences-between-l1-and-l2-as-loss-function-and-regularization/)). Think following situation
Let's say you have following array as output [10, 10, 10, 0, 0] and you try to achieve [10, 10, 10, 10, 10]. In this case, your loss is 20 (10 + 10). However, you have 3/5 success. Also, it may indicate some overfit.
For same case, think following output [6, 6, 6, 6, 6]. It still has loss of 20 (4 + 4 + 4 + 4 + 4). However, whenever you apply threshold of 5, you can achieve 5/5 success. Hence, this is the case that we want.
If you use L2 loss, for the first case, you will have 10^2 + 10^2 = 200 as loss output. For the second case, you will get 4^2 \* 5 = 80.
Hence, optimizer will try to run away from #1 as quick as possible to achieve global success rather than perfect success of some outputs and complete failure of the others. You can apply loss function like this for that.
>
> tf.reduce\_mean(tf.nn.l2\_loss(logits - image))
>
>
>
Alternatively, you can check for cross entropy loss function. (it does apply softmax internally, do not apply softmax twice)
>
> tf.reduce\_mean(tf.nn.softmax\_cross\_entropy\_with\_logits(pred, image))
>
>
> |
35,444,952 | I'm currently doing my first steps with SAP HANA Vora on Cloudera Express 5.5.0.
The Vora server is up and running and I would now like to use the Vora spark shell but this is what I get:
```
sh start-spark-shell.sh
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/spark/launcher/Main
Caused by: java.lang.ClassNotFoundException: org.apache.spark.launcher.Main
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
Could not find the main class: org.apache.spark.launcher.Main. Program will exit.
```
This is how my environment looks like:
```
export LD_LIBRARY_PATH=/opt/cloudera/parcels/CDH/lib/hadoop/lib/native
export JAVA_HOME=/usr/java/default
export HADOOP_PARCEL_PATH=/opt/cloudera/parcels/CDH
export HADOOP_CONF_DIR=/etc/hadoop/conf
export SPARK_HOME=/usr/lib/spark
export SPARK_CONF_DIR=$SPARK_HOME/conf
export PATH=$PATH:$SPARK_HOME/bin
SPARK_DIST_CLASSPATH=$SPARK_HOME/lib/spark-assembly.jar
SPARK_DIST_CLASSPATH=$SPARK_DIST_CLASSPATH:$HADOOP_PARCEL_PATH/lib/hadoop/lib/*
SPARK_DIST_CLASSPATH=$SPARK_DIST_CLASSPATH:$HADOOP_PARCEL_PATH/lib/hadoop/*
SPARK_DIST_CLASSPATH=$SPARK_DIST_CLASSPATH:$HADOOP_PARCEL_PATH/lib/hadoop-hdfs/lib/*
SPARK_DIST_CLASSPATH=$SPARK_DIST_CLASSPATH:$HADOOP_PARCEL_PATH/lib/hadoop-hdfs/*
SPARK_DIST_CLASSPATH=$SPARK_DIST_CLASSPATH:$HADOOP_PARCEL_PATH/lib/hadoop-mapreduce/lib/*
SPARK_DIST_CLASSPATH=$SPARK_DIST_CLASSPATH:$HADOOP_PARCEL_PATH/lib/hadoop-mapreduce/*
SPARK_DIST_CLASSPATH=$SPARK_DIST_CLASSPATH:$HADOOP_PARCEL_PATH/lib/hadoop-yarn/lib/*
SPARK_DIST_CLASSPATH=$SPARK_DIST_CLASSPATH:$HADOOP_PARCEL_PATH/lib/hadoop-yarn/*
SPARK_DIST_CLASSPATH=$SPARK_DIST_CLASSPATH:$HADOOP_PARCEL_PATH/lib/hive/lib/*
SPARK_DIST_CLASSPATH=$SPARK_DIST_CLASSPATH:$HADOOP_PARCEL_PATH/lib/flume-ng/lib/*
SPARK_DIST_CLASSPATH=$SPARK_DIST_CLASSPATH:$HADOOP_PARCEL_PATH/lib/parquet/lib/*
SPARK_DIST_CLASSPATH=$SPARK_DIST_CLASSPATH:$HADOOP_PARCEL_PATH/lib/avro/lib/*
export SPARK_DIST_CLASSPATH
``` | 2016/02/16 | [
"https://Stackoverflow.com/questions/35444952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1867854/"
] | The cron job has been running for a while now without any issues, and it is keeping the space usage under control.
I have reduced the parameter to 15 days.
My crontab looks like this:
```
# clean up old files from working directory
0 20 * * * find /<path_to>/bamboo-home/xml-data/build-dir/ -depth -not -path *repositories-cache* -atime +15 -delete
# clean up old backups every Sunday
0 21 * * 0 find /<path_to>/bamboo-home/backups -type f -mtime +28 -delete
# remove any old logs from install directory after 15 days
0 22 * * * find /<path_to>/bamboo/logs/ -type f -mtime +15 -delete
# quick and dirty truncate catalina.out to stop it growing too large (or better still use logrotate)
0 23 * * * cat /dev/null > /<path_to>/bamboo/logs/catalina.out
```
I hope this is useful for others trying to tame bamboo's diskspace usage.
The first job is the important one, the last three are just housekeeping.
N.B. logrotate is not used on catalina.out due to unique circumstances in my companies outsourced linux environment. I would generally recommend logrotate if possible rather than my quick and dirty truncate method - see answer by Jon V. | While the cron idea works well - the thing that I've also done in the past with Bamboo is to "Clean working directory after each build" options. Basically, for any given job, there's a config option that will clean up the appropriate `build-dir/<build_plan_job>` directory for a given plan/job:
Actions -> Configure Plan -> click the Job -> Miscelaneous Tab -> first checkbox
While that makes sure that future build scratch areas are cleaned up, it does *not* help for already existing and/or old builds. Given the normal git style workflow where you have lots of branches (and each branch creates a specific job ID for it (like `PLAN-JOB_WITH_BRANCH_NUMBER-BUILD_NUMBER` or similar) that gets old/large fast. I just did a quick check, and we're now cleaning up the build areas for most builds (the large ones at least), but we have over 100Gig of build cruft from branches that have been merged loooong ago.
Thanks for the cron example, though, that should work OK for the future.
Unrelated: the more I use Bamboo, the more I love/hate it.
**EDIT**: as a general comment, I'd try *really hard* to work with an SA to get a logrotate rule set up/implemented for the `catalina.out` - overwriting with `/dev/null` seems like a really bad idea, unless you're already slurping them up with something like ELK or Splunk.
My `/etc/logrotate.d/bamboo_catalina_out` looks like (using your paths):
```
/<path_to>/bamboo/logs/catalina.out {
create 0660 bamboo bamboo
compress
copytruncate
missingok
rotate 10
size 100M
}
```
Finally - is there a reason why you have both the third and fourth cron scripts? |
171,748 | I am trying to plot the solid formed by the intersection of the surface between
```
p1 = Plot3D[1 + x^2 - y^2, {x, -1.2, 1.2}, {y, -1.2, 1.2}]
```
and
```
p2 = Plot3D[3 Log[1 + x^2], {x, -1.4, 1.4}, {y, -1, 1}]
```
I am also trying to get the volume of said solid. I've tried the solution given in [How to plot and find the volume of a solid?](https://mathematica.stackexchange.com/q/39161/57777), but I am only recently starting in this language and can't manage to adapt it to work with my functions. Any help will be apreciated. Thank you.
Here is the code for the two surfaces and its intersection.
[](https://i.stack.imgur.com/JiLGw.png) | 2018/04/23 | [
"https://mathematica.stackexchange.com/questions/171748",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/57777/"
] | Clearly the maximum x extent will be when y==0. Use `Reduce` to find the x extent.
```
Reduce[1+x^2-0^2==3 Log[1+x^2],x]
```
Use `Reduce` to find the y extent for a given x.
```
Reduce[1+x^2-y^2==3 Log[1+x^2],y]
```
Then `Integrate` over the y extent for each x to find the volume.
```
NIntegrate[1+x^2-y^2-3 Log[1+x^2],
{x,-Sqrt[E^(-ProductLog[-1/3])-1],Sqrt[E^(-ProductLog[-1/3])-1]},
{y,-Sqrt[1+x^2-3*Log[1+x^2]],Sqrt[1+x^2-3*Log[1+x^2]]}]
```
In exactly the same way `Plot3D` the volume between them.
```
Plot3D[{1+x^2-y^2,3 Log[1+x^2]},
{x,-Sqrt[E^(-ProductLog[-1/3])-1],Sqrt[E^(-ProductLog[-1/3])-1]},
{y,-Sqrt[1+x^2-3*Log[1+x^2]],Sqrt[1+x^2-3*Log[1+x^2]]}]
```
Check all this very carefully to make certain no mistakes have been made. | per comment:
```
r = ImplicitRegion[
3 Log[1 + x^2] < z <
1 + x^2 - y^2, {{x, -1.4, 1.4},y,z}];
Volume[r]
```
>
> 1.2471664022353517
>
>
>
`DiscretizRegion` and `RegionPlot` have a hard time with it though.
```
DiscretizeRegion[r, MaxCellMeasure -> .0001, MeshQualityGoal -> 1]
```
[](https://i.stack.imgur.com/TiNXW.png)
This does not work at all in v10.1 by the way.
Edit. Another way to get the figure:
```
Plot3D[{1 + x^2 - y^2, 3 Log[1 + x^2]}, {x, -1, 1}, {y, -1, 1},
RegionFunction -> Function[{x, y}, 3 Log[1 + x^2] <= 1 + x^2 - y^2]]
```
[](https://i.stack.imgur.com/xmVqz.png)
and another volume:
```
NIntegrate[
Boole[3 Log[1 + x^2] <= z <= 1 + x^2 - y^2], {x, -1, 1}, {y, -1,
1}, {z, -1, 3}]
```
>
> 1.247166402235352
>
>
> |
171,748 | I am trying to plot the solid formed by the intersection of the surface between
```
p1 = Plot3D[1 + x^2 - y^2, {x, -1.2, 1.2}, {y, -1.2, 1.2}]
```
and
```
p2 = Plot3D[3 Log[1 + x^2], {x, -1.4, 1.4}, {y, -1, 1}]
```
I am also trying to get the volume of said solid. I've tried the solution given in [How to plot and find the volume of a solid?](https://mathematica.stackexchange.com/q/39161/57777), but I am only recently starting in this language and can't manage to adapt it to work with my functions. Any help will be apreciated. Thank you.
Here is the code for the two surfaces and its intersection.
[](https://i.stack.imgur.com/JiLGw.png) | 2018/04/23 | [
"https://mathematica.stackexchange.com/questions/171748",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/57777/"
] | Clearly the maximum x extent will be when y==0. Use `Reduce` to find the x extent.
```
Reduce[1+x^2-0^2==3 Log[1+x^2],x]
```
Use `Reduce` to find the y extent for a given x.
```
Reduce[1+x^2-y^2==3 Log[1+x^2],y]
```
Then `Integrate` over the y extent for each x to find the volume.
```
NIntegrate[1+x^2-y^2-3 Log[1+x^2],
{x,-Sqrt[E^(-ProductLog[-1/3])-1],Sqrt[E^(-ProductLog[-1/3])-1]},
{y,-Sqrt[1+x^2-3*Log[1+x^2]],Sqrt[1+x^2-3*Log[1+x^2]]}]
```
In exactly the same way `Plot3D` the volume between them.
```
Plot3D[{1+x^2-y^2,3 Log[1+x^2]},
{x,-Sqrt[E^(-ProductLog[-1/3])-1],Sqrt[E^(-ProductLog[-1/3])-1]},
{y,-Sqrt[1+x^2-3*Log[1+x^2]],Sqrt[1+x^2-3*Log[1+x^2]]}]
```
Check all this very carefully to make certain no mistakes have been made. | A different way to discretize is to work with each surface separately and take their intersection.
```
ToBMR[g_Graphics3D] := With[{s = DiscretizeGraphics[g]},
BoundaryMeshRegion[MeshCoordinates[s], MeshCells[s, 2]]
];
p1 = Plot3D[1 + x^2 - y^2, {x, -1.5, 1.5}, {y, -1.5, 1.5},
Filling -> Bottom, PlotRange -> {-2, Automatic}, PlotPoints -> 50];
p2 = Plot3D[3 Log[1 + x^2], {x, -1.5, 1.5}, {y, -1.5, 1.5},
PlotStyle -> Red, Filling -> Top, PlotPoints -> 50];
m1 = ToBMR[p1];
m2 = ToBMR[p2];
saddle = RegionIntersection[m1, m2]
```
[](https://i.stack.imgur.com/JUjd3.png)
```
Volume[saddle]
```
>
>
> ```
> 1.24449
>
> ```
>
>
---
Here's the same calculation with `PlotPoints -> 200`:
```
Volume[saddle]
```
>
>
> ```
> 1.24697
>
> ```
>
> |
30,044,954 | My develop H/W environment is Raspberry Pi2 & VX-1000 camera
My develop S/W environment is Arch linux & c++ & opencv
I could stream on webpage by using mjpg-streamer
with this command `mjpg_streamer -i "./input_uvc.so -d /dev/video0 -n -f 30 -r 320x240" -o "./output_http.so -n -w ./www"`
This run is good. (turns on camera (means turns on led on camera) )
But when I execute the program made by opencv code, it doesn't turn on camera (not turn on led) and the function `cvCaptureFromCAM()` returns `NULL`.
My source code is
```
#include <iostream>
#include <time.h>
#include <opencv/cv.h>
#include <opencv/highgui.h>
using namespace cv;
using namespace std;
int main(int argc,char** argv)
{
char c;
IplImage* frame;
CvCapture* capture;
capture = cvCaptureFromCAM(-1);
if(capture == NULL)
cout << "Strange!!" << endl;
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH , 320);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT , 240);
bool bLoop = true;
cout << "Start streaming" << endl;
while (bLoop){
cvGrabFrame(capture); // Get a frame from cam
frame = cvRetrieveFrame(capture, 0); // get a frame from capture
cvSaveImage("save.jpg", frame);
cvWaitKey(33); // wait key input for 33ms
}
cvReleaseCapture(&capture);
cvDestroyAllWindows();
return 0;
}
``` | 2015/05/05 | [
"https://Stackoverflow.com/questions/30044954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4864919/"
] | wrap this util method into a Utility class build the jar and put it in classpath of your iReport and whenever you are compiling this jrxml | Using Java 8 you can do this in single line:
```
System.out.println(LocalDate.now().minusMonths(6).format(DateTimeFormatter.ofPattern("yyyy/MM/dd")));
```
If you cannot use Java 8 consider using [Joda Time](http://www.joda.org/joda-time/) library. |
30,044,954 | My develop H/W environment is Raspberry Pi2 & VX-1000 camera
My develop S/W environment is Arch linux & c++ & opencv
I could stream on webpage by using mjpg-streamer
with this command `mjpg_streamer -i "./input_uvc.so -d /dev/video0 -n -f 30 -r 320x240" -o "./output_http.so -n -w ./www"`
This run is good. (turns on camera (means turns on led on camera) )
But when I execute the program made by opencv code, it doesn't turn on camera (not turn on led) and the function `cvCaptureFromCAM()` returns `NULL`.
My source code is
```
#include <iostream>
#include <time.h>
#include <opencv/cv.h>
#include <opencv/highgui.h>
using namespace cv;
using namespace std;
int main(int argc,char** argv)
{
char c;
IplImage* frame;
CvCapture* capture;
capture = cvCaptureFromCAM(-1);
if(capture == NULL)
cout << "Strange!!" << endl;
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH , 320);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT , 240);
bool bLoop = true;
cout << "Start streaming" << endl;
while (bLoop){
cvGrabFrame(capture); // Get a frame from cam
frame = cvRetrieveFrame(capture, 0); // get a frame from capture
cvSaveImage("save.jpg", frame);
cvWaitKey(33); // wait key input for 33ms
}
cvReleaseCapture(&capture);
cvDestroyAllWindows();
return 0;
}
``` | 2015/05/05 | [
"https://Stackoverflow.com/questions/30044954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4864919/"
] | wrap this util method into a Utility class build the jar and put it in classpath of your iReport and whenever you are compiling this jrxml | Use Joda library because of various shortcomings of the `Date` and `Calendar` classes
```
new DateTime().minusMonths(6).toDate();
```
In **Java 8** update following also will be good.
```
LocalDateTime.from(referenceDate.toInstant()).minusMonths(6);
``` |
30,044,954 | My develop H/W environment is Raspberry Pi2 & VX-1000 camera
My develop S/W environment is Arch linux & c++ & opencv
I could stream on webpage by using mjpg-streamer
with this command `mjpg_streamer -i "./input_uvc.so -d /dev/video0 -n -f 30 -r 320x240" -o "./output_http.so -n -w ./www"`
This run is good. (turns on camera (means turns on led on camera) )
But when I execute the program made by opencv code, it doesn't turn on camera (not turn on led) and the function `cvCaptureFromCAM()` returns `NULL`.
My source code is
```
#include <iostream>
#include <time.h>
#include <opencv/cv.h>
#include <opencv/highgui.h>
using namespace cv;
using namespace std;
int main(int argc,char** argv)
{
char c;
IplImage* frame;
CvCapture* capture;
capture = cvCaptureFromCAM(-1);
if(capture == NULL)
cout << "Strange!!" << endl;
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH , 320);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT , 240);
bool bLoop = true;
cout << "Start streaming" << endl;
while (bLoop){
cvGrabFrame(capture); // Get a frame from cam
frame = cvRetrieveFrame(capture, 0); // get a frame from capture
cvSaveImage("save.jpg", frame);
cvWaitKey(33); // wait key input for 33ms
}
cvReleaseCapture(&capture);
cvDestroyAllWindows();
return 0;
}
``` | 2015/05/05 | [
"https://Stackoverflow.com/questions/30044954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4864919/"
] | wrap this util method into a Utility class build the jar and put it in classpath of your iReport and whenever you are compiling this jrxml | To calculate the previous date just do something like below where **total number of previous days are multiplied with `24 * 60 * 60 * 1000`**
```
new Date(System.currentTimeMillis() - 7 * 24 * 60 * 60 * 1000);
```
Where, *7 days are subtracted from the current date.*
Calculate the number of days in service side & pass it as a parameter to above line of code to get the required previous date.
Hope this helps. |
30,044,954 | My develop H/W environment is Raspberry Pi2 & VX-1000 camera
My develop S/W environment is Arch linux & c++ & opencv
I could stream on webpage by using mjpg-streamer
with this command `mjpg_streamer -i "./input_uvc.so -d /dev/video0 -n -f 30 -r 320x240" -o "./output_http.so -n -w ./www"`
This run is good. (turns on camera (means turns on led on camera) )
But when I execute the program made by opencv code, it doesn't turn on camera (not turn on led) and the function `cvCaptureFromCAM()` returns `NULL`.
My source code is
```
#include <iostream>
#include <time.h>
#include <opencv/cv.h>
#include <opencv/highgui.h>
using namespace cv;
using namespace std;
int main(int argc,char** argv)
{
char c;
IplImage* frame;
CvCapture* capture;
capture = cvCaptureFromCAM(-1);
if(capture == NULL)
cout << "Strange!!" << endl;
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH , 320);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT , 240);
bool bLoop = true;
cout << "Start streaming" << endl;
while (bLoop){
cvGrabFrame(capture); // Get a frame from cam
frame = cvRetrieveFrame(capture, 0); // get a frame from capture
cvSaveImage("save.jpg", frame);
cvWaitKey(33); // wait key input for 33ms
}
cvReleaseCapture(&capture);
cvDestroyAllWindows();
return 0;
}
``` | 2015/05/05 | [
"https://Stackoverflow.com/questions/30044954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4864919/"
] | Using Java 8 you can do this in single line:
```
System.out.println(LocalDate.now().minusMonths(6).format(DateTimeFormatter.ofPattern("yyyy/MM/dd")));
```
If you cannot use Java 8 consider using [Joda Time](http://www.joda.org/joda-time/) library. | Use Joda library because of various shortcomings of the `Date` and `Calendar` classes
```
new DateTime().minusMonths(6).toDate();
```
In **Java 8** update following also will be good.
```
LocalDateTime.from(referenceDate.toInstant()).minusMonths(6);
``` |
30,044,954 | My develop H/W environment is Raspberry Pi2 & VX-1000 camera
My develop S/W environment is Arch linux & c++ & opencv
I could stream on webpage by using mjpg-streamer
with this command `mjpg_streamer -i "./input_uvc.so -d /dev/video0 -n -f 30 -r 320x240" -o "./output_http.so -n -w ./www"`
This run is good. (turns on camera (means turns on led on camera) )
But when I execute the program made by opencv code, it doesn't turn on camera (not turn on led) and the function `cvCaptureFromCAM()` returns `NULL`.
My source code is
```
#include <iostream>
#include <time.h>
#include <opencv/cv.h>
#include <opencv/highgui.h>
using namespace cv;
using namespace std;
int main(int argc,char** argv)
{
char c;
IplImage* frame;
CvCapture* capture;
capture = cvCaptureFromCAM(-1);
if(capture == NULL)
cout << "Strange!!" << endl;
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH , 320);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT , 240);
bool bLoop = true;
cout << "Start streaming" << endl;
while (bLoop){
cvGrabFrame(capture); // Get a frame from cam
frame = cvRetrieveFrame(capture, 0); // get a frame from capture
cvSaveImage("save.jpg", frame);
cvWaitKey(33); // wait key input for 33ms
}
cvReleaseCapture(&capture);
cvDestroyAllWindows();
return 0;
}
``` | 2015/05/05 | [
"https://Stackoverflow.com/questions/30044954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4864919/"
] | Using Java 8 you can do this in single line:
```
System.out.println(LocalDate.now().minusMonths(6).format(DateTimeFormatter.ofPattern("yyyy/MM/dd")));
```
If you cannot use Java 8 consider using [Joda Time](http://www.joda.org/joda-time/) library. | To calculate the previous date just do something like below where **total number of previous days are multiplied with `24 * 60 * 60 * 1000`**
```
new Date(System.currentTimeMillis() - 7 * 24 * 60 * 60 * 1000);
```
Where, *7 days are subtracted from the current date.*
Calculate the number of days in service side & pass it as a parameter to above line of code to get the required previous date.
Hope this helps. |
30,044,954 | My develop H/W environment is Raspberry Pi2 & VX-1000 camera
My develop S/W environment is Arch linux & c++ & opencv
I could stream on webpage by using mjpg-streamer
with this command `mjpg_streamer -i "./input_uvc.so -d /dev/video0 -n -f 30 -r 320x240" -o "./output_http.so -n -w ./www"`
This run is good. (turns on camera (means turns on led on camera) )
But when I execute the program made by opencv code, it doesn't turn on camera (not turn on led) and the function `cvCaptureFromCAM()` returns `NULL`.
My source code is
```
#include <iostream>
#include <time.h>
#include <opencv/cv.h>
#include <opencv/highgui.h>
using namespace cv;
using namespace std;
int main(int argc,char** argv)
{
char c;
IplImage* frame;
CvCapture* capture;
capture = cvCaptureFromCAM(-1);
if(capture == NULL)
cout << "Strange!!" << endl;
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH , 320);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT , 240);
bool bLoop = true;
cout << "Start streaming" << endl;
while (bLoop){
cvGrabFrame(capture); // Get a frame from cam
frame = cvRetrieveFrame(capture, 0); // get a frame from capture
cvSaveImage("save.jpg", frame);
cvWaitKey(33); // wait key input for 33ms
}
cvReleaseCapture(&capture);
cvDestroyAllWindows();
return 0;
}
``` | 2015/05/05 | [
"https://Stackoverflow.com/questions/30044954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4864919/"
] | To calculate the previous date just do something like below where **total number of previous days are multiplied with `24 * 60 * 60 * 1000`**
```
new Date(System.currentTimeMillis() - 7 * 24 * 60 * 60 * 1000);
```
Where, *7 days are subtracted from the current date.*
Calculate the number of days in service side & pass it as a parameter to above line of code to get the required previous date.
Hope this helps. | Use Joda library because of various shortcomings of the `Date` and `Calendar` classes
```
new DateTime().minusMonths(6).toDate();
```
In **Java 8** update following also will be good.
```
LocalDateTime.from(referenceDate.toInstant()).minusMonths(6);
``` |
39,556,519 | I want to create a sass file that the selectors will be attribute selectors.
When I work with class selectors, in most of the cases I will do
```
.parent {
&-child {
}
}
```
which gives me the following css: `.parent-child {}`.
I want to achieve the same thing with attribute selectors:
```
[data-parent] {
&-child {
}
}
```
which I want to become: `[data-parent-child] {}`
someone knows how to achieve this? thanks. | 2016/09/18 | [
"https://Stackoverflow.com/questions/39556519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1926936/"
] | You can use this `mixin` as a workaround to get the desired result.
```
@mixin child-attribute($child) {
$string: inspect(&);
$original: str-slice($string, 3, -4);
@at-root #{ selector-replace(&, &, "[#{$original}#{$child}]" ) } {
@content;
}
}
```
The code simply does the following
1. **$string** variable is responsible for turning the parent selector to a string using the `inspect` function
2. **$original** variable is responsible for getting the *text* content of the `$string` variable i.e the value `'data-parent'` from `'([data-parent])'`
3. **selector-replace** function then replaces the parent selector with the concatenation of the `$original` variable and `child` variable
When used in the following ways
```
[data-parent] {
@include child-attribute('-child') {
color: green;
}
}
```
The css output
```
[data-parent-child] {
color: green;
}
```
Depending on what you want to achieve, it can also be used like this
```
[grandparent] {
@include child-attribute('-parent') {
color: white;
@include child-attribute('-child') {
color: blue;
}
}
}
```
Which generates the following css
```
[grandparent-parent] {
color: white;
}
[grandparent-parent-child] {
color: blue;
}
```
Hope this helps you | You can create `mixin` that will set styles for elements with data attribytes.
Scss:
```
@mixin data($name) {
[data-#{$name}] {
@content;
}
}
* {
@include data('lol') {
color: red;
};
}
```
Css output:
```
* [data-lol] {
color: red;
}
```
**[DEMO](http://www.sassmeister.com/gist/b71cba8f388f207e9b7356b2f6f16ddf)** |
39,556,519 | I want to create a sass file that the selectors will be attribute selectors.
When I work with class selectors, in most of the cases I will do
```
.parent {
&-child {
}
}
```
which gives me the following css: `.parent-child {}`.
I want to achieve the same thing with attribute selectors:
```
[data-parent] {
&-child {
}
}
```
which I want to become: `[data-parent-child] {}`
someone knows how to achieve this? thanks. | 2016/09/18 | [
"https://Stackoverflow.com/questions/39556519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1926936/"
] | You can use this `mixin` as a workaround to get the desired result.
```
@mixin child-attribute($child) {
$string: inspect(&);
$original: str-slice($string, 3, -4);
@at-root #{ selector-replace(&, &, "[#{$original}#{$child}]" ) } {
@content;
}
}
```
The code simply does the following
1. **$string** variable is responsible for turning the parent selector to a string using the `inspect` function
2. **$original** variable is responsible for getting the *text* content of the `$string` variable i.e the value `'data-parent'` from `'([data-parent])'`
3. **selector-replace** function then replaces the parent selector with the concatenation of the `$original` variable and `child` variable
When used in the following ways
```
[data-parent] {
@include child-attribute('-child') {
color: green;
}
}
```
The css output
```
[data-parent-child] {
color: green;
}
```
Depending on what you want to achieve, it can also be used like this
```
[grandparent] {
@include child-attribute('-parent') {
color: white;
@include child-attribute('-child') {
color: blue;
}
}
}
```
Which generates the following css
```
[grandparent-parent] {
color: white;
}
[grandparent-parent-child] {
color: blue;
}
```
Hope this helps you | I would go down a slightly different route of having a `class` on your elements that contain the `data` attributes.
`<div class="data-obj" data-parent="true"></div>`
`<div class="data-obj" data-parent-child="true"></div>`
then in your SASS do
```
.data-obj {
...
&[data-parent] { ... }
&[data-parent-child] { ... }
}
``` |
65,198,438 | We have an application in Asp.net Webform. We must use passwordless sign-in using Microsoft Authenticator App. Basically, the user enters samAccountName, and the system must check Microsoft Authenticator App for approval, and based on the response we have to redirect to change the password screen.
We have a login module that validates our username password with the internal Active directory. We cannot implement a new authentication model now. We just need validation using the Microsoft Authenticator app after approval from the app we need to redirect to the change password screen there we will change the AD account password.
Where do I start with? Plz Help give some idea | 2020/12/08 | [
"https://Stackoverflow.com/questions/65198438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8152735/"
] | The Raw Database returns correct time because DBMS time zone is correct.
but in Eloquent, `created_at` field converts into an `Carbon::class` instance by default.
and `Carbon::class` will use timezone configuration of your app to convert to real time.
so change in laravel `./config/app.php` :
```
'timezone' => 'Asia/Kuala_Lumpur',
```
because i suppose you are in +8 Timezone based on your profile location,
and your reporting time log are 8 hours difference from **UTC** the default time zone config in Laravel. | You can add a mutator to change format returned by eloquent
```
public function getCreatedAtAttribute($value) {
return date('Y-m-d H:i:s',strtotime($value));
}
```
add this function in your Timeline model.
you can also modify function by using carbon methods
for more info you can refer to laravel docs.
<https://laravel.com/docs/8.x/eloquent-mutators#introduction> |
6,034,883 | I'm just wondering if it is possible..
I have a base class, with a variable called Level. I then derive a class from it, but here Level should be called Points.
Is there any way to rename the Level variable in the derived class?
**Edit** - Excuse me for calling a property a variable. I'm quite new to programming, and especially to classes (Which our teacher doesn't teach us for some reason) | 2011/05/17 | [
"https://Stackoverflow.com/questions/6034883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/719392/"
] | The closest you could get with inheritance would be:
```
class BaseClass
{
protected int Level { get; set; }
}
class SubClass : BaseClass
{
public int Points { get { return Level; } set { Level = value; } }
}
```
But that doesn't actually *expose* BaseClass.Level, since a protected property is only visible to subclasses.
As @Jason explains, a subclass can't obscure the public interface of its base class. If you really wanted to do that, you could *encapsulate* the base in a new object that exposes its properties:
```
class A
{
public Foo { get; set; }
public Bar { get; set; }
public Level { get; set;}
}
class B
{
private A _internalA;
public Foo { get { return _internalA.Foo; } set { _internalA.Foo = value; } }
public Bar { get { return _internalA.Bar; } set { _internalA.Bar= value; } }
public Points { get { return _internalA.Level; } set { _internalA.Level = value; } }
}
```
This is typically referred to as *composition*: B is composed of A, rather than inheriting from it. | No, that's not possible. You can override the behavior using virtual properties, but not rename it. |
6,034,883 | I'm just wondering if it is possible..
I have a base class, with a variable called Level. I then derive a class from it, but here Level should be called Points.
Is there any way to rename the Level variable in the derived class?
**Edit** - Excuse me for calling a property a variable. I'm quite new to programming, and especially to classes (Which our teacher doesn't teach us for some reason) | 2011/05/17 | [
"https://Stackoverflow.com/questions/6034883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/719392/"
] | The closest you could get with inheritance would be:
```
class BaseClass
{
protected int Level { get; set; }
}
class SubClass : BaseClass
{
public int Points { get { return Level; } set { Level = value; } }
}
```
But that doesn't actually *expose* BaseClass.Level, since a protected property is only visible to subclasses.
As @Jason explains, a subclass can't obscure the public interface of its base class. If you really wanted to do that, you could *encapsulate* the base in a new object that exposes its properties:
```
class A
{
public Foo { get; set; }
public Bar { get; set; }
public Level { get; set;}
}
class B
{
private A _internalA;
public Foo { get { return _internalA.Foo; } set { _internalA.Foo = value; } }
public Bar { get { return _internalA.Bar; } set { _internalA.Bar= value; } }
public Points { get { return _internalA.Level; } set { _internalA.Level = value; } }
}
```
This is typically referred to as *composition*: B is composed of A, rather than inheriting from it. | >
> Is there any way to rename the Level variable in the derived class?
>
>
>
No, stop and think about why for a second. If you have an instance of `Base`, you could refer to the property `Level`. Now if you have an instance of `Derived`, it is also a `Base`, and therefore it should have property named `Level`. It's that simple: a `Derived` is also a `Base` so whatever you can do with `Base` you should be able to do with `Derived`.
But, you could do this:
```
class Base {
protected int Level { get; set; }
}
class Derived : Base {
public int Points { get { return this.Level; } set { this.Level = value; } }
}
```
Note that `Level` is no longer publicly visible. |
6,034,883 | I'm just wondering if it is possible..
I have a base class, with a variable called Level. I then derive a class from it, but here Level should be called Points.
Is there any way to rename the Level variable in the derived class?
**Edit** - Excuse me for calling a property a variable. I'm quite new to programming, and especially to classes (Which our teacher doesn't teach us for some reason) | 2011/05/17 | [
"https://Stackoverflow.com/questions/6034883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/719392/"
] | The closest you could get with inheritance would be:
```
class BaseClass
{
protected int Level { get; set; }
}
class SubClass : BaseClass
{
public int Points { get { return Level; } set { Level = value; } }
}
```
But that doesn't actually *expose* BaseClass.Level, since a protected property is only visible to subclasses.
As @Jason explains, a subclass can't obscure the public interface of its base class. If you really wanted to do that, you could *encapsulate* the base in a new object that exposes its properties:
```
class A
{
public Foo { get; set; }
public Bar { get; set; }
public Level { get; set;}
}
class B
{
private A _internalA;
public Foo { get { return _internalA.Foo; } set { _internalA.Foo = value; } }
public Bar { get { return _internalA.Bar; } set { _internalA.Bar= value; } }
public Points { get { return _internalA.Level; } set { _internalA.Level = value; } }
}
```
This is typically referred to as *composition*: B is composed of A, rather than inheriting from it. | Classes do not contain variables; they contain fields and properties (and methods, indexers, etc.)
I assume you're referring to properties, because fields shouldn't be public anyway.
There is no way to change the name of a property inherited from a base class.
What you can do:
**Option 1**
Add a property `Points` in addition to the property `Level` inherited from the base class:
```
class MyBaseClass
{
public int Level { get; set; }
}
class MyDerivedClass : MyBaseClass
{
public int Points
{
get { return this.Level; }
set { this.Level = value; }
}
}
```
Example:
```
MyDerivedClass x = new MyDerivedClass();
x.Points = 42;
Console.WriteLine(x.Level); // prints "42"
```
**Option 2**
Turn your base class into an interface, so you can implement it [explicitly](http://msdn.microsoft.com/en-us/library/ms173157%28v=VS.100%29.aspx), thereby hiding the property `Level`:
```
interface IMyInterface
{
int Level { get; set; }
}
class MyClass : IMyInterface
{
int IMyInterface.Level
{
get { return this.Points; }
set { this.Points = value; }
}
public int Points { get; set; }
}
```
Example:
```
MyClass y = new MyClass();
y.Points = 42; // works
y.Level = 99; // doesn't work
IMyInterface z = y;
z.Level = 99; // works
Console.WriteLine(y.Points); // prints "99"
``` |
6,034,883 | I'm just wondering if it is possible..
I have a base class, with a variable called Level. I then derive a class from it, but here Level should be called Points.
Is there any way to rename the Level variable in the derived class?
**Edit** - Excuse me for calling a property a variable. I'm quite new to programming, and especially to classes (Which our teacher doesn't teach us for some reason) | 2011/05/17 | [
"https://Stackoverflow.com/questions/6034883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/719392/"
] | >
> Is there any way to rename the Level variable in the derived class?
>
>
>
No, stop and think about why for a second. If you have an instance of `Base`, you could refer to the property `Level`. Now if you have an instance of `Derived`, it is also a `Base`, and therefore it should have property named `Level`. It's that simple: a `Derived` is also a `Base` so whatever you can do with `Base` you should be able to do with `Derived`.
But, you could do this:
```
class Base {
protected int Level { get; set; }
}
class Derived : Base {
public int Points { get { return this.Level; } set { this.Level = value; } }
}
```
Note that `Level` is no longer publicly visible. | No, that's not possible. You can override the behavior using virtual properties, but not rename it. |
6,034,883 | I'm just wondering if it is possible..
I have a base class, with a variable called Level. I then derive a class from it, but here Level should be called Points.
Is there any way to rename the Level variable in the derived class?
**Edit** - Excuse me for calling a property a variable. I'm quite new to programming, and especially to classes (Which our teacher doesn't teach us for some reason) | 2011/05/17 | [
"https://Stackoverflow.com/questions/6034883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/719392/"
] | Classes do not contain variables; they contain fields and properties (and methods, indexers, etc.)
I assume you're referring to properties, because fields shouldn't be public anyway.
There is no way to change the name of a property inherited from a base class.
What you can do:
**Option 1**
Add a property `Points` in addition to the property `Level` inherited from the base class:
```
class MyBaseClass
{
public int Level { get; set; }
}
class MyDerivedClass : MyBaseClass
{
public int Points
{
get { return this.Level; }
set { this.Level = value; }
}
}
```
Example:
```
MyDerivedClass x = new MyDerivedClass();
x.Points = 42;
Console.WriteLine(x.Level); // prints "42"
```
**Option 2**
Turn your base class into an interface, so you can implement it [explicitly](http://msdn.microsoft.com/en-us/library/ms173157%28v=VS.100%29.aspx), thereby hiding the property `Level`:
```
interface IMyInterface
{
int Level { get; set; }
}
class MyClass : IMyInterface
{
int IMyInterface.Level
{
get { return this.Points; }
set { this.Points = value; }
}
public int Points { get; set; }
}
```
Example:
```
MyClass y = new MyClass();
y.Points = 42; // works
y.Level = 99; // doesn't work
IMyInterface z = y;
z.Level = 99; // works
Console.WriteLine(y.Points); // prints "99"
``` | No, that's not possible. You can override the behavior using virtual properties, but not rename it. |
6,034,883 | I'm just wondering if it is possible..
I have a base class, with a variable called Level. I then derive a class from it, but here Level should be called Points.
Is there any way to rename the Level variable in the derived class?
**Edit** - Excuse me for calling a property a variable. I'm quite new to programming, and especially to classes (Which our teacher doesn't teach us for some reason) | 2011/05/17 | [
"https://Stackoverflow.com/questions/6034883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/719392/"
] | Classes do not contain variables; they contain fields and properties (and methods, indexers, etc.)
I assume you're referring to properties, because fields shouldn't be public anyway.
There is no way to change the name of a property inherited from a base class.
What you can do:
**Option 1**
Add a property `Points` in addition to the property `Level` inherited from the base class:
```
class MyBaseClass
{
public int Level { get; set; }
}
class MyDerivedClass : MyBaseClass
{
public int Points
{
get { return this.Level; }
set { this.Level = value; }
}
}
```
Example:
```
MyDerivedClass x = new MyDerivedClass();
x.Points = 42;
Console.WriteLine(x.Level); // prints "42"
```
**Option 2**
Turn your base class into an interface, so you can implement it [explicitly](http://msdn.microsoft.com/en-us/library/ms173157%28v=VS.100%29.aspx), thereby hiding the property `Level`:
```
interface IMyInterface
{
int Level { get; set; }
}
class MyClass : IMyInterface
{
int IMyInterface.Level
{
get { return this.Points; }
set { this.Points = value; }
}
public int Points { get; set; }
}
```
Example:
```
MyClass y = new MyClass();
y.Points = 42; // works
y.Level = 99; // doesn't work
IMyInterface z = y;
z.Level = 99; // works
Console.WriteLine(y.Points); // prints "99"
``` | >
> Is there any way to rename the Level variable in the derived class?
>
>
>
No, stop and think about why for a second. If you have an instance of `Base`, you could refer to the property `Level`. Now if you have an instance of `Derived`, it is also a `Base`, and therefore it should have property named `Level`. It's that simple: a `Derived` is also a `Base` so whatever you can do with `Base` you should be able to do with `Derived`.
But, you could do this:
```
class Base {
protected int Level { get; set; }
}
class Derived : Base {
public int Points { get { return this.Level; } set { this.Level = value; } }
}
```
Note that `Level` is no longer publicly visible. |
54,847,976 | **What happened:**
1. I have multiple objects saved in an arraylist that is saved in a gson string.
2. I change the class of the object (to include more variables and getter/setter methods)
3. Now I run into errors when trying to load the older objects (saved in step 1)
**Things to consider:**
I use gson/json to store the arraylist in an android shared preference. (the shared preference works fine for other values, the error appears to be when converting the string into an arraylist with json/gson)
**My code:**
```
public void loadDataSavedMatches() {
SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);
Gson gson = new Gson();
String json = prefs.getString("task list", null);
Type type = new TypeToken<ArrayList<TennisMatch>>() {
}.getType();
mTennisMatches = gson.fromJson(json, type);
if (mTennisMatches == null) {
mTennisMatches = new ArrayList<>();
}
Log.i("LOAD DATA", String.valueOf(mTennisMatches));
Log.i("LOAD DATA2", String.valueOf(prefs));
//hashMap
SharedPreferences hashPrefs = getSharedPreferences(HASH_MAP_SHARED_PREFS_FILE, Context.MODE_PRIVATE);
Gson hashGson = new Gson();
String hashJson = hashPrefs.getString("hashString", null);
Type hashType = new TypeToken<HashMap<String, TennisMatch>>() {
}.getType();
item_map = hashGson.fromJson(hashJson, hashType);
if (item_map == null) {
item_map = new HashMap<String, TennisMatch>();
}
}
```
**Error message:**
```
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.android.myapp, PID: 28341
java.lang.AssertionError: impossible
at java.lang.Enum$1.create(Enum.java:45)
at java.lang.Enum$1.create(Enum.java:35)
at libcore.util.BasicLruCache.get(BasicLruCache.java:54)
at java.lang.Enum.getSharedConstants(Enum.java:211)
at java.lang.Class.getEnumConstants(Class.java:1063)
at com.google.gson.internal.bind.TypeAdapters$EnumTypeAdapter.<init>(TypeAdapters.java:778)
at com.google.gson.internal.bind.TypeAdapters$30.create(TypeAdapters.java:817)
at com.google.gson.Gson.getAdapter(Gson.java:423)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:115)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:164)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:100)
at com.google.gson.Gson.getAdapter(Gson.java:423)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory.create(CollectionTypeAdapterFactory.java:53)
at com.google.gson.Gson.getAdapter(Gson.java:423)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:115)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:164)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:100)
at com.google.gson.Gson.getAdapter(Gson.java:423)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:115)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:164)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:100)
at com.google.gson.Gson.getAdapter(Gson.java:423)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:115)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:164)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:100)
at com.google.gson.Gson.getAdapter(Gson.java:423)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory.create(CollectionTypeAdapterFactory.java:53)
at com.google.gson.Gson.getAdapter(Gson.java:423)
at com.google.gson.Gson.fromJson(Gson.java:887)
at com.google.gson.Gson.fromJson(Gson.java:853)
at com.google.gson.Gson.fromJson(Gson.java:802)
at com.android.myapp.Activity.loadDataSavedMatches(ItemMatchListActivity.java:282)
at com.android.myapp.Activity.onCreate(ItemMatchListActivity.java:87)
at android.app.Activity.performCreate(Activity.java:6102)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2403)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
at android.app.ActivityThread.access$1200(ActivityThread.java:165)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1373)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5593)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.NoSuchMethodException: values []
at java.lang.Class.getMethod(Class.java:664)
at java.lang.Class.getDeclaredMethod(Class.java:626)
at java.lang.Enum$1.create(Enum.java:41)
at java.lang.Enum$1.create(Enum.java:35)
at libcore.util.BasicLruCache.get(BasicLruCache.java:54)
at java.lang.Enum.getSharedConstants(Enum.java:211)
at java.lang.Class.getEnumConstants(Class.java:1063)
at com.google.gson.internal.bind.TypeAdapters$EnumTypeAdapter.<init>(TypeAdapters.java:778)
at com.google.gson.internal.bind.TypeAdapters$30.create(TypeAdapters.java:817)
at com.google.gson.Gson.getAdapter(Gson.java:423)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:115)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:164)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:100)
at com.google.gson.Gson.getAdapter(Gson.java:423)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory.create(CollectionTypeAdapterFactory.java:53)
at com.google.gson.Gson.getAdapter(Gson.java:423)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:115)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:164)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:100)
at com.google.gson.Gson.getAdapter(Gson.java:423)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:115)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:164)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:100)
at com.google.gson.Gson.getAdapter(Gson.java:423)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:115)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:164)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:100)
at com.google.gson.Gson.getAdapter(Gson.java:423)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory.create(CollectionTypeAdapterFactory.java:53)
at com.google.gson.Gson.getAdapter(Gson.java:423)
at com.google.gson.Gson.fromJson(Gson.java:887)
at com.google.gson.Gson.fromJson(Gson.java:853)
at com.google.gson.Gson.fromJson(Gson.java:802)
at com.android.myapp.Activity.loadDataSavedMatches(ItemMatchListActivity.java:282)
at com.android.myapp.Activity.onCreate(ItemMatchListActivity.java:87)
at android.app.Activity.performCreate(Activity.java:6102)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2403)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
at android.app.ActivityThread.access$1200(ActivityThread.java:165)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1373)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5593)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
```
**Thank you for your help!** | 2019/02/24 | [
"https://Stackoverflow.com/questions/54847976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8539070/"
] | See [Android release APK crash with java.lang.AssertionError: impossible in java.lang.Enum](https://stackoverflow.com/questions/20651575/android-release-apk-crash-with-java-lang-assertionerror-impossible-in-java-lang/20651744), [AssertionError in Gson EnumTypeAdapter when using Proguard Obfuscation](https://stackoverflow.com/questions/15543607/assertionerror-in-gson-enumtypeadapter-when-using-proguard-obfuscation) or <https://github.com/zendesk/sunshine-conversations-android/issues/93>. In `proguard-rules.pro` add:
```
-keepclassmembers enum * {
public static **[] values();
public static ** valueOf(java.lang.String);
}
``` | Some of the new Data I was including were Firebase DocumentReferences & CollectionReferences, I noticed that these data types don't play nicely with gson/json and therefore I excluded them. I am thinking about using a string to save the Document and Collection Reference instead.
```
// private CollectionReference mColRef; //I removed this from my Object
// private DocumentReference mDocRef;
``` |
39,774,940 | I wrote a data using influx command (CLI) as follows:
```
CREATE DATABASE mydb
USE mydb
insert test value=1234567890123456789i
```
Then, I read the data using influx command (CLI)
```
> select * from test
name: test
time value
1475129299322514085 1234567890123456789
```
OK. No Problem.
But when I read the data using a JAVA program with influxdb-java-2.3.jar:
```
public static void main(String[] args) {
InfluxDB conn = InfluxDBFactory.connect(DB_URL, DB_USER, DB_PASSWD);
String sql = "SELECT time,value from test";
Query query = new Query(sql, DB_NAME);
QueryResult result = conn.query(query, TimeUnit.NANOSECONDS);
Series series = result.getResults().get(0).getSeries().get(0);
System.out.println(series.getColumns().get(0) + "=" + series.getValues().get(0).get(0) + " " + series.getValues().get(0).get(0).getClass().getName());
System.out.println(series.getColumns().get(1) + "=" + series.getValues().get(0).get(1) + " " + series.getValues().get(0).get(1).getClass().getName());
}
```
The result is:
```
time=1.47512929932251418E18 java.lang.Double
value=1.23456789012345677E18 java.lang.Double
```
Why was *"time"* returned in *"Double"* even though the query option was NANOSECONDS?
Why was *"value"* returned in *"Double"* even though the data was inserted with "i" suffix?
The "value" I am expecting is *1234567890123456789*, not *1234567890123456770* *(=1.23456789012345677E18)*.
How will I be able to get "Long" values without rounding error using influxdb-java.jar? | 2016/09/29 | [
"https://Stackoverflow.com/questions/39774940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6900431/"
] | use MSGPACK Format, on influxdb-java-2.15.jar
```
OkHttpClient.Builder client = new OkHttpClient.Builder();
InfluxDB jsonInfluxDB = InfluxDBFactory.connect(URL, USER, PASSWORD, client, ResponseFormat.JSON);
InfluxDB msgpackInfluxDB = InfluxDBFactory.connect(URL, USER, PASSWORD, client, ResponseFormat.MSGPACK);
//influxDB.setLogLevel(InfluxDB.LogLevel.FULL);
Query query = new Query("SELECT * FROM xxx LIMIT 1", "XXX");
QueryResult jsonResult = jsonInfluxDB.query(query, TimeUnit.NANOSECONDS);
logger.info("{}", jsonResult);
QueryResult msgpackResult = msgpackInfluxDB.query(query, TimeUnit.NANOSECONDS);
logger.info("{}", msgpackResult);
```
Result
```
INFO test - QueryResult [results=[Result [series=[Series [name=mib, tags=null, columns=[time, commodity, country, expiration, high, indicator, instrument, last, low, market, modifier, open, strike, turnover, volume], values=[[1.56937620100001485E18, 300, 96, 20191213, 1.621E7, =, 11, 1.6145E7, 1.592E7, 60, 0, 1.6E7, 0, 55640.0, 2.0]]]], error=null]], error=null]
INFO test - QueryResult [results=[Result [series=[Series [name=mib, tags=null, columns=[time, commodity, country, expiration, high, indicator, instrument, last, low, market, modifier, open, strike, turnover, volume], values=[[1569376201000014846, 300, 96, 20191213, 16210000, =, 11, 16145000, 15920000, 60, 0, 16000000, 0, 55640, 2]]]], error=null]], error=null]
``` | Unfortunately there is no proper solution for you. This library designed that way.
Workaround is to cast to `long`:
```
System.out.println(series.getColumns().get(0) + "=" + (long)(double)series.getValues().get(0).get(0) + " " + series.getValues().get(0).get(0).getClass().getName());
```
or
```
System.out.println(series.getColumns().get(1) + "=" + series.getValues().get(0).get(1).longValue() + " " + series.getValues().get(0).get(1).getClass().getName());
``` |
57,472,014 | This is the jsp page I'm using.I wrote javascript inside jsp. I have done some validation on form and then ajax call is used. Please check whether I have done something wrong in jsp.
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Register page</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<h3>Student registration form:</h3>
<form action="RegisterController" method="get" id="registerForm" name="stud" >
<table>
<tr>
<td><label>Username:</label></td>
<td><input type="text" name="uname" id="uname"></td><td><label id="nameId"></label></td>
</tr>
<tr>
<td><label>Email id:</label></td>
<td><input type="text" name="email" id="email"></td><td><label id="emailId"></label></td>
</tr>
<tr>
<td><label>Contact No:</label></td>
<td><input type="number" name="contact" id="contact"></td><td><label id="contactId"></label></td>
</tr>
<tr>
<td><label>Address:</label></td>
<td><textarea name="address" rows="3" cols="20" id="address"></textarea></td><td><label id="addressId"></label></td>
</tr>
<tr>
<td>Select City:</td>
<td>
<input type="text" list="city" name="cities" id="cities">
<datalist id="city">
<option value="Mumbai">Mumbai</option>
<option value="Pune">Pune</option>
<option value="Nashik">Nashik</option>
<option value="Solapur">Solapur</option>
</datalist>
</td><td>
<label id="cityId"></label>
</td>
</tr>
<tr>
<td>Gender:</td>
<td><input id="r1" type="radio" name="gender" value="male">Male<input id="r2" type="radio" name="gender" value="female">Female</td><td><label id="genderId"></label></td>
</tr>
<tr>
<td><label>Courses:</label></td>
<td>Java<input id="cb1" type="checkbox" name="course" value="java">Spark<input id="cb2" type="checkbox" name="course" value="spark">Hadoop<input id="cb3" type="checkbox" name="course" value="hadoop">PHP<input id="cb4" type="checkbox" name="course" value="php"></td><td><label id="courseId"></label></td>
</tr>
<tr>
<td>Select Time Preferable</td>
<td>
<select name="batches" id="batches">
<option value="7 am to 8 am">7 am to 8 am</option>
<option value="9 am to 10 am">9 am to 10 am</option>
<option value="11 am to 12 pm">11 am to 12 pm</option>
</select>
</td>
</tr>
</table>
<br>
<input type="submit" value="Register" id="Register"><br><br>
</form>
<a href="index.jsp">Go to login page</a>
</body>
<script type="text/javascript">
$(document).ready(function(){
$('#registerForm').submit(function(es){
es.preventDefault();
var name=$('#uname').val();
var email=$('#email').val();
var contact=$('#contact').val();
var address=$('#address').val();
var city=$('#cities').val();
var gender1=$('#r1').is(":checked");
var gender2=$('#r2').is(":checked");
var cbOne=$('#cb1').is(":checked");
var cbTwo=$('#cb2').is(":checked");
var cbThree=$('#cb3').is(":checked");
var cbFour=$('#cb4').is(":checked");
$('.error').remove();
//validating fields of form
if(name.length<=0){
$('#nameId').after('<span class="error" style="color:red">Enter the Username</span>');
}
if(contact.length!=10){
$('#contactId').after('<span class="error" style="color:red">Enter valid contact number</span>');
}
if(address.length<=0){
$('#addressId').after('<span class="error" style="color:red">Enter the address</span>');
}
if(city.length<=0){
$('#cityId').after('<span class="error" style="color:red">Enter the city</span>');
}
if(!(gender1||gender2)){
$('#genderId').after('<span class="error" style="color:red">Select gender</span>');
}
if(!(cbOne||cbTwo||cbThree||cbFour)){
$('#courseId').after('<span class="error" style="color:red">Select at least one course</span>')
}
if(email.length<=0){
$('#emailId').after('<span class="error" style="color:red">Enter the email</span>');
}
else{
//var regEx=/^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
//var regEx=/^\w+@[a-zA-Z]+\.[a-zA-Z]{2,3}$/;
var regEx=/^[a-zA-Z0-9]+@[a-zA-Z]+\.[com]{3}$/;
var validEmail=regEx.test(email);
if(!validEmail){
$('#emailId').after('<span class="error" style="color:red">Enter valid email</span>');
}
}
//data to be passed
var form_data={
username:$('#uname').val(),
email:$('#email').val(),
contact:$('#contact').val(),
address:$('#address').val(),
city:$('#cities').val(),
batch:$('#batches').val()
};
//ajax call goes here
$.ajax({
type: 'GET',
url: './RegisterController',
dataType: 'json',
data: form_data,
success: function(){
console.log("Sucess: ");
},
error : function(message) {
alert("error: "+message);
}
});
});
} );
</script>
</html>
```
I'm creating a registration form and want to transfer data of form using ajax call.I wrote the javascript for it. But Ajax call is triggering error function. I'm not getting what is wrong in the code.
```js
<script type="text/javascript">
$(document).ready(function(){
$('#registerForm').submit(function(es){
es.preventDefault();
var form_data={
username:$('#uname').val(),
email:$('#email').val(),
contact:$('#contact').val(),
address:$('#address').val(),
city:$('#cities').val(),
batch:$('#batches').val()
};
$.ajax({
type: 'GET',
url: 'RegisterController',
data: form_data,
success: function(){
console.log("Sucess: ");
},
error : function(message) {
alert("error: "+message);
}
});
});
} );
</script>
```
Thanks in advance. | 2019/08/13 | [
"https://Stackoverflow.com/questions/57472014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11920605/"
] | you can chnage the class of `white-text` to `text-white` and for background-color add `bg-primary` and also add code for custom color.
```css
.bg-custom{
background-color:#33b5e5 !important;
}
```
```html
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<h3>Default color</h3>
<h5 class="card-header bg-primary text-white text-center py-4" >Sign in</h5>
<hr/>
<h3>Custom color</h3>
<h5 class="card-header bg-custom text-white text-center py-4" >Sign in</h5>
<hr/>
<h3>With inline css</h3>
<h5 class="card-header text-white text-center py-4" style="background-color:#33b5e5">Sign in</h5>
``` | Please use bg-primary class.
```html
<h5 class="card-header info-color white-text text-center py-4 bg-primary">Sign in</h5>
``` |
57,472,014 | This is the jsp page I'm using.I wrote javascript inside jsp. I have done some validation on form and then ajax call is used. Please check whether I have done something wrong in jsp.
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Register page</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<h3>Student registration form:</h3>
<form action="RegisterController" method="get" id="registerForm" name="stud" >
<table>
<tr>
<td><label>Username:</label></td>
<td><input type="text" name="uname" id="uname"></td><td><label id="nameId"></label></td>
</tr>
<tr>
<td><label>Email id:</label></td>
<td><input type="text" name="email" id="email"></td><td><label id="emailId"></label></td>
</tr>
<tr>
<td><label>Contact No:</label></td>
<td><input type="number" name="contact" id="contact"></td><td><label id="contactId"></label></td>
</tr>
<tr>
<td><label>Address:</label></td>
<td><textarea name="address" rows="3" cols="20" id="address"></textarea></td><td><label id="addressId"></label></td>
</tr>
<tr>
<td>Select City:</td>
<td>
<input type="text" list="city" name="cities" id="cities">
<datalist id="city">
<option value="Mumbai">Mumbai</option>
<option value="Pune">Pune</option>
<option value="Nashik">Nashik</option>
<option value="Solapur">Solapur</option>
</datalist>
</td><td>
<label id="cityId"></label>
</td>
</tr>
<tr>
<td>Gender:</td>
<td><input id="r1" type="radio" name="gender" value="male">Male<input id="r2" type="radio" name="gender" value="female">Female</td><td><label id="genderId"></label></td>
</tr>
<tr>
<td><label>Courses:</label></td>
<td>Java<input id="cb1" type="checkbox" name="course" value="java">Spark<input id="cb2" type="checkbox" name="course" value="spark">Hadoop<input id="cb3" type="checkbox" name="course" value="hadoop">PHP<input id="cb4" type="checkbox" name="course" value="php"></td><td><label id="courseId"></label></td>
</tr>
<tr>
<td>Select Time Preferable</td>
<td>
<select name="batches" id="batches">
<option value="7 am to 8 am">7 am to 8 am</option>
<option value="9 am to 10 am">9 am to 10 am</option>
<option value="11 am to 12 pm">11 am to 12 pm</option>
</select>
</td>
</tr>
</table>
<br>
<input type="submit" value="Register" id="Register"><br><br>
</form>
<a href="index.jsp">Go to login page</a>
</body>
<script type="text/javascript">
$(document).ready(function(){
$('#registerForm').submit(function(es){
es.preventDefault();
var name=$('#uname').val();
var email=$('#email').val();
var contact=$('#contact').val();
var address=$('#address').val();
var city=$('#cities').val();
var gender1=$('#r1').is(":checked");
var gender2=$('#r2').is(":checked");
var cbOne=$('#cb1').is(":checked");
var cbTwo=$('#cb2').is(":checked");
var cbThree=$('#cb3').is(":checked");
var cbFour=$('#cb4').is(":checked");
$('.error').remove();
//validating fields of form
if(name.length<=0){
$('#nameId').after('<span class="error" style="color:red">Enter the Username</span>');
}
if(contact.length!=10){
$('#contactId').after('<span class="error" style="color:red">Enter valid contact number</span>');
}
if(address.length<=0){
$('#addressId').after('<span class="error" style="color:red">Enter the address</span>');
}
if(city.length<=0){
$('#cityId').after('<span class="error" style="color:red">Enter the city</span>');
}
if(!(gender1||gender2)){
$('#genderId').after('<span class="error" style="color:red">Select gender</span>');
}
if(!(cbOne||cbTwo||cbThree||cbFour)){
$('#courseId').after('<span class="error" style="color:red">Select at least one course</span>')
}
if(email.length<=0){
$('#emailId').after('<span class="error" style="color:red">Enter the email</span>');
}
else{
//var regEx=/^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
//var regEx=/^\w+@[a-zA-Z]+\.[a-zA-Z]{2,3}$/;
var regEx=/^[a-zA-Z0-9]+@[a-zA-Z]+\.[com]{3}$/;
var validEmail=regEx.test(email);
if(!validEmail){
$('#emailId').after('<span class="error" style="color:red">Enter valid email</span>');
}
}
//data to be passed
var form_data={
username:$('#uname').val(),
email:$('#email').val(),
contact:$('#contact').val(),
address:$('#address').val(),
city:$('#cities').val(),
batch:$('#batches').val()
};
//ajax call goes here
$.ajax({
type: 'GET',
url: './RegisterController',
dataType: 'json',
data: form_data,
success: function(){
console.log("Sucess: ");
},
error : function(message) {
alert("error: "+message);
}
});
});
} );
</script>
</html>
```
I'm creating a registration form and want to transfer data of form using ajax call.I wrote the javascript for it. But Ajax call is triggering error function. I'm not getting what is wrong in the code.
```js
<script type="text/javascript">
$(document).ready(function(){
$('#registerForm').submit(function(es){
es.preventDefault();
var form_data={
username:$('#uname').val(),
email:$('#email').val(),
contact:$('#contact').val(),
address:$('#address').val(),
city:$('#cities').val(),
batch:$('#batches').val()
};
$.ajax({
type: 'GET',
url: 'RegisterController',
data: form_data,
success: function(){
console.log("Sucess: ");
},
error : function(message) {
alert("error: "+message);
}
});
});
} );
</script>
```
Thanks in advance. | 2019/08/13 | [
"https://Stackoverflow.com/questions/57472014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11920605/"
] | you can chnage the class of `white-text` to `text-white` and for background-color add `bg-primary` and also add code for custom color.
```css
.bg-custom{
background-color:#33b5e5 !important;
}
```
```html
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<h3>Default color</h3>
<h5 class="card-header bg-primary text-white text-center py-4" >Sign in</h5>
<hr/>
<h3>Custom color</h3>
<h5 class="card-header bg-custom text-white text-center py-4" >Sign in</h5>
<hr/>
<h3>With inline css</h3>
<h5 class="card-header text-white text-center py-4" style="background-color:#33b5e5">Sign in</h5>
``` | You need to add `bg-info text-white` instead of `info-color white-text`
```html
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<p class="h4 mb-4">Sign in</p>
<h5 class="card-header bg-info text-white text-center py-4" >Sign in</h5>
```
This is reference [link](https://getbootstrap.com/docs/4.3/utilities/colors/#background-color) |
546,986 | $$\int\_0^\frac{\pi}{2}(\sin^3x +\cos^3x) \, \mathrm{d}x$$
How do I compute this? I tried to do the trigonometric manupulation but I can't get the answer. | 2013/10/31 | [
"https://math.stackexchange.com/questions/546986",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/101194/"
] | $\int\sin^3xdx=\int\sin^2x\sin(x)dx=-\int(1-\cos^2x)d\cos x$ | $\sin 3x$=$3\sin x$-$4\sin^3 x$ and
$\cos 3x=4\cos^3 x -3\cos x$
.use this formula to subtitute $\sin^3x$ and $\cos^3 x$ and use simple integration |
546,986 | $$\int\_0^\frac{\pi}{2}(\sin^3x +\cos^3x) \, \mathrm{d}x$$
How do I compute this? I tried to do the trigonometric manupulation but I can't get the answer. | 2013/10/31 | [
"https://math.stackexchange.com/questions/546986",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/101194/"
] | Hint: $\sin^3 x dx = -\sin^2 xd(\cos x) = (\cos^2 x - 1)d(\cos x)$. Do the same for $\cos^3 x dx$. | **Hint:** Use partial integration a couple of times. |
546,986 | $$\int\_0^\frac{\pi}{2}(\sin^3x +\cos^3x) \, \mathrm{d}x$$
How do I compute this? I tried to do the trigonometric manupulation but I can't get the answer. | 2013/10/31 | [
"https://math.stackexchange.com/questions/546986",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/101194/"
] | $a^3+b^3 = (a+b)(a^2+b^2 -ab)$, applying this to $a=\sin x, b=\cos x$, produces (noting that $a^2 + b^2 =1$),
$$I= \int (\sin x +\cos x )dx - \int (\sin x + \cos x)\sin x \cos x dx.$$
The second integral can be further expanded and solved with simple substitutions for $\sin x$ and $\cos x$. | $\sin 3x$=$3\sin x$-$4\sin^3 x$ and
$\cos 3x=4\cos^3 x -3\cos x$
.use this formula to subtitute $\sin^3x$ and $\cos^3 x$ and use simple integration |
546,986 | $$\int\_0^\frac{\pi}{2}(\sin^3x +\cos^3x) \, \mathrm{d}x$$
How do I compute this? I tried to do the trigonometric manupulation but I can't get the answer. | 2013/10/31 | [
"https://math.stackexchange.com/questions/546986",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/101194/"
] | $\int\sin^3xdx=\int\sin^2x\sin(x)dx=-\int(1-\cos^2x)d\cos x$ | The curve of $sinx$ and $cosx$ in the interval $(0,\frac{\pi}{2})$ is symmetric. So the curve of $sin^3x$ and $cos^3x$ are symmetric too. Hence the area enclosed under the curves are also equal. So the expression can be re-written as,
$2\int\_0^\frac{\pi}{2}sin^3x~dx$ or $2\int\_0^\frac{\pi}{2}cos^3x~dx$ whichever you prefer to evaluate.
I proceeded with $sin^3x$.
$2\int\_0^\frac{\pi}{2}sin^3x~dx$
$=2\int\_0^\frac{\pi}{2}2sinx(1-cos^2x)~dx$
$=2\int\_0^\frac{\pi}{2}sinx~dx-2\int\_0^\frac{\pi}{2}cos^2xsinx~dx$
Evaluating the first part of the integral is trivial. In the second part substitute $cosx=t$.
Rest of the part is very trivial to calculate. Don't forget to change the limit of the integral after substitution or simply reverse back the substitution you made to the expression after evaluation of the integral. |
546,986 | $$\int\_0^\frac{\pi}{2}(\sin^3x +\cos^3x) \, \mathrm{d}x$$
How do I compute this? I tried to do the trigonometric manupulation but I can't get the answer. | 2013/10/31 | [
"https://math.stackexchange.com/questions/546986",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/101194/"
] | $\int\sin^3xdx=\int\sin^2x\sin(x)dx=-\int(1-\cos^2x)d\cos x$ | **Hint:** Use partial integration a couple of times. |
546,986 | $$\int\_0^\frac{\pi}{2}(\sin^3x +\cos^3x) \, \mathrm{d}x$$
How do I compute this? I tried to do the trigonometric manupulation but I can't get the answer. | 2013/10/31 | [
"https://math.stackexchange.com/questions/546986",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/101194/"
] | Applying **[this](https://en.wikipedia.org/wiki/Integration_by_reduction_formulae)** should give you your answer in no time! | $\sin 3x$=$3\sin x$-$4\sin^3 x$ and
$\cos 3x=4\cos^3 x -3\cos x$
.use this formula to subtitute $\sin^3x$ and $\cos^3 x$ and use simple integration |
546,986 | $$\int\_0^\frac{\pi}{2}(\sin^3x +\cos^3x) \, \mathrm{d}x$$
How do I compute this? I tried to do the trigonometric manupulation but I can't get the answer. | 2013/10/31 | [
"https://math.stackexchange.com/questions/546986",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/101194/"
] | Applying **[this](https://en.wikipedia.org/wiki/Integration_by_reduction_formulae)** should give you your answer in no time! | **Hint:** Use partial integration a couple of times. |
546,986 | $$\int\_0^\frac{\pi}{2}(\sin^3x +\cos^3x) \, \mathrm{d}x$$
How do I compute this? I tried to do the trigonometric manupulation but I can't get the answer. | 2013/10/31 | [
"https://math.stackexchange.com/questions/546986",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/101194/"
] | $a^3+b^3 = (a+b)(a^2+b^2 -ab)$, applying this to $a=\sin x, b=\cos x$, produces (noting that $a^2 + b^2 =1$),
$$I= \int (\sin x +\cos x )dx - \int (\sin x + \cos x)\sin x \cos x dx.$$
The second integral can be further expanded and solved with simple substitutions for $\sin x$ and $\cos x$. | The curve of $sinx$ and $cosx$ in the interval $(0,\frac{\pi}{2})$ is symmetric. So the curve of $sin^3x$ and $cos^3x$ are symmetric too. Hence the area enclosed under the curves are also equal. So the expression can be re-written as,
$2\int\_0^\frac{\pi}{2}sin^3x~dx$ or $2\int\_0^\frac{\pi}{2}cos^3x~dx$ whichever you prefer to evaluate.
I proceeded with $sin^3x$.
$2\int\_0^\frac{\pi}{2}sin^3x~dx$
$=2\int\_0^\frac{\pi}{2}2sinx(1-cos^2x)~dx$
$=2\int\_0^\frac{\pi}{2}sinx~dx-2\int\_0^\frac{\pi}{2}cos^2xsinx~dx$
Evaluating the first part of the integral is trivial. In the second part substitute $cosx=t$.
Rest of the part is very trivial to calculate. Don't forget to change the limit of the integral after substitution or simply reverse back the substitution you made to the expression after evaluation of the integral. |
546,986 | $$\int\_0^\frac{\pi}{2}(\sin^3x +\cos^3x) \, \mathrm{d}x$$
How do I compute this? I tried to do the trigonometric manupulation but I can't get the answer. | 2013/10/31 | [
"https://math.stackexchange.com/questions/546986",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/101194/"
] | Applying **[this](https://en.wikipedia.org/wiki/Integration_by_reduction_formulae)** should give you your answer in no time! | The curve of $sinx$ and $cosx$ in the interval $(0,\frac{\pi}{2})$ is symmetric. So the curve of $sin^3x$ and $cos^3x$ are symmetric too. Hence the area enclosed under the curves are also equal. So the expression can be re-written as,
$2\int\_0^\frac{\pi}{2}sin^3x~dx$ or $2\int\_0^\frac{\pi}{2}cos^3x~dx$ whichever you prefer to evaluate.
I proceeded with $sin^3x$.
$2\int\_0^\frac{\pi}{2}sin^3x~dx$
$=2\int\_0^\frac{\pi}{2}2sinx(1-cos^2x)~dx$
$=2\int\_0^\frac{\pi}{2}sinx~dx-2\int\_0^\frac{\pi}{2}cos^2xsinx~dx$
Evaluating the first part of the integral is trivial. In the second part substitute $cosx=t$.
Rest of the part is very trivial to calculate. Don't forget to change the limit of the integral after substitution or simply reverse back the substitution you made to the expression after evaluation of the integral. |
546,986 | $$\int\_0^\frac{\pi}{2}(\sin^3x +\cos^3x) \, \mathrm{d}x$$
How do I compute this? I tried to do the trigonometric manupulation but I can't get the answer. | 2013/10/31 | [
"https://math.stackexchange.com/questions/546986",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/101194/"
] | Hint: $\sin^3 x dx = -\sin^2 xd(\cos x) = (\cos^2 x - 1)d(\cos x)$. Do the same for $\cos^3 x dx$. | $\sin 3x$=$3\sin x$-$4\sin^3 x$ and
$\cos 3x=4\cos^3 x -3\cos x$
.use this formula to subtitute $\sin^3x$ and $\cos^3 x$ and use simple integration |
50,256,184 | This is just a small portion of the data frame I am working with:
```
id drug start stop dose unit route
2010003 Amlodipine 2009-02-04 2009-11-19 1.5 mg Oral
2010003 Amlodipine 2009-11-19 2010-01-11 1.5 mg Oral
2010004 Cefprozil 2004-03-12 2004-03-19 175 mg Oral
2010004 Clobazam 2002-12-30 2003-01-01 5 mg Oral
```
I have a Stata `do` file, which shows what I am trying to do:
```
replace class = "ACE Inhibitor" if strmatch(upper(drug), "CAPTOPRIL*")
replace class = "ACE Inhibitor" if strmatch(upper(drug), "ENALAPRIL*")
replace class = "ACE Inhibitor" if strmatch(upper(drug), "ENALAPRILAT*")
replace class = "ACE Inhibitor" if strmatch(upper(drug), "FOSINOPRIL*")
replace class = "ACE Inhibitor" if strmatch(upper(drug), "LISINOPRIL*")
replace class = "ACE Inhibitor" if strmatch(upper(drug), "RAMIPRIL*")
replace class = "Acne Medication" if strmatch(upper(drug), "ADAPALENE*")
replace class = "Acne Medication" if strmatch(upper(drug), "ADAPALENE/BENZOYL PEROXIDE*")
replace class = "Acne Medication" if strmatch(upper(drug), "BENZOYL PEROXIDE*")
replace class = "Acne Medication" if strmatch(upper(drug), "BENZOYL PEROXIDE/CLINDAMYCIN*")
replace class = "Acne Medication" if strmatch(upper(drug), "ISOTRETINOIN*")
replace class = "Acne Medication" if strmatch(upper(drug), "ERYTHROMYCIN/TRETINOIN*")
replace class = "Acne Medication/Acute Promyelocytic Leukemia Medication" if strmatch(upper(drug), "TRETINOIN*")
replace class = "Alpha Agonist" if strmatch(upper(drug), "XYLOMETAZOLINE*")
replace class = "Alpha Blocker" if strmatch(upper(drug), "DOXAZOSIN*")
replace class = "Alpha Blocker" if strmatch(upper(drug), "PHENOXYBENZAMINE*")
replace class = "Alpha Blocker" if strmatch(upper(drug), "PHENTOLAMINE*")
replace class = "Alpha Blocker" if strmatch(upper(drug), "PRAZOSIN*")
replace class = "Alpha Blocker" if strmatch(upper(drug), "TAMSULOSIN*")
replace class = "Alpha Blocker" if strmatch(upper(drug), "TERAZOSIN*")
replace class = "Alpha/Beta Blocker" if strmatch(upper(drug), "CARVEDILOL*")
replace class = "Alpha/Beta Blocker" if strmatch(upper(drug), "LABETALOL*")
replace class = "Alpha-1 Agonist" if strmatch(upper(drug), "PHENYLEPHRINE*")
replace class = "Alpha-1 Agonist" if strmatch(upper(drug), "MIDODRINE*")
replace class = "Alpha-2 Agonist" if strmatch(upper(drug), "CLONIDINE*")
replace class = "Alpha-2 Agonist" if strmatch(upper(drug), "DEXMEDETOMIDINE*")
replace class = "Anaesthetic, general" if strmatch(upper(drug), "KETAMINE*")
replace class = "Anaesthetic, general" if strmatch(upper(drug), "THIOPENTAL*")
replace class = "Anaesthetic, local" if strmatch(upper(drug), "BENZOCAINE*")
replace class = "Anaesthetic, local" if strmatch(upper(drug), "BUPIVACAINE*")
replace class = "Anaesthetic, local" if strmatch(upper(drug), "BUPIVACAINE/FENTANYL*")
replace class = "Anaesthetic, local" if strmatch(upper(drug), "TETRACAINE*")
replace class = "Anaesthetic, local" if strmatch(upper(drug), "XYLOCAINE*")
replace class = "Anaesthetic, local/Antiarrythmic" if strmatch(upper(drug), "LIDOCAINE*")
replace class = "Anaesthetic, local/Antiseptic" if strmatch(upper(drug), "HEXYLRESORCINOL*")
replace class = "Anaesthetic, topical" if strmatch(upper(drug), "LIDOCAINE/PRILOCAINE*")
replace class = "Anaesthetic, topical" if strmatch(upper(drug), "PROPARACAINE*")
replace class = "Analgesic" if strmatch(upper(drug), "ACETAMINOPHEN*")
replace class = "Analgesic" if strmatch(upper(drug), "BELLADONNA & OPIUM SUPPOSITORY*")
```
I want to do the same classification in R but I do not know Stata.
Note that drugs can have more than one `class`.
Any advice and help would be greatly appreciated. | 2018/05/09 | [
"https://Stackoverflow.com/questions/50256184",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Change the code with:
```
[Unit]
Description=Atlassian Bamboo Agent
After=syslog.target network.target
[Service]
Type=forking
User=apps
Group=apps
ExecStart=/apps/bamboo-agent/bin/bamboo-agent.sh start
ExecStop=/apps/bamboo-agent/bin/bamboo-agent.sh stop
[Install]
WantedBy=multi-user.target
```
Then reload and start it (as root or using sudo)
```
systemctl daemon-reload
systemctl start bamboo-agent
```
Res: <https://community.atlassian.com/t5/Bamboo-questions/How-to-I-install-bamboo-agent-as-a-daemon-under-Linux/qaq-p/393880> | Have you installed the agent? Atlassian's Documentation sucks in this one.
You should install the agent as bamboo user with the word "**install**" at the end.
```
java -jar atlassian-bamboo-agent-installer-6.7.2.jar https://my.bamboo-server.com/agentServer/ install
```
Replace with the address of your Server of course
Also if you run `journalctl -xe` you'll probably see something like
[](https://i.stack.imgur.com/D1hjS.png)
This means you have to go to your bamboo-server under your **agents** page and confirm the agent.
[](https://i.stack.imgur.com/S55oy.png) |
50,256,184 | This is just a small portion of the data frame I am working with:
```
id drug start stop dose unit route
2010003 Amlodipine 2009-02-04 2009-11-19 1.5 mg Oral
2010003 Amlodipine 2009-11-19 2010-01-11 1.5 mg Oral
2010004 Cefprozil 2004-03-12 2004-03-19 175 mg Oral
2010004 Clobazam 2002-12-30 2003-01-01 5 mg Oral
```
I have a Stata `do` file, which shows what I am trying to do:
```
replace class = "ACE Inhibitor" if strmatch(upper(drug), "CAPTOPRIL*")
replace class = "ACE Inhibitor" if strmatch(upper(drug), "ENALAPRIL*")
replace class = "ACE Inhibitor" if strmatch(upper(drug), "ENALAPRILAT*")
replace class = "ACE Inhibitor" if strmatch(upper(drug), "FOSINOPRIL*")
replace class = "ACE Inhibitor" if strmatch(upper(drug), "LISINOPRIL*")
replace class = "ACE Inhibitor" if strmatch(upper(drug), "RAMIPRIL*")
replace class = "Acne Medication" if strmatch(upper(drug), "ADAPALENE*")
replace class = "Acne Medication" if strmatch(upper(drug), "ADAPALENE/BENZOYL PEROXIDE*")
replace class = "Acne Medication" if strmatch(upper(drug), "BENZOYL PEROXIDE*")
replace class = "Acne Medication" if strmatch(upper(drug), "BENZOYL PEROXIDE/CLINDAMYCIN*")
replace class = "Acne Medication" if strmatch(upper(drug), "ISOTRETINOIN*")
replace class = "Acne Medication" if strmatch(upper(drug), "ERYTHROMYCIN/TRETINOIN*")
replace class = "Acne Medication/Acute Promyelocytic Leukemia Medication" if strmatch(upper(drug), "TRETINOIN*")
replace class = "Alpha Agonist" if strmatch(upper(drug), "XYLOMETAZOLINE*")
replace class = "Alpha Blocker" if strmatch(upper(drug), "DOXAZOSIN*")
replace class = "Alpha Blocker" if strmatch(upper(drug), "PHENOXYBENZAMINE*")
replace class = "Alpha Blocker" if strmatch(upper(drug), "PHENTOLAMINE*")
replace class = "Alpha Blocker" if strmatch(upper(drug), "PRAZOSIN*")
replace class = "Alpha Blocker" if strmatch(upper(drug), "TAMSULOSIN*")
replace class = "Alpha Blocker" if strmatch(upper(drug), "TERAZOSIN*")
replace class = "Alpha/Beta Blocker" if strmatch(upper(drug), "CARVEDILOL*")
replace class = "Alpha/Beta Blocker" if strmatch(upper(drug), "LABETALOL*")
replace class = "Alpha-1 Agonist" if strmatch(upper(drug), "PHENYLEPHRINE*")
replace class = "Alpha-1 Agonist" if strmatch(upper(drug), "MIDODRINE*")
replace class = "Alpha-2 Agonist" if strmatch(upper(drug), "CLONIDINE*")
replace class = "Alpha-2 Agonist" if strmatch(upper(drug), "DEXMEDETOMIDINE*")
replace class = "Anaesthetic, general" if strmatch(upper(drug), "KETAMINE*")
replace class = "Anaesthetic, general" if strmatch(upper(drug), "THIOPENTAL*")
replace class = "Anaesthetic, local" if strmatch(upper(drug), "BENZOCAINE*")
replace class = "Anaesthetic, local" if strmatch(upper(drug), "BUPIVACAINE*")
replace class = "Anaesthetic, local" if strmatch(upper(drug), "BUPIVACAINE/FENTANYL*")
replace class = "Anaesthetic, local" if strmatch(upper(drug), "TETRACAINE*")
replace class = "Anaesthetic, local" if strmatch(upper(drug), "XYLOCAINE*")
replace class = "Anaesthetic, local/Antiarrythmic" if strmatch(upper(drug), "LIDOCAINE*")
replace class = "Anaesthetic, local/Antiseptic" if strmatch(upper(drug), "HEXYLRESORCINOL*")
replace class = "Anaesthetic, topical" if strmatch(upper(drug), "LIDOCAINE/PRILOCAINE*")
replace class = "Anaesthetic, topical" if strmatch(upper(drug), "PROPARACAINE*")
replace class = "Analgesic" if strmatch(upper(drug), "ACETAMINOPHEN*")
replace class = "Analgesic" if strmatch(upper(drug), "BELLADONNA & OPIUM SUPPOSITORY*")
```
I want to do the same classification in R but I do not know Stata.
Note that drugs can have more than one `class`.
Any advice and help would be greatly appreciated. | 2018/05/09 | [
"https://Stackoverflow.com/questions/50256184",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Change the code with:
```
[Unit]
Description=Atlassian Bamboo Agent
After=syslog.target network.target
[Service]
Type=forking
User=apps
Group=apps
ExecStart=/apps/bamboo-agent/bin/bamboo-agent.sh start
ExecStop=/apps/bamboo-agent/bin/bamboo-agent.sh stop
[Install]
WantedBy=multi-user.target
```
Then reload and start it (as root or using sudo)
```
systemctl daemon-reload
systemctl start bamboo-agent
```
Res: <https://community.atlassian.com/t5/Bamboo-questions/How-to-I-install-bamboo-agent-as-a-daemon-under-Linux/qaq-p/393880> | We have a shell script to start the remote agent that is called in a cron job that runs on reboot
launchRemoteAgent.sh
java -jar /home/bamboo/bamboo-agent-home/atlassian-bamboo-agent-installer-6.6.3.jar http://:8085/agentServer/ > /home/bamboo/bamboo.log 2>&1 &
crontab
@reboot /home/bamboo/bin/launchRemoteAgent.sh > /dev/null |
50,256,184 | This is just a small portion of the data frame I am working with:
```
id drug start stop dose unit route
2010003 Amlodipine 2009-02-04 2009-11-19 1.5 mg Oral
2010003 Amlodipine 2009-11-19 2010-01-11 1.5 mg Oral
2010004 Cefprozil 2004-03-12 2004-03-19 175 mg Oral
2010004 Clobazam 2002-12-30 2003-01-01 5 mg Oral
```
I have a Stata `do` file, which shows what I am trying to do:
```
replace class = "ACE Inhibitor" if strmatch(upper(drug), "CAPTOPRIL*")
replace class = "ACE Inhibitor" if strmatch(upper(drug), "ENALAPRIL*")
replace class = "ACE Inhibitor" if strmatch(upper(drug), "ENALAPRILAT*")
replace class = "ACE Inhibitor" if strmatch(upper(drug), "FOSINOPRIL*")
replace class = "ACE Inhibitor" if strmatch(upper(drug), "LISINOPRIL*")
replace class = "ACE Inhibitor" if strmatch(upper(drug), "RAMIPRIL*")
replace class = "Acne Medication" if strmatch(upper(drug), "ADAPALENE*")
replace class = "Acne Medication" if strmatch(upper(drug), "ADAPALENE/BENZOYL PEROXIDE*")
replace class = "Acne Medication" if strmatch(upper(drug), "BENZOYL PEROXIDE*")
replace class = "Acne Medication" if strmatch(upper(drug), "BENZOYL PEROXIDE/CLINDAMYCIN*")
replace class = "Acne Medication" if strmatch(upper(drug), "ISOTRETINOIN*")
replace class = "Acne Medication" if strmatch(upper(drug), "ERYTHROMYCIN/TRETINOIN*")
replace class = "Acne Medication/Acute Promyelocytic Leukemia Medication" if strmatch(upper(drug), "TRETINOIN*")
replace class = "Alpha Agonist" if strmatch(upper(drug), "XYLOMETAZOLINE*")
replace class = "Alpha Blocker" if strmatch(upper(drug), "DOXAZOSIN*")
replace class = "Alpha Blocker" if strmatch(upper(drug), "PHENOXYBENZAMINE*")
replace class = "Alpha Blocker" if strmatch(upper(drug), "PHENTOLAMINE*")
replace class = "Alpha Blocker" if strmatch(upper(drug), "PRAZOSIN*")
replace class = "Alpha Blocker" if strmatch(upper(drug), "TAMSULOSIN*")
replace class = "Alpha Blocker" if strmatch(upper(drug), "TERAZOSIN*")
replace class = "Alpha/Beta Blocker" if strmatch(upper(drug), "CARVEDILOL*")
replace class = "Alpha/Beta Blocker" if strmatch(upper(drug), "LABETALOL*")
replace class = "Alpha-1 Agonist" if strmatch(upper(drug), "PHENYLEPHRINE*")
replace class = "Alpha-1 Agonist" if strmatch(upper(drug), "MIDODRINE*")
replace class = "Alpha-2 Agonist" if strmatch(upper(drug), "CLONIDINE*")
replace class = "Alpha-2 Agonist" if strmatch(upper(drug), "DEXMEDETOMIDINE*")
replace class = "Anaesthetic, general" if strmatch(upper(drug), "KETAMINE*")
replace class = "Anaesthetic, general" if strmatch(upper(drug), "THIOPENTAL*")
replace class = "Anaesthetic, local" if strmatch(upper(drug), "BENZOCAINE*")
replace class = "Anaesthetic, local" if strmatch(upper(drug), "BUPIVACAINE*")
replace class = "Anaesthetic, local" if strmatch(upper(drug), "BUPIVACAINE/FENTANYL*")
replace class = "Anaesthetic, local" if strmatch(upper(drug), "TETRACAINE*")
replace class = "Anaesthetic, local" if strmatch(upper(drug), "XYLOCAINE*")
replace class = "Anaesthetic, local/Antiarrythmic" if strmatch(upper(drug), "LIDOCAINE*")
replace class = "Anaesthetic, local/Antiseptic" if strmatch(upper(drug), "HEXYLRESORCINOL*")
replace class = "Anaesthetic, topical" if strmatch(upper(drug), "LIDOCAINE/PRILOCAINE*")
replace class = "Anaesthetic, topical" if strmatch(upper(drug), "PROPARACAINE*")
replace class = "Analgesic" if strmatch(upper(drug), "ACETAMINOPHEN*")
replace class = "Analgesic" if strmatch(upper(drug), "BELLADONNA & OPIUM SUPPOSITORY*")
```
I want to do the same classification in R but I do not know Stata.
Note that drugs can have more than one `class`.
Any advice and help would be greatly appreciated. | 2018/05/09 | [
"https://Stackoverflow.com/questions/50256184",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Change the code with:
```
[Unit]
Description=Atlassian Bamboo Agent
After=syslog.target network.target
[Service]
Type=forking
User=apps
Group=apps
ExecStart=/apps/bamboo-agent/bin/bamboo-agent.sh start
ExecStop=/apps/bamboo-agent/bin/bamboo-agent.sh stop
[Install]
WantedBy=multi-user.target
```
Then reload and start it (as root or using sudo)
```
systemctl daemon-reload
systemctl start bamboo-agent
```
Res: <https://community.atlassian.com/t5/Bamboo-questions/How-to-I-install-bamboo-agent-as-a-daemon-under-Linux/qaq-p/393880> | Once you've run the agent for the first time it will create control scripts to install and manage the service.
So after running:
```
java -jar atlassian-bamboo-agent-installer-6.10.4.jar ...
```
Stop the agent and run:
```
sudo ./bamboo-agent-home/bin/bamboo-agent.sh install
```
Then you can control it with:
```
sudo service bamboo-agent [start|stop|restart|status]
```
Or you can call the agent script directly. Run the below to see all possible commands:
```
sudo ./bamboo-agent-home/bin/bamboo-agent.sh
```
The following command is useful to diagnose startup issues:
```
sudo ./bamboo-agent-home/bin/bamboo-agent.sh console
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.