qid
int64
1
74.7M
question
stringlengths
15
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
4
30.2k
response_k
stringlengths
11
36.5k
25,359,358
I have a question around the topic Generics in Java: Let's say I have following generic (static) method in class. In this method, I want to have access to certain method/fields of the real class. Is there some typesafe way in the static language Java? Or are there any workarounds? ``` public class GenericClassUtil { public static <T> void workWithRealTypeAttr(T objectClass) { //here get access to values of Easel, Cat, Dog or some other class } } ``` In main code: ------------- ``` GenericClassUtil.workWithRealTypeAttr(new Easel()); GenericClassUtil.workWithRealTypeAttr(new Cat()); GenericClassUtil.workWithRealTypeAttr(new Dog()); ```
2014/08/18
[ "https://Stackoverflow.com/questions/25359358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1625596/" ]
Create an Interface and extend `Easel`, `Cat`, `Dog` class to that interface. ``` public static <T extends ThatInterface> workWithRealTypeAttr(T objectClass) { //here get access to values of Easel, Cat, Dog or some other class } ``` [Ref:](http://docs.oracle.com/javase/tutorial/java/generics/bounded.html) > > There may be times when you want to restrict the types that can be used as type arguments in a parameterized type. For example, a method that operates on numbers might only want to accept instances of Number or its subclasses. This is what *bounded type parameters* are for. > > > To declare a bounded type parameter, list the type parameter's name, followed by the extends keyword, followed by its upper bound, which in this example is Number. Note that, in this context, extends is used in a general sense to mean either "extends" (as in classes) or "implements" (as in interfaces). > > > ``` public class Box<T> { private T t; public void set(T t) { this.t = t; } public T get() { return t; } public <U extends Number> void inspect(U u){ System.out.println("T: " + t.getClass().getName()); System.out.println("U: " + u.getClass().getName()); } public static void main(String[] args) { Box<Integer> integerBox = new Box<Integer>(); integerBox.set(new Integer(10)); integerBox.inspect("some text"); // error: this is still String! } } ```
The only way you can do is let all your classes implements a common interface and keep one common method in that interface. And you have to specify bounds for your T like (Considering Animal is the super class for all your mentioned class) Then you can access t.commonMethod() inside For example Have interface like ``` public interface Animal { void commonMethod(); } ``` Inside your method ``` <T extends Animal> tryWithGenerics(T t) { t.commonMethod(): //call like this } ``` **Note :** All your classes should implement that Animal interface
25,359,358
I have a question around the topic Generics in Java: Let's say I have following generic (static) method in class. In this method, I want to have access to certain method/fields of the real class. Is there some typesafe way in the static language Java? Or are there any workarounds? ``` public class GenericClassUtil { public static <T> void workWithRealTypeAttr(T objectClass) { //here get access to values of Easel, Cat, Dog or some other class } } ``` In main code: ------------- ``` GenericClassUtil.workWithRealTypeAttr(new Easel()); GenericClassUtil.workWithRealTypeAttr(new Cat()); GenericClassUtil.workWithRealTypeAttr(new Dog()); ```
2014/08/18
[ "https://Stackoverflow.com/questions/25359358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1625596/" ]
Create an Interface and extend `Easel`, `Cat`, `Dog` class to that interface. ``` public static <T extends ThatInterface> workWithRealTypeAttr(T objectClass) { //here get access to values of Easel, Cat, Dog or some other class } ``` [Ref:](http://docs.oracle.com/javase/tutorial/java/generics/bounded.html) > > There may be times when you want to restrict the types that can be used as type arguments in a parameterized type. For example, a method that operates on numbers might only want to accept instances of Number or its subclasses. This is what *bounded type parameters* are for. > > > To declare a bounded type parameter, list the type parameter's name, followed by the extends keyword, followed by its upper bound, which in this example is Number. Note that, in this context, extends is used in a general sense to mean either "extends" (as in classes) or "implements" (as in interfaces). > > > ``` public class Box<T> { private T t; public void set(T t) { this.t = t; } public T get() { return t; } public <U extends Number> void inspect(U u){ System.out.println("T: " + t.getClass().getName()); System.out.println("U: " + u.getClass().getName()); } public static void main(String[] args) { Box<Integer> integerBox = new Box<Integer>(); integerBox.set(new Integer(10)); integerBox.inspect("some text"); // error: this is still String! } } ```
You can do if you limit the generic type to classes that extend a certain base class. For example if your method only operates on `Animal` class then you would have: ``` public static <T extends Animal> workWithRealTypeAttr(T objectClass) { objectClass.someAnimalMethod() } public class Animal { public void someAnimalMethod() { } } ``` Each one of `Easel`, `Cat` and `Dog` would have to extend `Animal`. Trying to call `workWithRealTypeAttr` with an argument that does not extend `Animal` would result in a **compile** time error. You can of course offer yourself even more flexibility by using interfaces instead of classes. Generics would work in exactly the same way. You would just have an interface `Animal` and the classes `Easel`, `Cat` and `Dog` would implement that interface. **NOTE** As @user3218114 very correctly points out, there is no need to use generics in this simple case. You can just go with `Animal` as an argument to `workWithRealTypeAttr`. But I did not post that answer because I wanted to show OP how generics can work in the case he/she presented. The solution would obviously be more applicable if the method worked on Collection or something else that could take full advantage of generics.
25,359,358
I have a question around the topic Generics in Java: Let's say I have following generic (static) method in class. In this method, I want to have access to certain method/fields of the real class. Is there some typesafe way in the static language Java? Or are there any workarounds? ``` public class GenericClassUtil { public static <T> void workWithRealTypeAttr(T objectClass) { //here get access to values of Easel, Cat, Dog or some other class } } ``` In main code: ------------- ``` GenericClassUtil.workWithRealTypeAttr(new Easel()); GenericClassUtil.workWithRealTypeAttr(new Cat()); GenericClassUtil.workWithRealTypeAttr(new Dog()); ```
2014/08/18
[ "https://Stackoverflow.com/questions/25359358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1625596/" ]
You can do if you limit the generic type to classes that extend a certain base class. For example if your method only operates on `Animal` class then you would have: ``` public static <T extends Animal> workWithRealTypeAttr(T objectClass) { objectClass.someAnimalMethod() } public class Animal { public void someAnimalMethod() { } } ``` Each one of `Easel`, `Cat` and `Dog` would have to extend `Animal`. Trying to call `workWithRealTypeAttr` with an argument that does not extend `Animal` would result in a **compile** time error. You can of course offer yourself even more flexibility by using interfaces instead of classes. Generics would work in exactly the same way. You would just have an interface `Animal` and the classes `Easel`, `Cat` and `Dog` would implement that interface. **NOTE** As @user3218114 very correctly points out, there is no need to use generics in this simple case. You can just go with `Animal` as an argument to `workWithRealTypeAttr`. But I did not post that answer because I wanted to show OP how generics can work in the case he/she presented. The solution would obviously be more applicable if the method worked on Collection or something else that could take full advantage of generics.
Although it's not elegant you could use construction as below. You can try using instanceof and casting. ``` public static <T> workWithRealTypeAttr(T objectClass) { if (objectClass instanceof Easel) { ((Easel) objectClass).toSomehtingEaselsDo()); } elseif (objectClass instanceof Cat) { ((Cat) objectClass).toSomehtingCatsDo()); } elseif (objectClass instanceof Dog) { ((Dog) objectClass).toSomehtingDogsDo()); } else { //do something to inform about not supported class. } } ``` The other way may be using a common interface (as suggested in other answers) `<T extends yourInterface>` or a Decorator pattern.
25,359,358
I have a question around the topic Generics in Java: Let's say I have following generic (static) method in class. In this method, I want to have access to certain method/fields of the real class. Is there some typesafe way in the static language Java? Or are there any workarounds? ``` public class GenericClassUtil { public static <T> void workWithRealTypeAttr(T objectClass) { //here get access to values of Easel, Cat, Dog or some other class } } ``` In main code: ------------- ``` GenericClassUtil.workWithRealTypeAttr(new Easel()); GenericClassUtil.workWithRealTypeAttr(new Cat()); GenericClassUtil.workWithRealTypeAttr(new Dog()); ```
2014/08/18
[ "https://Stackoverflow.com/questions/25359358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1625596/" ]
> > I want to have access to certain method/fields of the real class > > > If you want to access method/fields of the real class then use different **overloaded methods** ``` class GenericClassUtil { public static void workWithRealTypeAttr(Bird objectClass) { // call a method specific to Bird (Easel) } public static void workWithRealTypeAttr(Mammal objectClass) { // call a method specific to Mammal (Cat, Dog etc) } } ``` You can groups classes as Mammal, Bird and make the method more generic. ![enter image description here](https://i.stack.imgur.com/QE4kE.png) --- You can group classes based on behavior as per design pattern. ``` class GenericClassUtil { public static void workWithRealTypeAttr(Flyable objectClass) { // call a method specific to Flyable } public static void workWithRealTypeAttr(Swimmable objectClass) { // call a method specific to Swimmable } } interface Swimmable { public void swim() } interface Flyable { public void fly() } ``` ![enter image description here](https://i.stack.imgur.com/fRjYx.png) It's better explained in [Head First Design Pattern](http://uet.vnu.edu.vn/%7Echauttm/e-books/java/Head-First-Java-2nd-edition.pdf)
Yes you can. There are two (or more) ways to achieve it. You can use Animal interface/class and use wildcard like this: ``` public static <T extends Animal> void makeAnimalEat(T animal) { animal.eat(); } ``` or use reflection like this: ``` public static <T> void makeAnimalEatReflection(T animal) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { animal.getClass().getMethod("eat").invoke(animal); } ``` Where Animal is interface: ``` interface Animal{ void eat(); } ``` For additional information about generic and wildcards you can visit <http://docs.oracle.com/javase/tutorial/extra/generics/wildcards.html>
25,359,358
I have a question around the topic Generics in Java: Let's say I have following generic (static) method in class. In this method, I want to have access to certain method/fields of the real class. Is there some typesafe way in the static language Java? Or are there any workarounds? ``` public class GenericClassUtil { public static <T> void workWithRealTypeAttr(T objectClass) { //here get access to values of Easel, Cat, Dog or some other class } } ``` In main code: ------------- ``` GenericClassUtil.workWithRealTypeAttr(new Easel()); GenericClassUtil.workWithRealTypeAttr(new Cat()); GenericClassUtil.workWithRealTypeAttr(new Dog()); ```
2014/08/18
[ "https://Stackoverflow.com/questions/25359358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1625596/" ]
> > I want to have access to certain method/fields of the real class > > > If you want to access method/fields of the real class then use different **overloaded methods** ``` class GenericClassUtil { public static void workWithRealTypeAttr(Bird objectClass) { // call a method specific to Bird (Easel) } public static void workWithRealTypeAttr(Mammal objectClass) { // call a method specific to Mammal (Cat, Dog etc) } } ``` You can groups classes as Mammal, Bird and make the method more generic. ![enter image description here](https://i.stack.imgur.com/QE4kE.png) --- You can group classes based on behavior as per design pattern. ``` class GenericClassUtil { public static void workWithRealTypeAttr(Flyable objectClass) { // call a method specific to Flyable } public static void workWithRealTypeAttr(Swimmable objectClass) { // call a method specific to Swimmable } } interface Swimmable { public void swim() } interface Flyable { public void fly() } ``` ![enter image description here](https://i.stack.imgur.com/fRjYx.png) It's better explained in [Head First Design Pattern](http://uet.vnu.edu.vn/%7Echauttm/e-books/java/Head-First-Java-2nd-edition.pdf)
The only way you can do is let all your classes implements a common interface and keep one common method in that interface. And you have to specify bounds for your T like (Considering Animal is the super class for all your mentioned class) Then you can access t.commonMethod() inside For example Have interface like ``` public interface Animal { void commonMethod(); } ``` Inside your method ``` <T extends Animal> tryWithGenerics(T t) { t.commonMethod(): //call like this } ``` **Note :** All your classes should implement that Animal interface
25,359,358
I have a question around the topic Generics in Java: Let's say I have following generic (static) method in class. In this method, I want to have access to certain method/fields of the real class. Is there some typesafe way in the static language Java? Or are there any workarounds? ``` public class GenericClassUtil { public static <T> void workWithRealTypeAttr(T objectClass) { //here get access to values of Easel, Cat, Dog or some other class } } ``` In main code: ------------- ``` GenericClassUtil.workWithRealTypeAttr(new Easel()); GenericClassUtil.workWithRealTypeAttr(new Cat()); GenericClassUtil.workWithRealTypeAttr(new Dog()); ```
2014/08/18
[ "https://Stackoverflow.com/questions/25359358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1625596/" ]
You can do if you limit the generic type to classes that extend a certain base class. For example if your method only operates on `Animal` class then you would have: ``` public static <T extends Animal> workWithRealTypeAttr(T objectClass) { objectClass.someAnimalMethod() } public class Animal { public void someAnimalMethod() { } } ``` Each one of `Easel`, `Cat` and `Dog` would have to extend `Animal`. Trying to call `workWithRealTypeAttr` with an argument that does not extend `Animal` would result in a **compile** time error. You can of course offer yourself even more flexibility by using interfaces instead of classes. Generics would work in exactly the same way. You would just have an interface `Animal` and the classes `Easel`, `Cat` and `Dog` would implement that interface. **NOTE** As @user3218114 very correctly points out, there is no need to use generics in this simple case. You can just go with `Animal` as an argument to `workWithRealTypeAttr`. But I did not post that answer because I wanted to show OP how generics can work in the case he/she presented. The solution would obviously be more applicable if the method worked on Collection or something else that could take full advantage of generics.
The only way you can do is let all your classes implements a common interface and keep one common method in that interface. And you have to specify bounds for your T like (Considering Animal is the super class for all your mentioned class) Then you can access t.commonMethod() inside For example Have interface like ``` public interface Animal { void commonMethod(); } ``` Inside your method ``` <T extends Animal> tryWithGenerics(T t) { t.commonMethod(): //call like this } ``` **Note :** All your classes should implement that Animal interface
25,359,358
I have a question around the topic Generics in Java: Let's say I have following generic (static) method in class. In this method, I want to have access to certain method/fields of the real class. Is there some typesafe way in the static language Java? Or are there any workarounds? ``` public class GenericClassUtil { public static <T> void workWithRealTypeAttr(T objectClass) { //here get access to values of Easel, Cat, Dog or some other class } } ``` In main code: ------------- ``` GenericClassUtil.workWithRealTypeAttr(new Easel()); GenericClassUtil.workWithRealTypeAttr(new Cat()); GenericClassUtil.workWithRealTypeAttr(new Dog()); ```
2014/08/18
[ "https://Stackoverflow.com/questions/25359358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1625596/" ]
Create an Interface and extend `Easel`, `Cat`, `Dog` class to that interface. ``` public static <T extends ThatInterface> workWithRealTypeAttr(T objectClass) { //here get access to values of Easel, Cat, Dog or some other class } ``` [Ref:](http://docs.oracle.com/javase/tutorial/java/generics/bounded.html) > > There may be times when you want to restrict the types that can be used as type arguments in a parameterized type. For example, a method that operates on numbers might only want to accept instances of Number or its subclasses. This is what *bounded type parameters* are for. > > > To declare a bounded type parameter, list the type parameter's name, followed by the extends keyword, followed by its upper bound, which in this example is Number. Note that, in this context, extends is used in a general sense to mean either "extends" (as in classes) or "implements" (as in interfaces). > > > ``` public class Box<T> { private T t; public void set(T t) { this.t = t; } public T get() { return t; } public <U extends Number> void inspect(U u){ System.out.println("T: " + t.getClass().getName()); System.out.println("U: " + u.getClass().getName()); } public static void main(String[] args) { Box<Integer> integerBox = new Box<Integer>(); integerBox.set(new Integer(10)); integerBox.inspect("some text"); // error: this is still String! } } ```
Yes you can. There are two (or more) ways to achieve it. You can use Animal interface/class and use wildcard like this: ``` public static <T extends Animal> void makeAnimalEat(T animal) { animal.eat(); } ``` or use reflection like this: ``` public static <T> void makeAnimalEatReflection(T animal) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { animal.getClass().getMethod("eat").invoke(animal); } ``` Where Animal is interface: ``` interface Animal{ void eat(); } ``` For additional information about generic and wildcards you can visit <http://docs.oracle.com/javase/tutorial/extra/generics/wildcards.html>
788,161
I can set the screen resolution manually once I log in using the following command: ``` xrandr -s 1360x768 ``` but I am not able to make it "stick". Every time I log back in, the resolution for a little while changes to 1360x768, but by the time the desktop appears, switches back to 800x600. I have also tried other versions of the command, if that matters. For example, `xrandr --output Virtual1 --mode 1360x768`. It works as long as I don't exit the current session, but switches back to 800x600 when I log back in. I have tried the following: 1. Placed the command in a `/etc/lightdm/lightdm.conf`, but this causes the entire GUI to fail to appear. 2. Edited `~/.xprofile` to run the command to set the screen resolution, but this doesn't work. 3. Installed open-vm-tools and made sure it is up to date. 4. Disabled 3D acceleration in the VM's settings as was suggested in another answer. This made no difference at all. 5. Added the `xrandr` command into my `~/.bashrc`. This causes the correct resolution to be set everytime I open up a terminal, but this solution is kludgy. I don't want to have to open a terminal to have my screen resolution properly set. Any ideas what else could be done? Thanks in advance! Edit: I am using VMware Workstation 12 Player, version 12.1.1 (build-3770994)
2016/06/17
[ "https://askubuntu.com/questions/788161", "https://askubuntu.com", "https://askubuntu.com/users/242805/" ]
If you are using Ubuntu on VMWare Workstation, you need to install **`VMWare tools`** to get proper resolution. Here is the step by step procedure to do that : * Start your Virtual machine and login to your Ubuntu. * Go to **VM** --> **Install VMWare Tools...** [![enter image description here](https://i.stack.imgur.com/O89Z9.png)](https://i.stack.imgur.com/O89Z9.png) * Click on `install` * Now you should see a Virtual CD named "VMWare tools" mounted in your Ubuntu. Copy the **`VMWareTools-xx.xx.xx.xxxxx.tar.gz`** to your home Directory . * Extract it [![enter image description here](https://i.stack.imgur.com/9j15V.png)](https://i.stack.imgur.com/9j15V.png) * Go to the extracted folder in a terminal : ``` cd ~/vmware-tools-distrib ``` * Provide execution permission for `vmware-install.pl` ``` chmod +x vmware-install.pl ``` * Execute it with superuser privileges . ``` sudo ./vmware-install.pl ``` * Enter your password. When asked for confirmation type **`yes`** and press `Enter`. If you wish to install with default settings, keep pressing `Enter` for the next messages, which are : + While doing the below procedure Press `Enter` when asked "Need to create..... This is what you want ?" + Default Directory `/usr/bin` + Default Directory containing init directories `/etc` + Default Directory with init scripts : `/etc/init.d` + Default Directory Demon files : `/usr/sbin` + Default Directory for library files : `/usr/lib/vmware-tools` + Default Directory for common agent library files : `/usr/lib` + Default Directory for common agent transient files : `/var/lib` + Default Directory for documentation files : `/usr/share/doc/vmware-tools` * Press `Enter` when asked if you want to invoke `/usr/bin/vmware-config-tools.pl` * Press `Enter` for all other queries. * Now **restart** your Ubuntu. Setting proper Resolution. -------------------------- * After restart, go to **System Settings --> Displays --> Resolution** and select your preferred resolution and click `Apply` and followed by `Keep this Configuration` [![enter image description here](https://i.stack.imgur.com/CrVk9.png)](https://i.stack.imgur.com/CrVk9.png) Thats all **;-)** . Restart and you will see its 1366x768 by default **:-)**
Edit your VMX to include: ``` vga.guestBackedPrimaryAware = "FALSE" svga.minVRAMSize = "16777216" ``` notes: * Tested with Xubuntu 16.04 with kernel version 4.4.0-77 in VMWare Fusion 8.5.6 at 1920x1200 * This may be a problem with the combination of kernel version (4.4.0-77 in my case) and virtualHW.version (see ref. #1) and may indicate a bug (see ref. #2) * My VM is pegged at `virtualHW.version = "11"` references: 1. <https://unix.stackexchange.com/questions/301531/ubuntu-server-stopped-running-in-higher-resolution> 2. <https://github.com/vmware/open-vm-tools/issues/54>
788,161
I can set the screen resolution manually once I log in using the following command: ``` xrandr -s 1360x768 ``` but I am not able to make it "stick". Every time I log back in, the resolution for a little while changes to 1360x768, but by the time the desktop appears, switches back to 800x600. I have also tried other versions of the command, if that matters. For example, `xrandr --output Virtual1 --mode 1360x768`. It works as long as I don't exit the current session, but switches back to 800x600 when I log back in. I have tried the following: 1. Placed the command in a `/etc/lightdm/lightdm.conf`, but this causes the entire GUI to fail to appear. 2. Edited `~/.xprofile` to run the command to set the screen resolution, but this doesn't work. 3. Installed open-vm-tools and made sure it is up to date. 4. Disabled 3D acceleration in the VM's settings as was suggested in another answer. This made no difference at all. 5. Added the `xrandr` command into my `~/.bashrc`. This causes the correct resolution to be set everytime I open up a terminal, but this solution is kludgy. I don't want to have to open a terminal to have my screen resolution properly set. Any ideas what else could be done? Thanks in advance! Edit: I am using VMware Workstation 12 Player, version 12.1.1 (build-3770994)
2016/06/17
[ "https://askubuntu.com/questions/788161", "https://askubuntu.com", "https://askubuntu.com/users/242805/" ]
I had the same problem, annoying but finally fixed using a variation of the first suggested answer above. I'm running Ubuntu 16.04.3 on Fusion 8.5.8 with HW version 12. Within Fusion display settings: 1. "Use full resolution for Retina Display" should be checked 2. "Use Fusion Display Preferences" set for both "Single Window" and "Full Screen". Fusion is running on MacOS 10.12.6 on MacBook Pro with Display Preferences set to "Default for Display" 1. `sudo apt-get autoremove open-vm-tools` 2. Install Fusion's VMware tools as `root` 3. Reboot I noticed after the reboot everything looked perfect, came back up with my 1920x1200 resolution but continued with the suggested final steps: 1. `sudo apt-get install open-vm-tools-desktop` 2. Reboot Came back up with the tiny 2560x1600, changed and saved to my preferred resolution and logged out and back in (actually just jumped back to my Mac desktop and back again as that would revert the settings as well) and Ubuntu reverted to the 2560x1600. So the final fix while in this state (running only VMware's tools with `open-vm-tools-desktop`) is the following: 1. `sudo apt-get autoremove open-vm-tools-desktop` 2. Run an install of VMware's tools over the existing (step one removed some required libraries and drivers) 3. Reboot Works like a charm and so far haven't noticed anything missing or lost functionality due to not having the open desktop tools installed, seems that VMware's tools give you everything you need and works.
Edit your VMX to include: ``` vga.guestBackedPrimaryAware = "FALSE" svga.minVRAMSize = "16777216" ``` notes: * Tested with Xubuntu 16.04 with kernel version 4.4.0-77 in VMWare Fusion 8.5.6 at 1920x1200 * This may be a problem with the combination of kernel version (4.4.0-77 in my case) and virtualHW.version (see ref. #1) and may indicate a bug (see ref. #2) * My VM is pegged at `virtualHW.version = "11"` references: 1. <https://unix.stackexchange.com/questions/301531/ubuntu-server-stopped-running-in-higher-resolution> 2. <https://github.com/vmware/open-vm-tools/issues/54>
788,161
I can set the screen resolution manually once I log in using the following command: ``` xrandr -s 1360x768 ``` but I am not able to make it "stick". Every time I log back in, the resolution for a little while changes to 1360x768, but by the time the desktop appears, switches back to 800x600. I have also tried other versions of the command, if that matters. For example, `xrandr --output Virtual1 --mode 1360x768`. It works as long as I don't exit the current session, but switches back to 800x600 when I log back in. I have tried the following: 1. Placed the command in a `/etc/lightdm/lightdm.conf`, but this causes the entire GUI to fail to appear. 2. Edited `~/.xprofile` to run the command to set the screen resolution, but this doesn't work. 3. Installed open-vm-tools and made sure it is up to date. 4. Disabled 3D acceleration in the VM's settings as was suggested in another answer. This made no difference at all. 5. Added the `xrandr` command into my `~/.bashrc`. This causes the correct resolution to be set everytime I open up a terminal, but this solution is kludgy. I don't want to have to open a terminal to have my screen resolution properly set. Any ideas what else could be done? Thanks in advance! Edit: I am using VMware Workstation 12 Player, version 12.1.1 (build-3770994)
2016/06/17
[ "https://askubuntu.com/questions/788161", "https://askubuntu.com", "https://askubuntu.com/users/242805/" ]
If you are using Ubuntu on VMWare Workstation, you need to install **`VMWare tools`** to get proper resolution. Here is the step by step procedure to do that : * Start your Virtual machine and login to your Ubuntu. * Go to **VM** --> **Install VMWare Tools...** [![enter image description here](https://i.stack.imgur.com/O89Z9.png)](https://i.stack.imgur.com/O89Z9.png) * Click on `install` * Now you should see a Virtual CD named "VMWare tools" mounted in your Ubuntu. Copy the **`VMWareTools-xx.xx.xx.xxxxx.tar.gz`** to your home Directory . * Extract it [![enter image description here](https://i.stack.imgur.com/9j15V.png)](https://i.stack.imgur.com/9j15V.png) * Go to the extracted folder in a terminal : ``` cd ~/vmware-tools-distrib ``` * Provide execution permission for `vmware-install.pl` ``` chmod +x vmware-install.pl ``` * Execute it with superuser privileges . ``` sudo ./vmware-install.pl ``` * Enter your password. When asked for confirmation type **`yes`** and press `Enter`. If you wish to install with default settings, keep pressing `Enter` for the next messages, which are : + While doing the below procedure Press `Enter` when asked "Need to create..... This is what you want ?" + Default Directory `/usr/bin` + Default Directory containing init directories `/etc` + Default Directory with init scripts : `/etc/init.d` + Default Directory Demon files : `/usr/sbin` + Default Directory for library files : `/usr/lib/vmware-tools` + Default Directory for common agent library files : `/usr/lib` + Default Directory for common agent transient files : `/var/lib` + Default Directory for documentation files : `/usr/share/doc/vmware-tools` * Press `Enter` when asked if you want to invoke `/usr/bin/vmware-config-tools.pl` * Press `Enter` for all other queries. * Now **restart** your Ubuntu. Setting proper Resolution. -------------------------- * After restart, go to **System Settings --> Displays --> Resolution** and select your preferred resolution and click `Apply` and followed by `Keep this Configuration` [![enter image description here](https://i.stack.imgur.com/CrVk9.png)](https://i.stack.imgur.com/CrVk9.png) Thats all **;-)** . Restart and you will see its 1366x768 by default **:-)**
Changing the resolution requires the VMWare Tools, or the open source equivalents. I've found the Open Source versions to work a little better than the compile-them versions that ship with VMWare Workstation. Install the Open VM Tools, with the following commands. Note that if you've installed the VMware Tools already you need to uninstall those first. ``` sudo apt-get install open-vm-tools open-vm-tools-desktop ``` Once this is done *fully shut down the VM, then start it up again in Workstation*. You can then see a larger set of resolutions in the GUI as you would for a standard computer, or use VMware Workstation's "Autofit Guest" and "Fit Guest Now" options with the Desktop Open VM Tools to autoadjust the resolution. This is confirmed working on VMware Workstation machines, as well as VMware ESXi virtual machines accessed via VMware Workstation, on Ubuntu, Lubuntu, Xubuntu, and Kubuntu 16.04 LTS machines that I personally have been running, and it works nearly flawlessly (make sure you give enough vRAM to the VMs, because it takes the Video RAM from that virtual RAM allocation you give by default...)
788,161
I can set the screen resolution manually once I log in using the following command: ``` xrandr -s 1360x768 ``` but I am not able to make it "stick". Every time I log back in, the resolution for a little while changes to 1360x768, but by the time the desktop appears, switches back to 800x600. I have also tried other versions of the command, if that matters. For example, `xrandr --output Virtual1 --mode 1360x768`. It works as long as I don't exit the current session, but switches back to 800x600 when I log back in. I have tried the following: 1. Placed the command in a `/etc/lightdm/lightdm.conf`, but this causes the entire GUI to fail to appear. 2. Edited `~/.xprofile` to run the command to set the screen resolution, but this doesn't work. 3. Installed open-vm-tools and made sure it is up to date. 4. Disabled 3D acceleration in the VM's settings as was suggested in another answer. This made no difference at all. 5. Added the `xrandr` command into my `~/.bashrc`. This causes the correct resolution to be set everytime I open up a terminal, but this solution is kludgy. I don't want to have to open a terminal to have my screen resolution properly set. Any ideas what else could be done? Thanks in advance! Edit: I am using VMware Workstation 12 Player, version 12.1.1 (build-3770994)
2016/06/17
[ "https://askubuntu.com/questions/788161", "https://askubuntu.com", "https://askubuntu.com/users/242805/" ]
Changing the resolution requires the VMWare Tools, or the open source equivalents. I've found the Open Source versions to work a little better than the compile-them versions that ship with VMWare Workstation. Install the Open VM Tools, with the following commands. Note that if you've installed the VMware Tools already you need to uninstall those first. ``` sudo apt-get install open-vm-tools open-vm-tools-desktop ``` Once this is done *fully shut down the VM, then start it up again in Workstation*. You can then see a larger set of resolutions in the GUI as you would for a standard computer, or use VMware Workstation's "Autofit Guest" and "Fit Guest Now" options with the Desktop Open VM Tools to autoadjust the resolution. This is confirmed working on VMware Workstation machines, as well as VMware ESXi virtual machines accessed via VMware Workstation, on Ubuntu, Lubuntu, Xubuntu, and Kubuntu 16.04 LTS machines that I personally have been running, and it works nearly flawlessly (make sure you give enough vRAM to the VMs, because it takes the Video RAM from that virtual RAM allocation you give by default...)
I had the same problem, annoying but finally fixed using a variation of the first suggested answer above. I'm running Ubuntu 16.04.3 on Fusion 8.5.8 with HW version 12. Within Fusion display settings: 1. "Use full resolution for Retina Display" should be checked 2. "Use Fusion Display Preferences" set for both "Single Window" and "Full Screen". Fusion is running on MacOS 10.12.6 on MacBook Pro with Display Preferences set to "Default for Display" 1. `sudo apt-get autoremove open-vm-tools` 2. Install Fusion's VMware tools as `root` 3. Reboot I noticed after the reboot everything looked perfect, came back up with my 1920x1200 resolution but continued with the suggested final steps: 1. `sudo apt-get install open-vm-tools-desktop` 2. Reboot Came back up with the tiny 2560x1600, changed and saved to my preferred resolution and logged out and back in (actually just jumped back to my Mac desktop and back again as that would revert the settings as well) and Ubuntu reverted to the 2560x1600. So the final fix while in this state (running only VMware's tools with `open-vm-tools-desktop`) is the following: 1. `sudo apt-get autoremove open-vm-tools-desktop` 2. Run an install of VMware's tools over the existing (step one removed some required libraries and drivers) 3. Reboot Works like a charm and so far haven't noticed anything missing or lost functionality due to not having the open desktop tools installed, seems that VMware's tools give you everything you need and works.
788,161
I can set the screen resolution manually once I log in using the following command: ``` xrandr -s 1360x768 ``` but I am not able to make it "stick". Every time I log back in, the resolution for a little while changes to 1360x768, but by the time the desktop appears, switches back to 800x600. I have also tried other versions of the command, if that matters. For example, `xrandr --output Virtual1 --mode 1360x768`. It works as long as I don't exit the current session, but switches back to 800x600 when I log back in. I have tried the following: 1. Placed the command in a `/etc/lightdm/lightdm.conf`, but this causes the entire GUI to fail to appear. 2. Edited `~/.xprofile` to run the command to set the screen resolution, but this doesn't work. 3. Installed open-vm-tools and made sure it is up to date. 4. Disabled 3D acceleration in the VM's settings as was suggested in another answer. This made no difference at all. 5. Added the `xrandr` command into my `~/.bashrc`. This causes the correct resolution to be set everytime I open up a terminal, but this solution is kludgy. I don't want to have to open a terminal to have my screen resolution properly set. Any ideas what else could be done? Thanks in advance! Edit: I am using VMware Workstation 12 Player, version 12.1.1 (build-3770994)
2016/06/17
[ "https://askubuntu.com/questions/788161", "https://askubuntu.com", "https://askubuntu.com/users/242805/" ]
If you are using Ubuntu on VMWare Workstation, you need to install **`VMWare tools`** to get proper resolution. Here is the step by step procedure to do that : * Start your Virtual machine and login to your Ubuntu. * Go to **VM** --> **Install VMWare Tools...** [![enter image description here](https://i.stack.imgur.com/O89Z9.png)](https://i.stack.imgur.com/O89Z9.png) * Click on `install` * Now you should see a Virtual CD named "VMWare tools" mounted in your Ubuntu. Copy the **`VMWareTools-xx.xx.xx.xxxxx.tar.gz`** to your home Directory . * Extract it [![enter image description here](https://i.stack.imgur.com/9j15V.png)](https://i.stack.imgur.com/9j15V.png) * Go to the extracted folder in a terminal : ``` cd ~/vmware-tools-distrib ``` * Provide execution permission for `vmware-install.pl` ``` chmod +x vmware-install.pl ``` * Execute it with superuser privileges . ``` sudo ./vmware-install.pl ``` * Enter your password. When asked for confirmation type **`yes`** and press `Enter`. If you wish to install with default settings, keep pressing `Enter` for the next messages, which are : + While doing the below procedure Press `Enter` when asked "Need to create..... This is what you want ?" + Default Directory `/usr/bin` + Default Directory containing init directories `/etc` + Default Directory with init scripts : `/etc/init.d` + Default Directory Demon files : `/usr/sbin` + Default Directory for library files : `/usr/lib/vmware-tools` + Default Directory for common agent library files : `/usr/lib` + Default Directory for common agent transient files : `/var/lib` + Default Directory for documentation files : `/usr/share/doc/vmware-tools` * Press `Enter` when asked if you want to invoke `/usr/bin/vmware-config-tools.pl` * Press `Enter` for all other queries. * Now **restart** your Ubuntu. Setting proper Resolution. -------------------------- * After restart, go to **System Settings --> Displays --> Resolution** and select your preferred resolution and click `Apply` and followed by `Keep this Configuration` [![enter image description here](https://i.stack.imgur.com/CrVk9.png)](https://i.stack.imgur.com/CrVk9.png) Thats all **;-)** . Restart and you will see its 1366x768 by default **:-)**
Like you, I can't find any way to get it to run on startup, but I did find a way to get it to run on login which was "good enough" for me. I added this to my `~/.profile`: ``` xrandr --newmode "1600x900_60.00" 118.25 1600 1696 1856 2112 900 903 908 934 -hsync +vsync xrandr --addmode Virtual1 1600x900_60.00 xrandr -s 1600x900 ``` You should be able to do the same for your resolution: ``` xrandr --newmode "1360x768_60.00" 84.75 1360 1432 1568 1776 768 771 781 798 -hsync +vsync xrandr --addmode Virtual1 1360x768_60.00 xrandr -s 1360x768 ``` It no longer seems to work on 18.04, though (it changes and then immediately switches back). In that case, add the above to an executable `.sh` file and add a new entry calling it from Ubuntu's *Startup Applications*: ![screenshot](https://i.stack.imgur.com/tLY25.png)
788,161
I can set the screen resolution manually once I log in using the following command: ``` xrandr -s 1360x768 ``` but I am not able to make it "stick". Every time I log back in, the resolution for a little while changes to 1360x768, but by the time the desktop appears, switches back to 800x600. I have also tried other versions of the command, if that matters. For example, `xrandr --output Virtual1 --mode 1360x768`. It works as long as I don't exit the current session, but switches back to 800x600 when I log back in. I have tried the following: 1. Placed the command in a `/etc/lightdm/lightdm.conf`, but this causes the entire GUI to fail to appear. 2. Edited `~/.xprofile` to run the command to set the screen resolution, but this doesn't work. 3. Installed open-vm-tools and made sure it is up to date. 4. Disabled 3D acceleration in the VM's settings as was suggested in another answer. This made no difference at all. 5. Added the `xrandr` command into my `~/.bashrc`. This causes the correct resolution to be set everytime I open up a terminal, but this solution is kludgy. I don't want to have to open a terminal to have my screen resolution properly set. Any ideas what else could be done? Thanks in advance! Edit: I am using VMware Workstation 12 Player, version 12.1.1 (build-3770994)
2016/06/17
[ "https://askubuntu.com/questions/788161", "https://askubuntu.com", "https://askubuntu.com/users/242805/" ]
Changing the resolution requires the VMWare Tools, or the open source equivalents. I've found the Open Source versions to work a little better than the compile-them versions that ship with VMWare Workstation. Install the Open VM Tools, with the following commands. Note that if you've installed the VMware Tools already you need to uninstall those first. ``` sudo apt-get install open-vm-tools open-vm-tools-desktop ``` Once this is done *fully shut down the VM, then start it up again in Workstation*. You can then see a larger set of resolutions in the GUI as you would for a standard computer, or use VMware Workstation's "Autofit Guest" and "Fit Guest Now" options with the Desktop Open VM Tools to autoadjust the resolution. This is confirmed working on VMware Workstation machines, as well as VMware ESXi virtual machines accessed via VMware Workstation, on Ubuntu, Lubuntu, Xubuntu, and Kubuntu 16.04 LTS machines that I personally have been running, and it works nearly flawlessly (make sure you give enough vRAM to the VMs, because it takes the Video RAM from that virtual RAM allocation you give by default...)
Like you, I can't find any way to get it to run on startup, but I did find a way to get it to run on login which was "good enough" for me. I added this to my `~/.profile`: ``` xrandr --newmode "1600x900_60.00" 118.25 1600 1696 1856 2112 900 903 908 934 -hsync +vsync xrandr --addmode Virtual1 1600x900_60.00 xrandr -s 1600x900 ``` You should be able to do the same for your resolution: ``` xrandr --newmode "1360x768_60.00" 84.75 1360 1432 1568 1776 768 771 781 798 -hsync +vsync xrandr --addmode Virtual1 1360x768_60.00 xrandr -s 1360x768 ``` It no longer seems to work on 18.04, though (it changes and then immediately switches back). In that case, add the above to an executable `.sh` file and add a new entry calling it from Ubuntu's *Startup Applications*: ![screenshot](https://i.stack.imgur.com/tLY25.png)
788,161
I can set the screen resolution manually once I log in using the following command: ``` xrandr -s 1360x768 ``` but I am not able to make it "stick". Every time I log back in, the resolution for a little while changes to 1360x768, but by the time the desktop appears, switches back to 800x600. I have also tried other versions of the command, if that matters. For example, `xrandr --output Virtual1 --mode 1360x768`. It works as long as I don't exit the current session, but switches back to 800x600 when I log back in. I have tried the following: 1. Placed the command in a `/etc/lightdm/lightdm.conf`, but this causes the entire GUI to fail to appear. 2. Edited `~/.xprofile` to run the command to set the screen resolution, but this doesn't work. 3. Installed open-vm-tools and made sure it is up to date. 4. Disabled 3D acceleration in the VM's settings as was suggested in another answer. This made no difference at all. 5. Added the `xrandr` command into my `~/.bashrc`. This causes the correct resolution to be set everytime I open up a terminal, but this solution is kludgy. I don't want to have to open a terminal to have my screen resolution properly set. Any ideas what else could be done? Thanks in advance! Edit: I am using VMware Workstation 12 Player, version 12.1.1 (build-3770994)
2016/06/17
[ "https://askubuntu.com/questions/788161", "https://askubuntu.com", "https://askubuntu.com/users/242805/" ]
If you are using Ubuntu on VMWare Workstation, you need to install **`VMWare tools`** to get proper resolution. Here is the step by step procedure to do that : * Start your Virtual machine and login to your Ubuntu. * Go to **VM** --> **Install VMWare Tools...** [![enter image description here](https://i.stack.imgur.com/O89Z9.png)](https://i.stack.imgur.com/O89Z9.png) * Click on `install` * Now you should see a Virtual CD named "VMWare tools" mounted in your Ubuntu. Copy the **`VMWareTools-xx.xx.xx.xxxxx.tar.gz`** to your home Directory . * Extract it [![enter image description here](https://i.stack.imgur.com/9j15V.png)](https://i.stack.imgur.com/9j15V.png) * Go to the extracted folder in a terminal : ``` cd ~/vmware-tools-distrib ``` * Provide execution permission for `vmware-install.pl` ``` chmod +x vmware-install.pl ``` * Execute it with superuser privileges . ``` sudo ./vmware-install.pl ``` * Enter your password. When asked for confirmation type **`yes`** and press `Enter`. If you wish to install with default settings, keep pressing `Enter` for the next messages, which are : + While doing the below procedure Press `Enter` when asked "Need to create..... This is what you want ?" + Default Directory `/usr/bin` + Default Directory containing init directories `/etc` + Default Directory with init scripts : `/etc/init.d` + Default Directory Demon files : `/usr/sbin` + Default Directory for library files : `/usr/lib/vmware-tools` + Default Directory for common agent library files : `/usr/lib` + Default Directory for common agent transient files : `/var/lib` + Default Directory for documentation files : `/usr/share/doc/vmware-tools` * Press `Enter` when asked if you want to invoke `/usr/bin/vmware-config-tools.pl` * Press `Enter` for all other queries. * Now **restart** your Ubuntu. Setting proper Resolution. -------------------------- * After restart, go to **System Settings --> Displays --> Resolution** and select your preferred resolution and click `Apply` and followed by `Keep this Configuration` [![enter image description here](https://i.stack.imgur.com/CrVk9.png)](https://i.stack.imgur.com/CrVk9.png) Thats all **;-)** . Restart and you will see its 1366x768 by default **:-)**
I had the same problem, annoying but finally fixed using a variation of the first suggested answer above. I'm running Ubuntu 16.04.3 on Fusion 8.5.8 with HW version 12. Within Fusion display settings: 1. "Use full resolution for Retina Display" should be checked 2. "Use Fusion Display Preferences" set for both "Single Window" and "Full Screen". Fusion is running on MacOS 10.12.6 on MacBook Pro with Display Preferences set to "Default for Display" 1. `sudo apt-get autoremove open-vm-tools` 2. Install Fusion's VMware tools as `root` 3. Reboot I noticed after the reboot everything looked perfect, came back up with my 1920x1200 resolution but continued with the suggested final steps: 1. `sudo apt-get install open-vm-tools-desktop` 2. Reboot Came back up with the tiny 2560x1600, changed and saved to my preferred resolution and logged out and back in (actually just jumped back to my Mac desktop and back again as that would revert the settings as well) and Ubuntu reverted to the 2560x1600. So the final fix while in this state (running only VMware's tools with `open-vm-tools-desktop`) is the following: 1. `sudo apt-get autoremove open-vm-tools-desktop` 2. Run an install of VMware's tools over the existing (step one removed some required libraries and drivers) 3. Reboot Works like a charm and so far haven't noticed anything missing or lost functionality due to not having the open desktop tools installed, seems that VMware's tools give you everything you need and works.
788,161
I can set the screen resolution manually once I log in using the following command: ``` xrandr -s 1360x768 ``` but I am not able to make it "stick". Every time I log back in, the resolution for a little while changes to 1360x768, but by the time the desktop appears, switches back to 800x600. I have also tried other versions of the command, if that matters. For example, `xrandr --output Virtual1 --mode 1360x768`. It works as long as I don't exit the current session, but switches back to 800x600 when I log back in. I have tried the following: 1. Placed the command in a `/etc/lightdm/lightdm.conf`, but this causes the entire GUI to fail to appear. 2. Edited `~/.xprofile` to run the command to set the screen resolution, but this doesn't work. 3. Installed open-vm-tools and made sure it is up to date. 4. Disabled 3D acceleration in the VM's settings as was suggested in another answer. This made no difference at all. 5. Added the `xrandr` command into my `~/.bashrc`. This causes the correct resolution to be set everytime I open up a terminal, but this solution is kludgy. I don't want to have to open a terminal to have my screen resolution properly set. Any ideas what else could be done? Thanks in advance! Edit: I am using VMware Workstation 12 Player, version 12.1.1 (build-3770994)
2016/06/17
[ "https://askubuntu.com/questions/788161", "https://askubuntu.com", "https://askubuntu.com/users/242805/" ]
I wrote here before, a clean install of ubuntu has no problem with resolution. But after that I found the solution while I was looking for an answer for another problem. Follow the steps below and everything will be fixed. If you have the latest VMware Tools and open-vm-tools is not install, the skip to step 3. 1) `sudo apt-get autoremove open-vm-tools` 2) Install VMware Tools by following the usual method (Virtual Machine --> Reinstall VMWare Tools) 3) Reboot the VM 4) `sudo apt-get install open-vm-tools-desktop` 5) Reboot the VM. Hope this helps. I know how frustrating it is to try and fix this.
I had the same problem, annoying but finally fixed using a variation of the first suggested answer above. I'm running Ubuntu 16.04.3 on Fusion 8.5.8 with HW version 12. Within Fusion display settings: 1. "Use full resolution for Retina Display" should be checked 2. "Use Fusion Display Preferences" set for both "Single Window" and "Full Screen". Fusion is running on MacOS 10.12.6 on MacBook Pro with Display Preferences set to "Default for Display" 1. `sudo apt-get autoremove open-vm-tools` 2. Install Fusion's VMware tools as `root` 3. Reboot I noticed after the reboot everything looked perfect, came back up with my 1920x1200 resolution but continued with the suggested final steps: 1. `sudo apt-get install open-vm-tools-desktop` 2. Reboot Came back up with the tiny 2560x1600, changed and saved to my preferred resolution and logged out and back in (actually just jumped back to my Mac desktop and back again as that would revert the settings as well) and Ubuntu reverted to the 2560x1600. So the final fix while in this state (running only VMware's tools with `open-vm-tools-desktop`) is the following: 1. `sudo apt-get autoremove open-vm-tools-desktop` 2. Run an install of VMware's tools over the existing (step one removed some required libraries and drivers) 3. Reboot Works like a charm and so far haven't noticed anything missing or lost functionality due to not having the open desktop tools installed, seems that VMware's tools give you everything you need and works.
788,161
I can set the screen resolution manually once I log in using the following command: ``` xrandr -s 1360x768 ``` but I am not able to make it "stick". Every time I log back in, the resolution for a little while changes to 1360x768, but by the time the desktop appears, switches back to 800x600. I have also tried other versions of the command, if that matters. For example, `xrandr --output Virtual1 --mode 1360x768`. It works as long as I don't exit the current session, but switches back to 800x600 when I log back in. I have tried the following: 1. Placed the command in a `/etc/lightdm/lightdm.conf`, but this causes the entire GUI to fail to appear. 2. Edited `~/.xprofile` to run the command to set the screen resolution, but this doesn't work. 3. Installed open-vm-tools and made sure it is up to date. 4. Disabled 3D acceleration in the VM's settings as was suggested in another answer. This made no difference at all. 5. Added the `xrandr` command into my `~/.bashrc`. This causes the correct resolution to be set everytime I open up a terminal, but this solution is kludgy. I don't want to have to open a terminal to have my screen resolution properly set. Any ideas what else could be done? Thanks in advance! Edit: I am using VMware Workstation 12 Player, version 12.1.1 (build-3770994)
2016/06/17
[ "https://askubuntu.com/questions/788161", "https://askubuntu.com", "https://askubuntu.com/users/242805/" ]
Like you, I can't find any way to get it to run on startup, but I did find a way to get it to run on login which was "good enough" for me. I added this to my `~/.profile`: ``` xrandr --newmode "1600x900_60.00" 118.25 1600 1696 1856 2112 900 903 908 934 -hsync +vsync xrandr --addmode Virtual1 1600x900_60.00 xrandr -s 1600x900 ``` You should be able to do the same for your resolution: ``` xrandr --newmode "1360x768_60.00" 84.75 1360 1432 1568 1776 768 771 781 798 -hsync +vsync xrandr --addmode Virtual1 1360x768_60.00 xrandr -s 1360x768 ``` It no longer seems to work on 18.04, though (it changes and then immediately switches back). In that case, add the above to an executable `.sh` file and add a new entry calling it from Ubuntu's *Startup Applications*: ![screenshot](https://i.stack.imgur.com/tLY25.png)
Edit your VMX to include: ``` vga.guestBackedPrimaryAware = "FALSE" svga.minVRAMSize = "16777216" ``` notes: * Tested with Xubuntu 16.04 with kernel version 4.4.0-77 in VMWare Fusion 8.5.6 at 1920x1200 * This may be a problem with the combination of kernel version (4.4.0-77 in my case) and virtualHW.version (see ref. #1) and may indicate a bug (see ref. #2) * My VM is pegged at `virtualHW.version = "11"` references: 1. <https://unix.stackexchange.com/questions/301531/ubuntu-server-stopped-running-in-higher-resolution> 2. <https://github.com/vmware/open-vm-tools/issues/54>
788,161
I can set the screen resolution manually once I log in using the following command: ``` xrandr -s 1360x768 ``` but I am not able to make it "stick". Every time I log back in, the resolution for a little while changes to 1360x768, but by the time the desktop appears, switches back to 800x600. I have also tried other versions of the command, if that matters. For example, `xrandr --output Virtual1 --mode 1360x768`. It works as long as I don't exit the current session, but switches back to 800x600 when I log back in. I have tried the following: 1. Placed the command in a `/etc/lightdm/lightdm.conf`, but this causes the entire GUI to fail to appear. 2. Edited `~/.xprofile` to run the command to set the screen resolution, but this doesn't work. 3. Installed open-vm-tools and made sure it is up to date. 4. Disabled 3D acceleration in the VM's settings as was suggested in another answer. This made no difference at all. 5. Added the `xrandr` command into my `~/.bashrc`. This causes the correct resolution to be set everytime I open up a terminal, but this solution is kludgy. I don't want to have to open a terminal to have my screen resolution properly set. Any ideas what else could be done? Thanks in advance! Edit: I am using VMware Workstation 12 Player, version 12.1.1 (build-3770994)
2016/06/17
[ "https://askubuntu.com/questions/788161", "https://askubuntu.com", "https://askubuntu.com/users/242805/" ]
I wrote here before, a clean install of ubuntu has no problem with resolution. But after that I found the solution while I was looking for an answer for another problem. Follow the steps below and everything will be fixed. If you have the latest VMware Tools and open-vm-tools is not install, the skip to step 3. 1) `sudo apt-get autoremove open-vm-tools` 2) Install VMware Tools by following the usual method (Virtual Machine --> Reinstall VMWare Tools) 3) Reboot the VM 4) `sudo apt-get install open-vm-tools-desktop` 5) Reboot the VM. Hope this helps. I know how frustrating it is to try and fix this.
Edit your VMX to include: ``` vga.guestBackedPrimaryAware = "FALSE" svga.minVRAMSize = "16777216" ``` notes: * Tested with Xubuntu 16.04 with kernel version 4.4.0-77 in VMWare Fusion 8.5.6 at 1920x1200 * This may be a problem with the combination of kernel version (4.4.0-77 in my case) and virtualHW.version (see ref. #1) and may indicate a bug (see ref. #2) * My VM is pegged at `virtualHW.version = "11"` references: 1. <https://unix.stackexchange.com/questions/301531/ubuntu-server-stopped-running-in-higher-resolution> 2. <https://github.com/vmware/open-vm-tools/issues/54>
13,276,155
I have almost the same issue as where described [here](https://stackoverflow.com/questions/10536170/equalizer-not-always-supported-even-when-api-9), answer in this post doesn't help me, I release my equalizer immediately after setting band levels to it. It works perfect on my 4.0.4 device, it works great on friend's 2.3.5 device, it crashes on a little percent of devices and it doesn't matter which version of android is running on these devices. So there is error on `Equalizer mEqualizer = new Equalizer(0, mediaPlayer.getAudioSessionId());` ``` java.lang.UnsupportedOperationException: Effect library not loaded at android.media.audiofx.AudioEffect.<init>(AudioEffect.java:355) at android.media.audiofx.Equalizer.<init>(Equalizer.java:149) ``` I have no idea how to solve this, any suggestions?
2012/11/07
[ "https://Stackoverflow.com/questions/13276155", "https://Stackoverflow.com", "https://Stackoverflow.com/users/552246/" ]
Make sure that you reboot the device and test it again with the release() after using the equalizer, it worked for me after 2 days of searching for clues.
This depends on the build of Android that is loaded on the device. This log means that there is no library to implements the AudioEffect feature. I m afraid there is no solution for this, rather then importing into your project some third party audio effect library
13,276,155
I have almost the same issue as where described [here](https://stackoverflow.com/questions/10536170/equalizer-not-always-supported-even-when-api-9), answer in this post doesn't help me, I release my equalizer immediately after setting band levels to it. It works perfect on my 4.0.4 device, it works great on friend's 2.3.5 device, it crashes on a little percent of devices and it doesn't matter which version of android is running on these devices. So there is error on `Equalizer mEqualizer = new Equalizer(0, mediaPlayer.getAudioSessionId());` ``` java.lang.UnsupportedOperationException: Effect library not loaded at android.media.audiofx.AudioEffect.<init>(AudioEffect.java:355) at android.media.audiofx.Equalizer.<init>(Equalizer.java:149) ``` I have no idea how to solve this, any suggestions?
2012/11/07
[ "https://Stackoverflow.com/questions/13276155", "https://Stackoverflow.com", "https://Stackoverflow.com/users/552246/" ]
From the documentation, you have to call release() on an Equalizer, MediaPlayer, Visualizer, etc for a graceful exit, or you will see this error when restarting the app. The only remedy then is to reboot, as previously mentioned in this thread. This is where the Android application lifecycle makes things a little difficult, since apps are never supposed to exit (just pause and resume), unless absolutely required by the OS for memory reasons, or a reboot occurs. Your app onDestroy() method is called in both cases. You can put the release() in onDestroy(), and that would satisfy the Android lifecycle for deployed apps. Your users would not see this error. In development however there is a problem: IDEs like Eclipse (which is actually a framework for building IDEs, and not meant to be an IDE itself...) will kill the app process instead of sending it a destroy message. This violates the lifecycle and release() is not called. This is also why you should never call System.exit(). It violates the lifecycle at the risk of ungraceful exits exactly like this. So your process was exiting ungracefully. Only happens in development, not deployment. One remedy is to not use the device window in eclipse to stop processes. It is not a stop, but a kill. Eclipse also kills (lifecycle violation) the process ungracefully when you Run an app project while there is already an instance running. As the doctor said, if it hurts, don't do it: instead use the debugger which sends actual lifecycle messages to the app.
This depends on the build of Android that is loaded on the device. This log means that there is no library to implements the AudioEffect feature. I m afraid there is no solution for this, rather then importing into your project some third party audio effect library
13,276,155
I have almost the same issue as where described [here](https://stackoverflow.com/questions/10536170/equalizer-not-always-supported-even-when-api-9), answer in this post doesn't help me, I release my equalizer immediately after setting band levels to it. It works perfect on my 4.0.4 device, it works great on friend's 2.3.5 device, it crashes on a little percent of devices and it doesn't matter which version of android is running on these devices. So there is error on `Equalizer mEqualizer = new Equalizer(0, mediaPlayer.getAudioSessionId());` ``` java.lang.UnsupportedOperationException: Effect library not loaded at android.media.audiofx.AudioEffect.<init>(AudioEffect.java:355) at android.media.audiofx.Equalizer.<init>(Equalizer.java:149) ``` I have no idea how to solve this, any suggestions?
2012/11/07
[ "https://Stackoverflow.com/questions/13276155", "https://Stackoverflow.com", "https://Stackoverflow.com/users/552246/" ]
Make sure that you reboot the device and test it again with the release() after using the equalizer, it worked for me after 2 days of searching for clues.
From the documentation, you have to call release() on an Equalizer, MediaPlayer, Visualizer, etc for a graceful exit, or you will see this error when restarting the app. The only remedy then is to reboot, as previously mentioned in this thread. This is where the Android application lifecycle makes things a little difficult, since apps are never supposed to exit (just pause and resume), unless absolutely required by the OS for memory reasons, or a reboot occurs. Your app onDestroy() method is called in both cases. You can put the release() in onDestroy(), and that would satisfy the Android lifecycle for deployed apps. Your users would not see this error. In development however there is a problem: IDEs like Eclipse (which is actually a framework for building IDEs, and not meant to be an IDE itself...) will kill the app process instead of sending it a destroy message. This violates the lifecycle and release() is not called. This is also why you should never call System.exit(). It violates the lifecycle at the risk of ungraceful exits exactly like this. So your process was exiting ungracefully. Only happens in development, not deployment. One remedy is to not use the device window in eclipse to stop processes. It is not a stop, but a kill. Eclipse also kills (lifecycle violation) the process ungracefully when you Run an app project while there is already an instance running. As the doctor said, if it hurts, don't do it: instead use the debugger which sends actual lifecycle messages to the app.
45,595,323
This is the `Cluster` table: ``` ╭────╥────────────┬─────────────╮ │ id ║ name │ prefix │ ╞════╬════════════╪═════════════╡ │ 1 ║ Yard work │ YA │ │ 2 ║ Construc.. │ CR │ └────╨────────────┴─────────────┘ ``` Both `name` and `prefix` have uniqueness and non-null constraints. Now we get to a material table where each row has a foreign key to a cluster. ``` ╭────╥──────────────┬─────────────╮ │ id ║ cluster_id │ name │ ╞════╬══════════════╪═════════════│ │ 1 ║ 1 │ Shovel │ │ 2 ║ 1 │ Lawn mower │ └────╨──────────────┴─────────────┘ ``` We want to give each material another unique identifier (perhaps as the primary key even) which I can't quite figure out how to write the sequence for: 1. Prefix with a hard coded letter (`W` from here on) 2. Take the `prefix` of the cluster (`YA` from here on) 3. Given what we have now (`W-YA`) find the last value and increment by 1, this should end up being 5 characters long and padded with 0 So we would end up with, given that ^ example, 1. W-YA-00001 2. W-YA-00002 3. W-YA-00003 With another cluster\_id we would then end up with 1. W-CR-00001 2. W-CR-00002 I imagine this is solved through `CREATE SEQUENCE` but I'm not sure where to start at all. Note that the clusters table can receive new rows at any given moment. A row can neither change nor be deleted though. Rows from `cluster_materials` can NOT be deleted, and the cluster\_id can *NOT* be changed. **UPDATE:** Sequences are not the way to go here as I need to guarantee a gapless increase in the numbers, which sequences do not provide. **UPDATE 2:** [Gapless Sequences for Primary Keys](http://www.varlena.com/GeneralBits/130.php) does describe how to achieve gapless keys, and I think it could be modified to fit my needs. However it does seem like if an insert fails here this would blow up as the count was incremented but the row is never inserted (say because it doesn't pass all constraints.) I guess that can be solved with transactions. **UPDATE 3:** I'm slowly making progress in this fiddle: <http://sqlfiddle.com/#!15/791ed/2> **UPDATE 4:** Latest progress. This is working just fine right now. It does not do any locking however and I don't know exactly how it works during concurrent inserts (which aren't an issue but locking would probably be good to prevent any unexpected issues in the future.) <http://sqlfiddle.com/#!15/7ad0f/9>
2017/08/09
[ "https://Stackoverflow.com/questions/45595323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/354531/" ]
If performance is not an issue at all, then I suggest you following solution: Schema: ```sql create table cluster ( id bigint primary key, name text not null unique, prefix text not null unique ); create table material ( id text primary key, cluster_id bigint not null references cluster, name text not null ); ``` Some data for cluster: ```sql insert into cluster (id, name, prefix) values (1, 'Yard work', 'YW'), (2, 'Construc..', 'CR'); ``` Stored procedure that adds materials: ```sql create or replace function add_material( p_cluster_id bigint, p_name text ) returns text as $body$ -- for gapless ids -- prevents concurrent updates and inserts -- release on commit or rollback lock table material in exclusive mode; insert into material (id, cluster_id, name) select 'W-' || c.prefix || '-' || lpad( ( select coalesce(max(substring(m.id from '.....$')::integer) + 1, 1) from material m where m.cluster_id = c.id )::text, 5, '0' ) id, c.id cluster_id, p_name as "name" from cluster c where c.id = p_cluster_id returning id; $body$ language sql volatile; ``` Example of usage: ```sql select add_material(1, 'test1'); ``` Result: `W-YW-00001` ```sql select add_material(1, 'test2'); ``` Result: `W-YW-00002` ```sql select add_material(2, 'test3'); ``` Result: `W-CR-00001` To increase performance for `select max(...)` you could add index on `material (cluster_id, substring(m.id from '.....$')::integer)`
* this is a terrible design; you should **not** compose (candidate)keys from (concatenations of) expressions, and **certainly not** from aggregates. * since your composed identifier is functionally dependent on the actual keys, it can be constructed on the fly (in this case: based on a window-function) * using some particular ORM is not a reason for a bad database design. Never. --- ``` CREATE TABLE clus ( id integer not null primary key , name varchar UNIQUE , prefix varchar(2) UNIQUE ); INSERT INTO clus(id, name, prefix)VALUES (1,'Yard work','YA' ), (2,'Construc..', 'CR' ); -- Both name and prefix have uniqueness and non-null constraints. -- Now we get to a material table where each row has a foreign key to a cluster. CREATE TABLE mat ( id integer not null , cluster_id integer not null REFERENCES clus(id) , name varchar UNIQUE , PRIMARY KEY(id,cluster_id) ); INSERT INTO mat(id, cluster_id, name)VALUES ( 1 , 1 , 'Shovel' ) ,( 2 , 1 , 'Lawn mower') ,( 5 , 1 , 'fire hose' ); SELECT omg.* , 'W-' || omg.pfx || '-' || to_char(omg.rnk, 'FM0000') AS wtf FROM(SELECT c.id AS cid, c.name AS cname, c.prefix AS pfx ,m.id AS mid, m.name AS mname , rank()over (partition by m.cluster_id ORDER BY m.id) AS rnk FROM clus c JOIN mat m ON m.cluster_id = c.id ) omg ; ``` --- Result: --- ``` CREATE TABLE INSERT 0 2 CREATE TABLE INSERT 0 3 cid | cname | pfx | mid | mname | rnk | wtf -----+-----------+-----+-----+------------+-----+----------- 1 | Yard work | YA | 1 | Shovel | 1 | W-YA-0001 1 | Yard work | YA | 2 | Lawn mower | 2 | W-YA-0002 1 | Yard work | YA | 5 | fire hose | 3 | W-YA-0003 (3 rows) ```
8,379,555
I am trying to limit the swipe area of the UIScrollview, but i amnot able to do that. I would like to set the swipe area only to the top of the UIScrollview, but i would like to set all the content visible. Update: ``` - (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { if ([touches count] > 0) { UITouch *tempTouch = [touches anyObject]; CGPoint touchLocation = [tempTouch locationInView:self.categoryScrollView]; if (touchLocation.y > 280.0) { NSLog(@"enabled"); self.categoryScrollView.scrollEnabled = YES; } } [self.categoryScrollView touchesBegan:touches withEvent:event]; } - (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { // [super touchesEnded:touches withEvent:event]; self.categoryScrollView.scrollEnabled = YES; [self.categoryScrollView touchesBegan:touches withEvent:event]; } ``` Solution: dont forget to set delaysContentTouches to NO on the UIScrollView ``` self.categoryScrollView.delaysContentTouches = NO; ```
2011/12/04
[ "https://Stackoverflow.com/questions/8379555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1077114/" ]
You can disable scrolling on the `UIScrollView`, override `touchesBegan:withEvent:` in your view controller, check if any of the touches began in the area where you'd like to enable swipes, and if the answer is 'yes', re-enable scrolling. Also override `touchesEnded:withEvent:` and `touchesCancelled:withEvent:` to disable scrolling when the touches are over.
[This blog post](http://www.lukaszielinski.de/blog/posts/2014/03/26/restrict-panning-of-uipageviewcontroller-to-certain-area/) showcases a very simple and clean way of implementing the functionality. ``` // init or viewDidLoad UIScrollView *scrollView = (UIScrollView *)view; _scrollViewPanGestureRecognzier = [[UIPanGestureRecognizer alloc] init]; _scrollViewPanGestureRecognzier.delegate = self; [scrollView addGestureRecognizer:_scrollViewPanGestureRecognzier]; // - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer*)otherGestureRecognizer { return NO; } - (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer { if (gestureRecognizer == _scrollViewPanGestureRecognzier) { CGPoint locationInView = [gestureRecognizer locationInView:self.view]; if (locationInView.y > SOME_VALUE) { return YES; } return NO; } return NO; } ```
8,379,555
I am trying to limit the swipe area of the UIScrollview, but i amnot able to do that. I would like to set the swipe area only to the top of the UIScrollview, but i would like to set all the content visible. Update: ``` - (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { if ([touches count] > 0) { UITouch *tempTouch = [touches anyObject]; CGPoint touchLocation = [tempTouch locationInView:self.categoryScrollView]; if (touchLocation.y > 280.0) { NSLog(@"enabled"); self.categoryScrollView.scrollEnabled = YES; } } [self.categoryScrollView touchesBegan:touches withEvent:event]; } - (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { // [super touchesEnded:touches withEvent:event]; self.categoryScrollView.scrollEnabled = YES; [self.categoryScrollView touchesBegan:touches withEvent:event]; } ``` Solution: dont forget to set delaysContentTouches to NO on the UIScrollView ``` self.categoryScrollView.delaysContentTouches = NO; ```
2011/12/04
[ "https://Stackoverflow.com/questions/8379555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1077114/" ]
You can disable scrolling on the `UIScrollView`, override `touchesBegan:withEvent:` in your view controller, check if any of the touches began in the area where you'd like to enable swipes, and if the answer is 'yes', re-enable scrolling. Also override `touchesEnded:withEvent:` and `touchesCancelled:withEvent:` to disable scrolling when the touches are over.
Other answers didn't work for me. Subclassing `UIScrollView` worked for me (Swift 3): ``` class ScrollViewWithLimitedPan : UIScrollView { // MARK: - UIPanGestureRecognizer Delegate Method Override - override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { let locationInView = gestureRecognizer.location(in: self) print("where are we \(locationInView.y)") return locationInView.y > 400 } } ```
8,379,555
I am trying to limit the swipe area of the UIScrollview, but i amnot able to do that. I would like to set the swipe area only to the top of the UIScrollview, but i would like to set all the content visible. Update: ``` - (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { if ([touches count] > 0) { UITouch *tempTouch = [touches anyObject]; CGPoint touchLocation = [tempTouch locationInView:self.categoryScrollView]; if (touchLocation.y > 280.0) { NSLog(@"enabled"); self.categoryScrollView.scrollEnabled = YES; } } [self.categoryScrollView touchesBegan:touches withEvent:event]; } - (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { // [super touchesEnded:touches withEvent:event]; self.categoryScrollView.scrollEnabled = YES; [self.categoryScrollView touchesBegan:touches withEvent:event]; } ``` Solution: dont forget to set delaysContentTouches to NO on the UIScrollView ``` self.categoryScrollView.delaysContentTouches = NO; ```
2011/12/04
[ "https://Stackoverflow.com/questions/8379555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1077114/" ]
Other answers didn't work for me. Subclassing `UIScrollView` worked for me (Swift 3): ``` class ScrollViewWithLimitedPan : UIScrollView { // MARK: - UIPanGestureRecognizer Delegate Method Override - override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { let locationInView = gestureRecognizer.location(in: self) print("where are we \(locationInView.y)") return locationInView.y > 400 } } ```
[This blog post](http://www.lukaszielinski.de/blog/posts/2014/03/26/restrict-panning-of-uipageviewcontroller-to-certain-area/) showcases a very simple and clean way of implementing the functionality. ``` // init or viewDidLoad UIScrollView *scrollView = (UIScrollView *)view; _scrollViewPanGestureRecognzier = [[UIPanGestureRecognizer alloc] init]; _scrollViewPanGestureRecognzier.delegate = self; [scrollView addGestureRecognizer:_scrollViewPanGestureRecognzier]; // - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer*)otherGestureRecognizer { return NO; } - (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer { if (gestureRecognizer == _scrollViewPanGestureRecognzier) { CGPoint locationInView = [gestureRecognizer locationInView:self.view]; if (locationInView.y > SOME_VALUE) { return YES; } return NO; } return NO; } ```
79,239
[Calmette](https://en.wikipedia.org/wiki/Albert_Calmette) tried injecting horses with snake venom and then taking out the serum which has produced antibodies against the venom and injecting in the snake-bitten human. Shouldn't our immune system recognize this exogenous protein and try to eliminate it as it's a non-self protein?
2018/11/23
[ "https://biology.stackexchange.com/questions/79239", "https://biology.stackexchange.com", "https://biology.stackexchange.com/users/42917/" ]
Our immune system does react to horse antibodies, but as with any adaptive immune response it takes some time for the response to develop. In the weeks before our immune response fully responds to the horse antibodies, the infused antibodies can have their effect. If you then have a *second* infusion of horse antibodies, the immune response would not only prevent them from having their beneficial effect, but it might case serious adverse effects. This [serum sickness](https://en.wikipedia.org/wiki/Serum_sickness) (Wikipedia link) has been known for over a century; here is a paper from 1918 discussing it as a well-known issue: > > 1. The injection of horse serum either in small or in large amounts in human beings is always followed sooner or later by the development of hypersensitiveness of the skin to subsequent injections of horse serum. For the development of this reaction serum disease is not essential. > > > --[THE RELATION OF CIRCULATING ANTIBODIES TO SERUM DISEASE. J. Exp. Med. Published March 1, 1918](http://jem.rupress.org/content/27/3/341.long) Although there aren't many modern situations in which horse (or other non-human species) serum is injected into humans, when it is (as with anti-venom, which is generally produced in non-human animals) serum sickness is still a concern. > > Serum sickness is a delayed immune reaction resulting from the injection of foreign protein or serum. Antivenom is known to cause serum sickness but the incidence and characteristics are poorly defined. ... The primary outcome was the proportion with serum sickness, pre-defined as three or more of: fever, erythematous rash/urticaria, myalgia/arthralgia, headache, malaise, nausea/vomiting 5–20 days post-antivenom. > > > --[Incidence of serum sickness after the administration of Australian snake antivenom (ASP-22). Clinical Toxicology. Published 2016](https://www.tandfonline.com/doi/full/10.3109/15563650.2015.1101771)
Human/mammalian immune system do not react to everything foreign that enters the body. This foreign substances are called "antigens". Instead, the host [i.e. body] reacts to "immunogens" - these are antigens, that CAN elicit immune reaction. Microbes are immunogens, for instance. They don't only consist of microbe proteins, but also of so-called PAMPs, pathogen-associated microbial particles. This can be a bacterial cell wall or "peculiar" DNA and double-stranded RNA, that are definitely cannot be found in mammalian tissue. And these PAMPs are recognized by PRRs, pattern recognition receptors, that are found on innate immune cells, such as dendritic cells and macrophages. WITHOUT activation of innate immune cells, without, basically, INFLAMMATION, the overall immune reaction is not possible. At least, this is a current concept. So, horse antibodies are not sufficient to elicit immune reaction. In order to induce immune reaction, these antibodies should be injected with something, that can activate PRRs or cause tissue damage, like aluminum dioxide. The latter substance is largely used in formulation of vaccines. Guess, why ;-) Of course, there are immune reactions to proteins or harmless xeno-antibodies, but this is usually not physiological, if the manifested reaction is severe. Example: food allergy to egg protein, ovalbumin. Hope, it helped. Best, S
21,003
With a few colleagues, we're trying to design an (intermediate) algebra course (US terminology) where we stress the interplay between algebra and geometry. The algebraic topics we would like to cover are (1) linear equation in two variables, (2) quadratic equations in two variables, (3) polynomials in one variable, (4) rational functions in one variable (though we're not sure we want to introduce functions), (5) radicals. For (1) and (2) there are obvious geometric counterparts: lines and conic sections. **Question**: Are there natural geometric counterparts for (3), (4) and (5)? Are there elementary geometric constructions that naturally lead to these algebraic objects? **Side question**: Are there (affordable) textbooks or lecture notes out there which have this kind of approach?
2011/02/08
[ "https://math.stackexchange.com/questions/21003", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
Bart, as linear equations related to lines, some rational functions are related to orbifolds. You can also explain the solutions of r(z)=c where c is given. It might be very instructive to see the solution set of r(z)=c as c changes continuously on the sphere, or more generally, r(z)=L or C where L is an arbitrary line and C is a circle.
For 5, for square roots, it seems almost too obvious to use the hypotenuse of right triangles. For higher roots, diagonals on cubes of higher dimensions? For 3, a quadratic in one variable is also a conic section. For higher degrees...so this is for high school right? ...yeah this one isn't obvious.
21,003
With a few colleagues, we're trying to design an (intermediate) algebra course (US terminology) where we stress the interplay between algebra and geometry. The algebraic topics we would like to cover are (1) linear equation in two variables, (2) quadratic equations in two variables, (3) polynomials in one variable, (4) rational functions in one variable (though we're not sure we want to introduce functions), (5) radicals. For (1) and (2) there are obvious geometric counterparts: lines and conic sections. **Question**: Are there natural geometric counterparts for (3), (4) and (5)? Are there elementary geometric constructions that naturally lead to these algebraic objects? **Side question**: Are there (affordable) textbooks or lecture notes out there which have this kind of approach?
2011/02/08
[ "https://math.stackexchange.com/questions/21003", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
This seems rather ambitious for most U.S. college intermediate algebra courses, which typically are not-for-credit remedial courses that lie below the level of college algebra and precalculus courses. Nonetheless, here are some things I've used in precalculus courses that might of use. To see what the graph of something like $yx^2 + 2y^3 = 3x + 3y$ looks like using a (standard implicit-incapable) graphing calculator, solve for $x$ in terms of $y$ using the quadratic formula (or $y$ in terms of $x$ when possible, but I'm giving an example where we don't have the option of solving for $y$) and then graph both solutions simultaneously as if $x$ and $y$ were switched. That is, if you're using one of the TI graphing calculators, then enter for `y1=` and `y2=` the following: `y1 = (3+(9-4x(2x^3-3x))^(1/2))/(2x)` `y2 = (3-(9-4x(2x^3-3x))^(1/2))/(2x)` (Note for would-be editors: Please don't LaTeX the expressions above, as what I've given is what the calculator input should be.) To account for the fact that you're graphing the inverse relation, rotate what you see 90 degrees counterclockwise and then reflect the rotated result across the vertical axis. Equivalently, you can reflect what you see about the line $y=x$, but I suspect what I first suggested is easier for students to carry out. Here's a more elaborate example. Suppose we want to know what the graph of $y^4 - 4xy^3 + 2y^2 + 4xy + 1 = 0$ looks like. (Yes, I know about the Newton polygon method, but let's not go there.) Although this can be solved for $y$ in terms of $x$, it is rather difficult to do so and the result is somewhat difficult to interpret graphically by hand. You'll get the 4 different expressions $y = x \pm \sqrt{x^2 - 1} \pm \sqrt{x^2 - x} \pm \sqrt{x^2 + x}$, where the 4 sign permutations are $(+,+,+),$ $(+,-,-)$, $(-,+,-)$, and $(-,-,+)$. On the other hand, it is easy to solve for $x$ in terms of $y$ and the result is $x = \frac{\left(y^2+1\right)^2}{4y\left(y^2-1\right)}$, which can be graphed by hand using standard methods for graphing rational functions. For graphs of polynomial functions, especially when given as (or easily put into) factored as linear and real-irreducible quadratics with real coefficients (and probably best to mostly avoid using real-irreducible quadratics, at least at the beginning), you can discuss how their graphs locally look at each $x$-intercept and how their graphs roughly look globally by using "order of contact with the $x$-axis" notions (which you don't have to define precisely, of course) and end behavior. For example, since $y = (x+2)^3 (2x+1)^2 x (3-x)$ has the form $y = (x)^3(2x)^2(x)(-x) + \;$ lower order terms, or $y = -4x^7 + \;$ lower order terms, a zoomed out view of the graph will look like the graph of $y = -4x^7$, so the graph "enters at the upper left of quadrant 2" and "exits at the lower right of quadrant 4". Also, the graph passes through the $x$-axis at $x=-2$ "in a cubic fashion" so that locally at this zero the graph looks like a version (translated and reflected, the latter because in going from left to right the graph passes from positive $y$-values to negative $y$-values) of the graph of $y = x^3$. The same kind of analysis leads to what the graph locally looks like at the other $x$-intercepts, which I'll assume you know what I'm talking about by now since this is (or at least it used to be) a fairly standard topic in precalculus courses. In the case of rational functions, one topic that could be investigated is linear fractional transformations (as they're called in complex analysis), or quotients of linear (= affine) functions, by looking at them through the lens of precalculus transformations of the graph of $y = \frac{1}{x}$. Although you definitely don't want to consider the general case, here's the general case version, where I'm assuming $c \neq 0$. (The first equality comes from a 1-step long division calculation.) $\frac{ax+b}{cx+d} = \frac{a}{c} + \frac{b - \frac{ad}{c}}{cx+d}$ $= \frac{a}{c} + \frac{\frac{b}{c} - \frac{ad}{c^2}}{x+\frac{d}{c}}$ $= \frac{a}{c} + \frac{1}{c^2}(bc-ad)\left[ \frac{1}{1 - \left(-\frac{d}{c}\right)}\right]$ Note that this shows the graph of $y = \frac{ax+b}{cx+d}$ can be obtained from the graph of $y = \frac{1}{x}$ by a horizontal translation to the right by $-\frac{d}{c}$ units, followed by a vertical stretch by a factor of $\frac{1}{c^2}(bc-ad)$, followed by a vertical translation up by $\frac{a}{c}$ units. For a possibly useful reference, see Edward C. Wallace, "Investigations involving involutions", Mathematics Teacher 81 (1988), pp. 578-579. [See also these related letters in the Reader Reflections column: Thomas Edwards (MT 83, p. 496), Larry Hoehm (MT 83, p. 496), Andrew Berry (MT 95, p. 406), and Sidney H. Kung (MT 97, pp. 227 & 242).] While I'm on the topic, here's an "intermediate algebra appropriate" situation where a linear fractional transformation arises. For which number or numbers $x$, if any, can we find a number whose sum with $x$ equals its product with $x$? If we denote the desired number by $y$, then the condition becomes $x + y = xy$, or $y = \frac{x}{x-1}$.
For 5, for square roots, it seems almost too obvious to use the hypotenuse of right triangles. For higher roots, diagonals on cubes of higher dimensions? For 3, a quadratic in one variable is also a conic section. For higher degrees...so this is for high school right? ...yeah this one isn't obvious.
21,003
With a few colleagues, we're trying to design an (intermediate) algebra course (US terminology) where we stress the interplay between algebra and geometry. The algebraic topics we would like to cover are (1) linear equation in two variables, (2) quadratic equations in two variables, (3) polynomials in one variable, (4) rational functions in one variable (though we're not sure we want to introduce functions), (5) radicals. For (1) and (2) there are obvious geometric counterparts: lines and conic sections. **Question**: Are there natural geometric counterparts for (3), (4) and (5)? Are there elementary geometric constructions that naturally lead to these algebraic objects? **Side question**: Are there (affordable) textbooks or lecture notes out there which have this kind of approach?
2011/02/08
[ "https://math.stackexchange.com/questions/21003", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
This seems rather ambitious for most U.S. college intermediate algebra courses, which typically are not-for-credit remedial courses that lie below the level of college algebra and precalculus courses. Nonetheless, here are some things I've used in precalculus courses that might of use. To see what the graph of something like $yx^2 + 2y^3 = 3x + 3y$ looks like using a (standard implicit-incapable) graphing calculator, solve for $x$ in terms of $y$ using the quadratic formula (or $y$ in terms of $x$ when possible, but I'm giving an example where we don't have the option of solving for $y$) and then graph both solutions simultaneously as if $x$ and $y$ were switched. That is, if you're using one of the TI graphing calculators, then enter for `y1=` and `y2=` the following: `y1 = (3+(9-4x(2x^3-3x))^(1/2))/(2x)` `y2 = (3-(9-4x(2x^3-3x))^(1/2))/(2x)` (Note for would-be editors: Please don't LaTeX the expressions above, as what I've given is what the calculator input should be.) To account for the fact that you're graphing the inverse relation, rotate what you see 90 degrees counterclockwise and then reflect the rotated result across the vertical axis. Equivalently, you can reflect what you see about the line $y=x$, but I suspect what I first suggested is easier for students to carry out. Here's a more elaborate example. Suppose we want to know what the graph of $y^4 - 4xy^3 + 2y^2 + 4xy + 1 = 0$ looks like. (Yes, I know about the Newton polygon method, but let's not go there.) Although this can be solved for $y$ in terms of $x$, it is rather difficult to do so and the result is somewhat difficult to interpret graphically by hand. You'll get the 4 different expressions $y = x \pm \sqrt{x^2 - 1} \pm \sqrt{x^2 - x} \pm \sqrt{x^2 + x}$, where the 4 sign permutations are $(+,+,+),$ $(+,-,-)$, $(-,+,-)$, and $(-,-,+)$. On the other hand, it is easy to solve for $x$ in terms of $y$ and the result is $x = \frac{\left(y^2+1\right)^2}{4y\left(y^2-1\right)}$, which can be graphed by hand using standard methods for graphing rational functions. For graphs of polynomial functions, especially when given as (or easily put into) factored as linear and real-irreducible quadratics with real coefficients (and probably best to mostly avoid using real-irreducible quadratics, at least at the beginning), you can discuss how their graphs locally look at each $x$-intercept and how their graphs roughly look globally by using "order of contact with the $x$-axis" notions (which you don't have to define precisely, of course) and end behavior. For example, since $y = (x+2)^3 (2x+1)^2 x (3-x)$ has the form $y = (x)^3(2x)^2(x)(-x) + \;$ lower order terms, or $y = -4x^7 + \;$ lower order terms, a zoomed out view of the graph will look like the graph of $y = -4x^7$, so the graph "enters at the upper left of quadrant 2" and "exits at the lower right of quadrant 4". Also, the graph passes through the $x$-axis at $x=-2$ "in a cubic fashion" so that locally at this zero the graph looks like a version (translated and reflected, the latter because in going from left to right the graph passes from positive $y$-values to negative $y$-values) of the graph of $y = x^3$. The same kind of analysis leads to what the graph locally looks like at the other $x$-intercepts, which I'll assume you know what I'm talking about by now since this is (or at least it used to be) a fairly standard topic in precalculus courses. In the case of rational functions, one topic that could be investigated is linear fractional transformations (as they're called in complex analysis), or quotients of linear (= affine) functions, by looking at them through the lens of precalculus transformations of the graph of $y = \frac{1}{x}$. Although you definitely don't want to consider the general case, here's the general case version, where I'm assuming $c \neq 0$. (The first equality comes from a 1-step long division calculation.) $\frac{ax+b}{cx+d} = \frac{a}{c} + \frac{b - \frac{ad}{c}}{cx+d}$ $= \frac{a}{c} + \frac{\frac{b}{c} - \frac{ad}{c^2}}{x+\frac{d}{c}}$ $= \frac{a}{c} + \frac{1}{c^2}(bc-ad)\left[ \frac{1}{1 - \left(-\frac{d}{c}\right)}\right]$ Note that this shows the graph of $y = \frac{ax+b}{cx+d}$ can be obtained from the graph of $y = \frac{1}{x}$ by a horizontal translation to the right by $-\frac{d}{c}$ units, followed by a vertical stretch by a factor of $\frac{1}{c^2}(bc-ad)$, followed by a vertical translation up by $\frac{a}{c}$ units. For a possibly useful reference, see Edward C. Wallace, "Investigations involving involutions", Mathematics Teacher 81 (1988), pp. 578-579. [See also these related letters in the Reader Reflections column: Thomas Edwards (MT 83, p. 496), Larry Hoehm (MT 83, p. 496), Andrew Berry (MT 95, p. 406), and Sidney H. Kung (MT 97, pp. 227 & 242).] While I'm on the topic, here's an "intermediate algebra appropriate" situation where a linear fractional transformation arises. For which number or numbers $x$, if any, can we find a number whose sum with $x$ equals its product with $x$? If we denote the desired number by $y$, then the condition becomes $x + y = xy$, or $y = \frac{x}{x-1}$.
Bart, as linear equations related to lines, some rational functions are related to orbifolds. You can also explain the solutions of r(z)=c where c is given. It might be very instructive to see the solution set of r(z)=c as c changes continuously on the sphere, or more generally, r(z)=L or C where L is an arbitrary line and C is a circle.
34,489,986
this is my code ``` void SMatrix::pow(int power, SMatrix & result) { if (this->rowSize != this->colSize || this->rowSize != result.rowSize || this->colSize != result.colSize || power <= 0) { delete & result; result = new SMatrix (result.rowSize, result.colSize); } } ``` Im trying to delete this result in this case, and send it as new `SMatrix`. How can i do it? (`reuslt = newM`..... ask me for `SMatrix *`, but it doesn't work with &). In the main i can build it like that: SMatrix \* s = new SMatrix(4, 4); or SMatrix s(4, 4); (pointer or not).
2015/12/28
[ "https://Stackoverflow.com/questions/34489986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5699256/" ]
This code is just "doing it wrong". If you have a reference argument, then the implied effect is that the ownership of any pointer to it belongs to the caller. ``` void SMatrix::pow(int power, SMatrix & result) { if (this->rowSize != this->colSize || this->rowSize != result.rowSize || this->colSize != result.colSize || power <= 0) { delete & result; result = new SMatrix (result.rowSize, result.colSize); } } ``` If your `SMatrix` doesn't have a proper `operator=`, then you should have one. In other words, the correct thing should happen if you do: ``` if (rowSize != colSize || rowSize != result.rowSize || colSize != result.colSize || power <= 0) { result = SMatrix (result.rowSize, result.colSize); } ``` (Note that I removed both the `delete` line and the `new` operator) If this, for some reason, won't work correctly, then you need to fix that, not rely on how the orignal data was allocated.
``` delete & result; result = new SMatrix (result.rowSize, result.colSize); ``` You can't `delete` an object and then call `operator=` on it. You're doing the equivalent of this: ``` std::string* j = new std::string ("hello"); delete j; *j = "goodbye"; // Oops, there's no string whose value we can set ``` I think you probably just want `result = SMatrix (result.rowSize, result.colSize);`. You want to change the value of `result`, you don't want to delete or create anything dynamic.
40,876,192
I have a directory with script files, say: ``` scripts/ foo.sh script1.sh test.sh ... etc ``` and would like to execute each script like: ``` $ ./scripts/foo.sh start $ ./scripts/script1.sh start etc ``` without needing to know all the script filenames. Is there a way to append `start` to them and execute? I've tried tab-completion as it's pretty good in ZSH, using `./scripts/*[TAB] start` with no luck, but I would imagine there's another way to do so, so it outputs: ``` $ ./scripts/foo.sh start ./scripts/script1.sh start ``` Or perhaps some other way to make it easier? I'd like to do so in the Terminal without an alias or function if possible, as these scripts are on a box I SSH to and shouldn't be modifying `*._profile` or `.*rc` files.
2016/11/29
[ "https://Stackoverflow.com/questions/40876192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1183537/" ]
Use a simple loop: ``` for script in scripts/*.sh; do "$script" start done ``` There's just one caveat: if there are no such `*.sh` files, you will get an error. A simple workaround for that is to check if `$script` is actually a file (and executable): ``` for script in scripts/*.sh; do [ -x "$script" ] && "$script" start done ``` Note that this can be written on a single line, if that's what you're after for: ``` for script in scripts/*.sh; do [ -x "$script" ] && "$script" start; done ```
Zsh has some shorthand loops that bash doesn't: ``` for f (scripts/*.sh) "$f" start ```
2,820
In Naruto, when the medical team starts to heal wounds, they use their chakra. Does this only heal and restore chakra, or does it also help regenerate the skin cut by kunais?
2013/03/06
[ "https://anime.stackexchange.com/questions/2820", "https://anime.stackexchange.com", "https://anime.stackexchange.com/users/8/" ]
Medical ninjutsu can be used to heal wounds, such as those cause by kunai. It is used for a number of purposes, including: * Healing: [Healing Chakra Transmission](http://naruto.wikia.com/wiki/Healing_Chakra_Transmission), [Healing Resuscitation Regeneration Technique](http://naruto.wikia.com/wiki/Healing_Resuscitation_Regeneration_Technique) * Treating internal and external injuries: [Mystical Palm Technique](http://naruto.wikia.com/wiki/Mystical_Palm_Technique) * Treating poisons: [Delicate Illness Extraction Technique](http://naruto.wikia.com/wiki/Delicate_Illness_Extraction_Technique) * Performing autopsy or surgery: [Chakra Scalpel](http://naruto.wikia.com/wiki/Chakra_Scalpel) * Healing oneself: [Creation Rebirth](http://naruto.wikia.com/wiki/Creation_Rebirth), [Strength of a Hundred Technique](http://naruto.wikia.com/wiki/Strength_of_a_Hundred_Technique) * Offensively in several ways: [Body Pathway Derangement](http://naruto.wikia.com/wiki/Body_Pathway_Derangement), [Poison Mist Needle Shot](http://naruto.wikia.com/wiki/Poison_Mist_Needle_Shot).
**How does the healing jutsu work?** It works by channeling the healer's chakra into the patient's body, in order to help the regeneration of skin, cells, chakra flow, etc. The medical-nin can also use medical ninjutsu in himself. This type of technique requires great chakra control, because excessive infusion of chakra may cause unwanted problems. Healing jutsu have a wide range of uses, such has physical injury healing, poison healing, or even offensive uses. **Does it also help regenerate the skin cut by kunais?** Yes, there are some examples: * The [Mystical Palm Technique](http://naruto.wikia.com/wiki/Mystical_Palm_Technique) helps in the regeneration of injuries, both internal and external. This technique requires great chakra control, for excess of chakra infused can drive the patient into a comatose state. For this same reason, this technique can also be used as an offensive technique (as seen in chapter 103, pages 9-10, when Kabuto used it against Kiba). This technique's usage has been seen (among others) in chapter 296, pages 12-13, when Kabuto (who can use this technique effectively at a distance) healed Sakura's wounds (caused by Naruto in [Four-tailed form](http://naruto.wikia.com/wiki/Naruto_Uzumaki%27s_Jinch%C5%ABriki_Forms#Version_2)). Also, in chapter 297, Sakura heals Naruto's skin after it had been damaged by the Kyuubi cloak. * Also, Tsunade's [Mitotic Regeneration](http://naruto.wikia.com/wiki/Creation_Rebirth) is able to regenerate physical injuries, at the cost of reducing her lifespan. We've seen her heal herself after she was trespassed by Orochimaru, using the Kusanagi sword, in chapter 169. After having been inflicted these wounds that would otherwise have been fatal, she regenerated herself fully, eliminating every cut in her body. * There are also [techniques that can resuscitate](http://naruto.wikia.com/wiki/Healing_Resuscitation_Regeneration_Technique), healing the injured body parts in the process. This was the technique used when reviving and healing Neji (chapter 235, page 9), after his fight with Kidomaru. In this fight, Neji was trespassed by an arrow (with considerable diameter), that brought about his collapse. With regular healing techniques, such as the Mystical Palm Technique, the healing of such wounds would've been impossible.
25,008,029
Googlebot can't fetch my joomla site after I migrate to another Hosting .. And when I checked with <http://web-sniffer.net/> (with option: Trace., and user-agent: googlebot) the result is 403. ``` <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> <html><head> <title>403 Forbidden</title> </head><body> <h1>Forbidden</h1> <p>You don't have permission to access / on this server.</p> <p>Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.</p> <hr> <address>Apache Server at www.mentarimedia.com Port 80</address> </body></html> ``` pls help me for this..
2014/07/29
[ "https://Stackoverflow.com/questions/25008029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3886309/" ]
There are two things happening here. One is member hiding. This is fairly well-known and covered [elsewhere](https://stackoverflow.com/questions/3838553/overriding-vs-method-hiding). The other, less-known feature is interface re-implementation covered in section 13.4.6 of the C# 5 specification. To quote: > > A class that inherits an interface implementation is permitted to **re-implement** the interface by including it in the base class list. A re-implementation of an interface follows exactly the same interface mapping rules as an initial implementation of an interface. Thus, the inherited interface mapping has no effect whatsoever on the interface mapping established for the re-implementation of the interface. > > > and > > Inherited public member declarations and inherited explicit interface member declarations participate in the interface mapping process for re-implemented interfaces. > > > The result for `f1.GetName()` is "Bar" because the method `Baz.GetName` is hiding `Bar.GetName` and `f1` is declared as type `Bar`. There is no dispatch to the run-time type's implementation unless it is explicitly declared as virtual and overridden. Similarly, for `f2.GetName()`, `Baz.GetName` is hiding the implementation in `Bar`, so it is not called when using dispatch through a reference to the interface. The interface is "mapped" to the method declared in `Bar` because that is the type on which the interface was declared. It does not matter that `Baz` has a compatible method with the same name. The rules for interface mapping are defined in section 13.4.4 of the spec. If `GetName` had been declared virtual in `Bar`, it could be overridden, which then would be called through the interface. The result is therefore also "Bar". For `f3.GetName()`, `Quux` re-implements `IFoo` so it gets to define its own mapping to `GetName`. Note that it also hides the implementation inherited from `Bar`. It is not necessary to use new to do the re-implementation, it simply suppresses the warning about hiding. Therefore the result is "Quux". So that explains the output that you see: "Bar-Bar-Quux" This [post](http://blogs.msdn.com/b/ericlippert/archive/2011/12/08/so-many-interfaces-part-two.aspx) by Eric Lippert discuss some more nuances in this tricky feature.
Interfaces by definition have no associated implementation, which is to say their methods are always virtual and abstract. In contrast, the class `Bar` above defines a concrete implementation for `GetName`. This satisfies the contract required to implement `IFoo`. Class `Baz` now inherits from `Bar` and declares a `new` method `GetName`. That is to say that the parent class `Bar` has a method with the same name, but it is completely ignored when working with `Baz` objects explicitly. However, if a `Baz` object is cast as a `Bar`, or simply assigned to a variable of type `Bar` or `IFoo`, it will do as it's told and behave like a `Bar`. In other words, the method name `GetName` refers to `Bar.GetName` instead of `Baz.GetName`. Now, in the third case, `Quux` both inherits from `Bar` *and* implements `IFoo`. Now, when cast as an `IFoo` it will provide its own implementation (according to the specification provided in Mike Z's answer). When a Quux is cast as a Bar, however, it returns "Bar", just as Baz does.
25,008,029
Googlebot can't fetch my joomla site after I migrate to another Hosting .. And when I checked with <http://web-sniffer.net/> (with option: Trace., and user-agent: googlebot) the result is 403. ``` <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> <html><head> <title>403 Forbidden</title> </head><body> <h1>Forbidden</h1> <p>You don't have permission to access / on this server.</p> <p>Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.</p> <hr> <address>Apache Server at www.mentarimedia.com Port 80</address> </body></html> ``` pls help me for this..
2014/07/29
[ "https://Stackoverflow.com/questions/25008029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3886309/" ]
There are two things happening here. One is member hiding. This is fairly well-known and covered [elsewhere](https://stackoverflow.com/questions/3838553/overriding-vs-method-hiding). The other, less-known feature is interface re-implementation covered in section 13.4.6 of the C# 5 specification. To quote: > > A class that inherits an interface implementation is permitted to **re-implement** the interface by including it in the base class list. A re-implementation of an interface follows exactly the same interface mapping rules as an initial implementation of an interface. Thus, the inherited interface mapping has no effect whatsoever on the interface mapping established for the re-implementation of the interface. > > > and > > Inherited public member declarations and inherited explicit interface member declarations participate in the interface mapping process for re-implemented interfaces. > > > The result for `f1.GetName()` is "Bar" because the method `Baz.GetName` is hiding `Bar.GetName` and `f1` is declared as type `Bar`. There is no dispatch to the run-time type's implementation unless it is explicitly declared as virtual and overridden. Similarly, for `f2.GetName()`, `Baz.GetName` is hiding the implementation in `Bar`, so it is not called when using dispatch through a reference to the interface. The interface is "mapped" to the method declared in `Bar` because that is the type on which the interface was declared. It does not matter that `Baz` has a compatible method with the same name. The rules for interface mapping are defined in section 13.4.4 of the spec. If `GetName` had been declared virtual in `Bar`, it could be overridden, which then would be called through the interface. The result is therefore also "Bar". For `f3.GetName()`, `Quux` re-implements `IFoo` so it gets to define its own mapping to `GetName`. Note that it also hides the implementation inherited from `Bar`. It is not necessary to use new to do the re-implementation, it simply suppresses the warning about hiding. Therefore the result is "Quux". So that explains the output that you see: "Bar-Bar-Quux" This [post](http://blogs.msdn.com/b/ericlippert/archive/2011/12/08/so-many-interfaces-part-two.aspx) by Eric Lippert discuss some more nuances in this tricky feature.
The output is Bar-Bar-Quux as a result of 3 calls to GetName() in your Console.WriteLine method call. ``` Bar f1 = new Baz(); IFoo f2 = new Baz(); IFoo f3 = new Quux(); Console.WriteLine(f1.GetName() + "-" + f2.GetName() + "-" + f3.GetName()); //Bar-Bar-Quux ``` Let's examine each call so it can be made more clear what happens. **f1.GetName()** `f1` is instantiated as `Baz`. *However*, it is **typed** as `Bar`. Because `Bar` exposes `GetName`, when `f1.GetName()` is used, that is the method which is called - *regardless* of the fact that `Baz` also implements `GetName`. The reason is that `f1` is not typed as `Baz`, and if it were, it would call `Baz`'s `GetName` method. An example of that would be to examine the output of ``` Console.WriteLine(((Baz)f1).GetName() + "-" + f2.GetName() + "-" + f3.GetName()); //Baz-Bar-Quux ``` This is possible because of two facts. First, `f1` was initially instantiated as `Baz`, it was simply typed as `Bar`. Second, `Baz` *does* have a `GetName` method, and the use of `new` in its definition hides the inherited `Bar`'s `GetName` method allowing `Baz`'s `GetName` to be called. **f2.GetName()** A very similar typing is occurring with `f2`, which is defined as ``` IFoo f2 = new Baz(); ``` While the Baz class does implement a `GetName` method, it does not implement `IFoo`'s `GetName` method because `Baz` does not inherit from `IFoo` and therefore the method is not available. `Bar` implements `IFoo`, and since `Baz` inherits from `Bar`, `Bar`'s `GetName` is the method which is exposed when `f2` is typed as `IFoo`. Again, since `f2` was initially instantiated as `Baz`, it can still be cast to `Baz`. ``` Console.WriteLine(f1.GetName() + "-" + ((Baz)f2).GetName() + "-" + f3.GetName()); //Bar-Baz-Quux ``` And will have the same output result for the reason noted above for `f1` (`f2` was originally typed as `Baz`, and `Baz`'s `GetName` method hides the inherited `Bar`'s `GetName` method). **f3.GetName()** Different story here. `Quux` *does* inherit and implement `IFoo`, **and** it hides `Bar`'s implementation of `IFoo` by using `new`. The result is that `Quux`'s `GetName` method is the one which is called.
25,008,029
Googlebot can't fetch my joomla site after I migrate to another Hosting .. And when I checked with <http://web-sniffer.net/> (with option: Trace., and user-agent: googlebot) the result is 403. ``` <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> <html><head> <title>403 Forbidden</title> </head><body> <h1>Forbidden</h1> <p>You don't have permission to access / on this server.</p> <p>Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.</p> <hr> <address>Apache Server at www.mentarimedia.com Port 80</address> </body></html> ``` pls help me for this..
2014/07/29
[ "https://Stackoverflow.com/questions/25008029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3886309/" ]
Interfaces by definition have no associated implementation, which is to say their methods are always virtual and abstract. In contrast, the class `Bar` above defines a concrete implementation for `GetName`. This satisfies the contract required to implement `IFoo`. Class `Baz` now inherits from `Bar` and declares a `new` method `GetName`. That is to say that the parent class `Bar` has a method with the same name, but it is completely ignored when working with `Baz` objects explicitly. However, if a `Baz` object is cast as a `Bar`, or simply assigned to a variable of type `Bar` or `IFoo`, it will do as it's told and behave like a `Bar`. In other words, the method name `GetName` refers to `Bar.GetName` instead of `Baz.GetName`. Now, in the third case, `Quux` both inherits from `Bar` *and* implements `IFoo`. Now, when cast as an `IFoo` it will provide its own implementation (according to the specification provided in Mike Z's answer). When a Quux is cast as a Bar, however, it returns "Bar", just as Baz does.
The output is Bar-Bar-Quux as a result of 3 calls to GetName() in your Console.WriteLine method call. ``` Bar f1 = new Baz(); IFoo f2 = new Baz(); IFoo f3 = new Quux(); Console.WriteLine(f1.GetName() + "-" + f2.GetName() + "-" + f3.GetName()); //Bar-Bar-Quux ``` Let's examine each call so it can be made more clear what happens. **f1.GetName()** `f1` is instantiated as `Baz`. *However*, it is **typed** as `Bar`. Because `Bar` exposes `GetName`, when `f1.GetName()` is used, that is the method which is called - *regardless* of the fact that `Baz` also implements `GetName`. The reason is that `f1` is not typed as `Baz`, and if it were, it would call `Baz`'s `GetName` method. An example of that would be to examine the output of ``` Console.WriteLine(((Baz)f1).GetName() + "-" + f2.GetName() + "-" + f3.GetName()); //Baz-Bar-Quux ``` This is possible because of two facts. First, `f1` was initially instantiated as `Baz`, it was simply typed as `Bar`. Second, `Baz` *does* have a `GetName` method, and the use of `new` in its definition hides the inherited `Bar`'s `GetName` method allowing `Baz`'s `GetName` to be called. **f2.GetName()** A very similar typing is occurring with `f2`, which is defined as ``` IFoo f2 = new Baz(); ``` While the Baz class does implement a `GetName` method, it does not implement `IFoo`'s `GetName` method because `Baz` does not inherit from `IFoo` and therefore the method is not available. `Bar` implements `IFoo`, and since `Baz` inherits from `Bar`, `Bar`'s `GetName` is the method which is exposed when `f2` is typed as `IFoo`. Again, since `f2` was initially instantiated as `Baz`, it can still be cast to `Baz`. ``` Console.WriteLine(f1.GetName() + "-" + ((Baz)f2).GetName() + "-" + f3.GetName()); //Bar-Baz-Quux ``` And will have the same output result for the reason noted above for `f1` (`f2` was originally typed as `Baz`, and `Baz`'s `GetName` method hides the inherited `Bar`'s `GetName` method). **f3.GetName()** Different story here. `Quux` *does* inherit and implement `IFoo`, **and** it hides `Bar`'s implementation of `IFoo` by using `new`. The result is that `Quux`'s `GetName` method is the one which is called.
51,739,653
So this is for a HW problem. It is a guessing game for numbers between 1 and 10. I had to create two exception classes: 1. to handle guesses 2. if the user exceeds 5 guesses There is also a third requirement for if the user enters an incorrect format (however that did not require me to make an additional exception class. My problem is that I want to the user to have 5 attempts no matter what they enter, whether it's five or 15. I was able to do this for any guesses outside of the range, but when I enter an invalid format, such as "five" the loop becomes infinite. What am I doing wrong? Thank you in advance: ``` import java.util.Random; import java.util.Scanner; public class GuessingGame { /** * @param args the command line arguments */ public static void main(String[] args) { final int MAX_ATTEMPTS = 5; // Stores maximum number of attempts int answer; // Stores answer int attempts = 1; // Stores nubmer of attempts int guess; // Stores user's guess boolean checkAnswer = true; // Loop control variable // Create Scanner object for keyboard input Scanner keyboard = new Scanner(System.in); // Generate random nubmer between 1 and 10 answer = generateNumber(); /** * Allow user to guess (up to five times) what the random number is. Includes * exception handling for guesses that are outside of the range of 1 and 10, * have exceeded 5 guesses, and are invalid formats and/or data types. **/ while (checkAnswer) { try { // Prompt user for input System.out.println("Please guess a number between 1 and 10"); System.out.println("HINT: " + answer); guess = keyboard.nextInt(); // Throw exception if user exceeds 5 guesses if (attempts > MAX_ATTEMPTS) throw new TooManyGuessesException(attempts); // Throw exception if user guesses outside of range else if ((guess > 10) || (guess < 1)) throw new BadGuessException(guess); // Prompt user that guess is correct and exit loop else if (guess == answer) { if (attempts == 1) System.out.println("YOU WIN!! Wow!! You made " + attempts + " attempt and guessed it on the " + "first try!"); else System.out.println("YOU WIN!! You made " + attempts + " attempts"); checkAnswer = false; } else { attempts++; // increment attempts if no correct guess } } // Handles guesses that are outside of range catch (BadGuessException e) { attempts++; System.out.println(e.getMessage()); continue; } // Handles exception if user exceeds maximum attempts catch (TooManyGuessesException e) { checkAnswer = false; System.out.println(e.getMessage()); } // Handles exception if user enters incorrect format catch (Exception e) { attempts++; System.out.println("Sorry, you entered an invalid number " + "format."); break; } } } /** * <b>generateNumber method</b> * <p> * Generates and returns 1 random number between 1 and 10 inclusive * </p> * * @return A random number between 1 and 10 inclusive. */ public static int generateNumber() { int randomNumber; // Store lotto number 1 final int RANGE = 10; // Sets range of random number // Create random object Random rand = new Random(); // Generate a random value randomNumber = rand.nextInt(RANGE) + 1; return randomNumber; } } ```
2018/08/08
[ "https://Stackoverflow.com/questions/51739653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
**Use Input & Output Decorators** Basic concept ---> [DEMO](https://stackblitz.com/edit/angular-harudq) **app.component.html:** ``` <app-component1 (elm)="catch1Data($event)"> </app-component1> <app-component2 [elm]="datatocomp2" *ngIf="datatocomp2"></app-component2> parent component : {{datatocomp2 | json}} ``` **app.component.ts:** ``` datatocomp2: any; catch1Data(data) { console.log(data) this.datatocomp2 = data; } ``` **component1.ts:** ``` @Output () elm : EventEmitter<any> = new EventEmitter<any>(); objectData: any; constructor() { } ngOnInit() { let objectData = { comp: 'component 1', data: 'anything' } this.objectData = objectData; this.elm.emit(objectData) } ``` **component2.ts:** ``` @Input() elm: any; constructor() { } ngOnInit() { console.log(this.elm); } ```
Use a shared service to share data between components, event emitter method isn't the best way for components in routing Simple example , create a datashare service **//DataShare Service** ``` import { ReplaySubject } from 'rxjs/Rx'; export class DatashareService { private dataObs$ = new ReplaySubject<any>(1); getData() { return this.dataObs$.asObservable(); } updateData(data) { this.dataObs$.next(data); } constructor() { } } ``` **In the component where you fetch data,** ``` import { DatashareService } from '../datashare.service'; ``` **update the value of the observable** ``` this.dataService.updateData(this.modal_id); ``` **Subscribe to the observable from the sub components** ``` import { Component, OnInit,OnDestroy,NgZone } from '@angular/core'; import { DatashareService } from '../datashare.service'; import { Subscription } from 'rxjs/Subscription'; ``` **In the constructor,** ``` constructor(private dataService: DatashareService ,private zone:NgZone){} ``` **Now, access data on init,** ``` ngOnInit() { this.subscription.add(this.dataService.getData().subscribe(data => { this.zone.run(()=>{ console.log(data); this.modal_selected=data; }) })) } ``` **Don't forget to unsubscribe on destroy** ``` ngOnDestroy() { // unsubscribe to ensure no memory leaks this.subscription.unsubscribe(); } ```
2,694,269
$$2^x = 3$$ $$5^y = 2$$ $$3^z = 125$$ Find the result of $xyz$ To get $xyz$, I've tried to multiply all together. $$2^x . 5^y . 3^z = 750$$ Unfortunalety, I've gone too wrong as in my perspective. Can you assist? I'd like to get your professional tips. **EDIT:** I'm trying to solve this question by using exponential properties.
2018/03/16
[ "https://math.stackexchange.com/questions/2694269", "https://math.stackexchange.com", "https://math.stackexchange.com/users/493389/" ]
Solve for each $x=\log\_2(3)$, $y=\log\_5(2)$ and $z=\log\_3(125)$. The product would be $xyz=\log\_2(3)\log\_5(2)\log\_3(125)$. Very likely they will examine also the possibility of some simplification. --- For the new requirement: Raise the first equation to $z$. You get $2^{xz}=3^z=125=5^3=2^{3/y}$. Raise again, but to $y$ and get $2^{xyz}=2^3$.
taking the logarithm we get $$x=\frac{\ln(3)}{\ln(2)}$$ $$y=\frac{\ln(2)}{\ln(5)}$$ $$z=\frac{\ln(125)}{\ln(3)}$$ Can you proceed?
2,694,269
$$2^x = 3$$ $$5^y = 2$$ $$3^z = 125$$ Find the result of $xyz$ To get $xyz$, I've tried to multiply all together. $$2^x . 5^y . 3^z = 750$$ Unfortunalety, I've gone too wrong as in my perspective. Can you assist? I'd like to get your professional tips. **EDIT:** I'm trying to solve this question by using exponential properties.
2018/03/16
[ "https://math.stackexchange.com/questions/2694269", "https://math.stackexchange.com", "https://math.stackexchange.com/users/493389/" ]
$$5^{xyz}=(5^y)^{xz}=2^{xz}=(2^x)^z=3^z=125$$
Solve for each $x=\log\_2(3)$, $y=\log\_5(2)$ and $z=\log\_3(125)$. The product would be $xyz=\log\_2(3)\log\_5(2)\log\_3(125)$. Very likely they will examine also the possibility of some simplification. --- For the new requirement: Raise the first equation to $z$. You get $2^{xz}=3^z=125=5^3=2^{3/y}$. Raise again, but to $y$ and get $2^{xyz}=2^3$.
2,694,269
$$2^x = 3$$ $$5^y = 2$$ $$3^z = 125$$ Find the result of $xyz$ To get $xyz$, I've tried to multiply all together. $$2^x . 5^y . 3^z = 750$$ Unfortunalety, I've gone too wrong as in my perspective. Can you assist? I'd like to get your professional tips. **EDIT:** I'm trying to solve this question by using exponential properties.
2018/03/16
[ "https://math.stackexchange.com/questions/2694269", "https://math.stackexchange.com", "https://math.stackexchange.com/users/493389/" ]
$$5^{xyz}=(5^y)^{xz}=2^{xz}=(2^x)^z=3^z=125$$
taking the logarithm we get $$x=\frac{\ln(3)}{\ln(2)}$$ $$y=\frac{\ln(2)}{\ln(5)}$$ $$z=\frac{\ln(125)}{\ln(3)}$$ Can you proceed?
58,473,505
``` df = pd.read_csv( 'https://media-doselect.s3.amazonaws.com/generic/MJjpYqLzv08xAkjqLp1ga1Aq/Historical_Data.csv') df.head() Date Article_ID Country_Code Sold_Units 0 20170817 1132 AT 1 1 20170818 1132 AT 1 2 20170821 1132 AT 1 3 20170822 1132 AT 1 4 20170906 1132 AT 1 ``` I have the above-given DataFrame. Note that the Date column is of type int64 and has missing dates 19th and 20th. I want to bring it to the format yyyy-mm-dd and impute the missing dates with values 0 in Article ID, Outlet Code and Sold Units. So far I have tried: ``` df['Date'] = pd.to_datetime(df['Date'].astype(str), format='%Y-%m-%d') ``` to get the dates in the required format. ``` Date Article_ID Outlet_Code Sold_Units 0 2017-08-17 1132 AT 1 1 2017-08-18 1132 AT 1 2 2017-08-21 1132 AT 1 3 2017-08-22 1132 AT 1 4 2017-09-06 1132 AT 1 ``` However, how do I impute the missing dates of 19th and 20th and impute the rows with 0s under the newly added date rows? Here is a snippet of what I have done which is returning a value error: cannot reindex from a duplicate axis. [![enter image description here](https://i.stack.imgur.com/gMUSL.png)](https://i.stack.imgur.com/gMUSL.png)
2019/10/20
[ "https://Stackoverflow.com/questions/58473505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11801923/" ]
You can use [`DataFrame.asfreq`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.asfreq.html) to reindex after deleting duplicates and then adding duplicate data and sorting: ``` df['Date'] = pd.to_datetime(df['Date'].astype(str), format='%Y-%m-%d') df2=df[df.duplicated('Date')].set_index('Date') new_df=df.drop_duplicates('Date').set_index('Date').asfreq('D',fill_value=0) new_df=new_df.append(df2).sort_index().reset_index() print(new_df) Date Article_ID Country_Code Sold_Units 0 2017-08-17 1132 AT 1 1 2017-08-17 1132 AT 1 2 2017-08-18 1132 AT 1 3 2017-08-19 0 0 0 4 2017-08-20 0 0 0 5 2017-08-21 1132 AT 1 6 2017-08-22 1132 AT 1 7 2017-08-23 0 0 0 8 2017-08-24 0 0 0 9 2017-08-25 0 0 0 10 2017-08-26 0 0 0 11 2017-08-27 0 0 0 12 2017-08-28 0 0 0 13 2017-08-29 0 0 0 14 2017-08-30 0 0 0 15 2017-08-31 0 0 0 16 2017-09-01 0 0 0 17 2017-09-02 0 0 0 18 2017-09-03 0 0 0 19 2017-09-04 0 0 0 20 2017-09-05 0 0 0 21 2017-09-06 1132 AT 1 ```
You can use: ``` df['Date'] = pd.to_datetime(df['Date'].astype(str), format='%Y-%m-%d',errors='coerce') ``` You don't miss your missing date, but it is represented by NaT. You've got something like this ``` Date Article_ID Outlet_Code Sold_Units 0 2017-08-17 1132 AT 1 1 2017-08-18 1132 AT 1 2 NaT 1132 AT 1 ```
65,433,445
I am new here I have this code ``` <div class="like-buttons"> <div class="liked"></div><button class="dislike like"><span class="countl">12</span></button> </div> ``` <https://codepen.io/Void0000/pen/oNzGmGr> and I need to make (with jQuery) some function, that when I will click on my button, it will be count +1 (eg: if it was 2 it becomes 3), and when I click again on it, it will count -1 (eg: if it was 3 it now becomes 2) and etc.
2020/12/24
[ "https://Stackoverflow.com/questions/65433445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14879896/" ]
Set event listeners on the classes, by jQuery. Like - ``` $('.like').onclick(function(){ let like = $(this). closest('.countd').html(); like = like + 1; }); ``` Do same for dislike button.
I am sorry, i wrote that i have two buttnos, it mistake, a have only 1 button, so i need this fucntion only for one button. So i clack once on button +1, i click once again on this button -1, etc< only 1 button!
65,433,445
I am new here I have this code ``` <div class="like-buttons"> <div class="liked"></div><button class="dislike like"><span class="countl">12</span></button> </div> ``` <https://codepen.io/Void0000/pen/oNzGmGr> and I need to make (with jQuery) some function, that when I will click on my button, it will be count +1 (eg: if it was 2 it becomes 3), and when I click again on it, it will count -1 (eg: if it was 3 it now becomes 2) and etc.
2020/12/24
[ "https://Stackoverflow.com/questions/65433445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14879896/" ]
According to @Shivam 's answer you can change like this; ``` $('.like').onclick(function(){ let like = $(this).closest('.countd').html(); if($(this).hasClass("clicked")){ $(this).removeClass("clicked"); like++; } else{ $(this).addClass("clicked"); like--; } $(this).closest('.countd').html(like) }); ``` Can you check this [Link](https://jsfiddle.net/cbalakus/xfh093yo/4/). I made some changes. ``` $(document).ready(function() { $('.like').click(function() { let like = parseInt($('.countl').html()); if ($(this).hasClass("clicked")) { $(this).removeClass("clicked"); like++; } else { $(this).addClass("clicked"); like--; } $('.countl').html(like) }); }); ```
Set event listeners on the classes, by jQuery. Like - ``` $('.like').onclick(function(){ let like = $(this). closest('.countd').html(); like = like + 1; }); ``` Do same for dislike button.
65,433,445
I am new here I have this code ``` <div class="like-buttons"> <div class="liked"></div><button class="dislike like"><span class="countl">12</span></button> </div> ``` <https://codepen.io/Void0000/pen/oNzGmGr> and I need to make (with jQuery) some function, that when I will click on my button, it will be count +1 (eg: if it was 2 it becomes 3), and when I click again on it, it will count -1 (eg: if it was 3 it now becomes 2) and etc.
2020/12/24
[ "https://Stackoverflow.com/questions/65433445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14879896/" ]
Set event listeners on the classes, by jQuery. Like - ``` $('.like').onclick(function(){ let like = $(this). closest('.countd').html(); like = like + 1; }); ``` Do same for dislike button.
Unfortunetly, its all not working = (
65,433,445
I am new here I have this code ``` <div class="like-buttons"> <div class="liked"></div><button class="dislike like"><span class="countl">12</span></button> </div> ``` <https://codepen.io/Void0000/pen/oNzGmGr> and I need to make (with jQuery) some function, that when I will click on my button, it will be count +1 (eg: if it was 2 it becomes 3), and when I click again on it, it will count -1 (eg: if it was 3 it now becomes 2) and etc.
2020/12/24
[ "https://Stackoverflow.com/questions/65433445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14879896/" ]
According to @Shivam 's answer you can change like this; ``` $('.like').onclick(function(){ let like = $(this).closest('.countd').html(); if($(this).hasClass("clicked")){ $(this).removeClass("clicked"); like++; } else{ $(this).addClass("clicked"); like--; } $(this).closest('.countd').html(like) }); ``` Can you check this [Link](https://jsfiddle.net/cbalakus/xfh093yo/4/). I made some changes. ``` $(document).ready(function() { $('.like').click(function() { let like = parseInt($('.countl').html()); if ($(this).hasClass("clicked")) { $(this).removeClass("clicked"); like++; } else { $(this).addClass("clicked"); like--; } $('.countl').html(like) }); }); ```
I am sorry, i wrote that i have two buttnos, it mistake, a have only 1 button, so i need this fucntion only for one button. So i clack once on button +1, i click once again on this button -1, etc< only 1 button!
65,433,445
I am new here I have this code ``` <div class="like-buttons"> <div class="liked"></div><button class="dislike like"><span class="countl">12</span></button> </div> ``` <https://codepen.io/Void0000/pen/oNzGmGr> and I need to make (with jQuery) some function, that when I will click on my button, it will be count +1 (eg: if it was 2 it becomes 3), and when I click again on it, it will count -1 (eg: if it was 3 it now becomes 2) and etc.
2020/12/24
[ "https://Stackoverflow.com/questions/65433445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14879896/" ]
According to @Shivam 's answer you can change like this; ``` $('.like').onclick(function(){ let like = $(this).closest('.countd').html(); if($(this).hasClass("clicked")){ $(this).removeClass("clicked"); like++; } else{ $(this).addClass("clicked"); like--; } $(this).closest('.countd').html(like) }); ``` Can you check this [Link](https://jsfiddle.net/cbalakus/xfh093yo/4/). I made some changes. ``` $(document).ready(function() { $('.like').click(function() { let like = parseInt($('.countl').html()); if ($(this).hasClass("clicked")) { $(this).removeClass("clicked"); like++; } else { $(this).addClass("clicked"); like--; } $('.countl').html(like) }); }); ```
Unfortunetly, its all not working = (
9,531,660
In Steve McConnell's "Code Complete", he describes testing an encryption program: > > I set up a test-data generator that fully exercised the encryption and > decryption parts of the program. It generated files of random > characters in random sizes. [...] For each random case, it generated > two copies of the random file, encrypted one copy, reinitialized > itself, decrypted the copy and then compared each byte in the > decrypted copy to the encrypted copy. If any bytes were different, the > generator printed all the information I needed to reproduce the error. > > > This test exhaustively tests the encryption "unit" and also performs some testing of other units - for example, those for file access and memory management. I do not see this as a standard unit test - that would involve testing the encryption unit in isolation. However, I also do not believe this is a standard integration test, since it concentrates so heavily on the encryption unit while using the others only in passing. How would you classify tests similar to this one?
2012/03/02
[ "https://Stackoverflow.com/questions/9531660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/200783/" ]
It is definitely **not a unit test**, since it is * not testing the smallest possible unit, which would be a single method of the core encryption unit * uses a lot of other functions as file access and memory management, instead of mocking them * is too slow for a unit test. Since the test is not going through the GUI (as mentioned in the comment below), it is **not a system or acceptance test**, unless the tests closely resemble customer requirements and drive the system under test just as if controlled through the GUI (for instance going under the hood by capturing the view's behavior from a MVC system and then removing the view by replaying the behavior). So in most cases, I'd call it an **integration test**: the integration of the first 3 elements of {encryption unit, file access unit, memory management unit, GUI} are tested. For **well designed tests**, the integration tests should focus on the interaction of the three units. The detailed functionality of each unit on its own should have been tested already in unit tests. Coming back to the quote you gave from Steve McConnell's "Code Complete", I would rather do the randomized encryption test by mocking the file access unit, and then on the integration test not have to test the core functionality of the encryption unit, but only test a couple of files (for situations like empty file; trivially encryptable file, e.g. only containing 'a'; hardly encryptable, e.g. already encrypted file; very large file; ...). In short: **Steve McConnell's test is a mixture of unit and integration test**, I guess that's what caused you asking this question...
I'd call it a functional test or a system test (although only a partial one -- there needs to be another test that fixed, known test vectors produce the correct known output). In principle, a unit test should execute no code from the project whatsoever, other than the unit under test. And *possibly* some other units that are independently tested without reference to the unit under test, and that are basically there to re-use code. This test doesn't take that approach. Pedantically it could be considered a unit test of the encrypt *executable*, though, if the way it works is to run the encrypt program with a command line. I don't think that's the case here, your quote talks about "the encryption and decryption parts of the program", but it's a similar situation. Anyway, unless (maybe) you're RMS re-implementing Unix from scratch in the small hours of the morning, you don't consider an executable to be a "unit", you break things down much smaller than that. Even aside from whether this test is constructed like a unit test, it may be that the encrypt "unit" is not truly a unit at all, but a collection of parts that themselves could be tested in isolation. By adding more dependency injection or otherwise redesigning the code, you could turn a less testable system into a more testable system and hence turn some of what used to be unit tests into integration tests. We don't know how testable this code really is. So perhaps you could describe it as an integration test of the encrypt module. It doesn't look like it came about as the result of a systematic attempt at integration testing, though, so it might be a bit misleading to call it that. I think people often describe tests as "unit tests" even though really they aren't, and it's something most people can live with. Especially if you're using a test framework with "unit" in its name, it's easy/lazy to just describe that as "the unit tests", when in fact you're running several different kinds of tests in a batch. Personally I don't think that the taxonomy of testing is hugely important, *except* that you shouldn't kid yourself that your tests are better than they really are, by thinking you've "unit tested everything" when really you haven't. I expect that if you're communicating with a large test team, the terminology becomes more important because everyone needs to know what they're talking about. But the largest test team I've ever worked with is only about 4 or 5 people.
410,550
`ls` returns output in several columns, whereas `ls|cat` returns byte-identical output with `ls -1` for directories I've tried. Still I see `ls -1` piped in answers, like `ls -1|wc -l`. Is there ever a reason to prefer `ls -1`? Why does `...|cat` change the output of `ls`?
2017/12/13
[ "https://unix.stackexchange.com/questions/410550", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/263916/" ]
`ls` tests whether output is going to a terminal. If the output isn't going to a terminal, then `-1` is the default. (This can be overridden by one of the `-C`, `-m`, or `-x` options.) Thus, when `ls` is used in a pipeline and you haven't overridden it with another option, `ls` will use `-1`. *You can rely on this because this behavior is required by POSIX* ### POSIX Specification POSIX requires `-1` as the default whenever output is not going to a terminal: [The POSIX spec](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/ls.html): > > The default format shall be to list one entry per line to standard > output; the exceptions are to terminals or when one of the -C, -m, or > -x options is specified. If the output is to a terminal, the format is implementation-defined. > > > Those three options which override the default single-column format are: > > -C > Write multi-text-column output with entries sorted down the columns, according to the collating sequence. The number of text > columns and the column separator characters are unspecified, but > should be adapted to the nature of the output device. This option > disables long format output. > > > -m > Stream output format; list pathnames across the page, separated by a <comma> character followed by a <space> character. Use a > <newline> character as the list terminator and after the separator > sequence when there is not room on a line for the next list entry. > This option disables long format output. > > > -x > The same as -C, except that the multi-text-column output is produced with entries sorted across, rather than down, the columns. > This option disables long format output. > > > ### GNU Documentation From [GNU ls manual](https://www.gnu.org/software/coreutils/manual/html_node/General-output-formatting.html#General-output-formatting): > > ‘-1’ > ‘--format=single-column’ > List one file per line. **This is > the default for ls when standard output is not a terminal**. See also > the -b and -q options to suppress direct output of newline characters > within a file name. [Emphasis added] > > > ### Examples Let's create three files: ``` $ touch file{1..3} ``` When output goes to a terminal, GNU `ls` chooses to use a multi-column format: ``` $ ls file1 file2 file3 ``` When output goes to a pipeline, the POSIX spec requires that single-column is the default: ``` $ ls | cat file1 file2 file3 ``` The three exceptions which override the default single-column behavior are `-m` for comma-separated, `-C` for columns sorted down, and `-x` for columns sorted across: ``` $ ls -m | cat file1, file2, file3 $ ls -C | cat file1 file2 file3 $ ls -x | cat file1 file2 file3 ```
When piping ls, ls cannot determine how much columns the console actually has (independant of the right-side command). So ls just does that on its own choice, or, in other words, this behaviour is **unstable** and may change in future versions. In contrast, `ls -1` was created for the purpose of counting or scripting in general, so its behaviour is stable.
410,550
`ls` returns output in several columns, whereas `ls|cat` returns byte-identical output with `ls -1` for directories I've tried. Still I see `ls -1` piped in answers, like `ls -1|wc -l`. Is there ever a reason to prefer `ls -1`? Why does `...|cat` change the output of `ls`?
2017/12/13
[ "https://unix.stackexchange.com/questions/410550", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/263916/" ]
* Why does piping the standard output change the behavior of `ls`?  Because it was designed that way.  The [POSIX Specification](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/ls.html) says: > > The default format shall be to list one entry per line to standard output; > the exceptions are to terminals > or when one of the **`-C`**, **`-m`**, or **`-x`** options is specified.  > If the output is to a terminal, the format is implementation-defined. > > > which is actually ambiguous about the default behavior (when not specified by an option like `-l` or `-1`) with output to a terminal, and the [GNU Coreutils documentation](https://www.gnu.org/software/coreutils/manual/html_node/ls-invocation.html) says > > If standard output is a terminal, > the output is in columns (sorted vertically) > and control characters are output as question marks; > otherwise, the output is listed one per line > and control characters are output as-is. > > > So you can see that output to a file will act the same as output to a pipe; that is, one entry per line, as if `-1` had been specified. * Why was it designed that way?  It might not be possible to know for sure (unless somebody can find some design notes), but I guess: + When `ls` is writing to a terminal, it expects that a human being is looking at the output.  People will prefer to get information in the minimum necessary number of lines, so stuff doesn’t scroll of the screen. + When `ls` is writing to a pipe, it expects that another program is reading the output.  It’s much easier for a program to read data that’s one value per line than to have to try to parse columns (since filenames can contain spaces). * Is there ever a reason to prefer `ls -1` when you’re writing to a file or a pipe?  No.
When piping ls, ls cannot determine how much columns the console actually has (independant of the right-side command). So ls just does that on its own choice, or, in other words, this behaviour is **unstable** and may change in future versions. In contrast, `ls -1` was created for the purpose of counting or scripting in general, so its behaviour is stable.
410,550
`ls` returns output in several columns, whereas `ls|cat` returns byte-identical output with `ls -1` for directories I've tried. Still I see `ls -1` piped in answers, like `ls -1|wc -l`. Is there ever a reason to prefer `ls -1`? Why does `...|cat` change the output of `ls`?
2017/12/13
[ "https://unix.stackexchange.com/questions/410550", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/263916/" ]
`ls` tests whether output is going to a terminal. If the output isn't going to a terminal, then `-1` is the default. (This can be overridden by one of the `-C`, `-m`, or `-x` options.) Thus, when `ls` is used in a pipeline and you haven't overridden it with another option, `ls` will use `-1`. *You can rely on this because this behavior is required by POSIX* ### POSIX Specification POSIX requires `-1` as the default whenever output is not going to a terminal: [The POSIX spec](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/ls.html): > > The default format shall be to list one entry per line to standard > output; the exceptions are to terminals or when one of the -C, -m, or > -x options is specified. If the output is to a terminal, the format is implementation-defined. > > > Those three options which override the default single-column format are: > > -C > Write multi-text-column output with entries sorted down the columns, according to the collating sequence. The number of text > columns and the column separator characters are unspecified, but > should be adapted to the nature of the output device. This option > disables long format output. > > > -m > Stream output format; list pathnames across the page, separated by a <comma> character followed by a <space> character. Use a > <newline> character as the list terminator and after the separator > sequence when there is not room on a line for the next list entry. > This option disables long format output. > > > -x > The same as -C, except that the multi-text-column output is produced with entries sorted across, rather than down, the columns. > This option disables long format output. > > > ### GNU Documentation From [GNU ls manual](https://www.gnu.org/software/coreutils/manual/html_node/General-output-formatting.html#General-output-formatting): > > ‘-1’ > ‘--format=single-column’ > List one file per line. **This is > the default for ls when standard output is not a terminal**. See also > the -b and -q options to suppress direct output of newline characters > within a file name. [Emphasis added] > > > ### Examples Let's create three files: ``` $ touch file{1..3} ``` When output goes to a terminal, GNU `ls` chooses to use a multi-column format: ``` $ ls file1 file2 file3 ``` When output goes to a pipeline, the POSIX spec requires that single-column is the default: ``` $ ls | cat file1 file2 file3 ``` The three exceptions which override the default single-column behavior are `-m` for comma-separated, `-C` for columns sorted down, and `-x` for columns sorted across: ``` $ ls -m | cat file1, file2, file3 $ ls -C | cat file1 file2 file3 $ ls -x | cat file1 file2 file3 ```
* Why does piping the standard output change the behavior of `ls`?  Because it was designed that way.  The [POSIX Specification](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/ls.html) says: > > The default format shall be to list one entry per line to standard output; > the exceptions are to terminals > or when one of the **`-C`**, **`-m`**, or **`-x`** options is specified.  > If the output is to a terminal, the format is implementation-defined. > > > which is actually ambiguous about the default behavior (when not specified by an option like `-l` or `-1`) with output to a terminal, and the [GNU Coreutils documentation](https://www.gnu.org/software/coreutils/manual/html_node/ls-invocation.html) says > > If standard output is a terminal, > the output is in columns (sorted vertically) > and control characters are output as question marks; > otherwise, the output is listed one per line > and control characters are output as-is. > > > So you can see that output to a file will act the same as output to a pipe; that is, one entry per line, as if `-1` had been specified. * Why was it designed that way?  It might not be possible to know for sure (unless somebody can find some design notes), but I guess: + When `ls` is writing to a terminal, it expects that a human being is looking at the output.  People will prefer to get information in the minimum necessary number of lines, so stuff doesn’t scroll of the screen. + When `ls` is writing to a pipe, it expects that another program is reading the output.  It’s much easier for a program to read data that’s one value per line than to have to try to parse columns (since filenames can contain spaces). * Is there ever a reason to prefer `ls -1` when you’re writing to a file or a pipe?  No.
26,627,096
I'm trying to create a text-based adventure game. I'm thinking I want the map to be represented by different nodes where each node corresponds to a distinct location and has node pointer variables (left, forward, and right) that should point to another node in the respective direction. I tried to implement it as a linked list, but with this data structure, I could only have each node point to one other node. I want each node to point to three other nodes. Which data structure could I use to implement this or is this even possible?
2014/10/29
[ "https://Stackoverflow.com/questions/26627096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2280464/" ]
A linked datastructure would do a good job of doing what you want: example: ``` class location { std::string loc_name; std::vector<std::pair<std::string,location*>> connections; std::string description; public: bool add_link(location* loc, std::string dicription_to, std::string dicription_from); //other parameters + functions to manage class } ``` This would allow you to create locations such as: ``` location* loc = new location("graveyard"); loc->description = "A spooky graveyard on a hill, a cool mist floats amongst the gravestones and monuments"; loc->add_link(crypt /*previously defined*/, "An imposing mausoleum with an open door, steps inside lead down into darkness", "Moonlight filters down from the top of some steps, a way out?"); loc.add_link(spooky_house /*previously defined*/, "The North gate of the graveyard", "The entrance to the house's spooky graveyard"); ``` I'd reccommend creating a map file you could read in though. Possibly using a template like this: locations file: ``` /*locations, format = "name; description"*/ Spooky House; house_description Crypt; crypt_description Graveyard; A spooky graveyard on a hill, a cool mist floats amongst the gravestones and monuments ``` links file: ``` /*links, format = "index # (from); index # (to); description (from->to); description (to->from)"*/ 3;2;An imposing mausoleum with an open door, steps inside lead down into darkness; Moonlight filters down from the top of some steps, a way out? 3;1;The North gate of the graveyard;The entrance to the house's spooky graveyard; ``` Loading the map would be as simple as reading in all the locations and pushing them into a vector for storage, then adding the links in to connect them.
You could implement a custom linked datastructure with linked positions on the map like this: ``` struct Map_Node{ Map_Node *left; Map_Node *right; Map_Node *forward; /* other needed field*/ }; ``` Then, you need to do the memory management on your own. For example by using smart pointers. ``` std::shared_ptr<Map_Node> entry{ new MapNode }; std::shared_ptr<Map_Node> hallway{ new MapNode }; entry->forward = &*hallway; //and so on ``` An easier but less efficient for getting the next file would be a std::map. If each position has its unique ID, e.g. a string, you could store the IDs of the neighboring fields and move freely on the map by using the ID. ``` struct Map_Node{ std::string name; std::string left; std::string right; std::string forward; /* other needed field*/ }; std::map<std::string, Map_Node> map; Map_Node entry; entry.name = "entry"; map[entry.name] = entry; Map_Node hallway; hallway.name = "hallway"; map[hallway.name] = hallway; //links between: map["entry"].forward = "hallway"; ```
35,728,722
I'm writting some code that uses a serialized file. The file is called **alcala.ser** and is in **utils**, a subfolder of **java**. The class calling the file is in the same folder. Here's the code: ``` InputStream file = new FileInputStream("/alcala.ser"); ``` I also tried: ``` InputStream file = new FileInputStream("alcala.ser"); ``` In both cases, I get > > java.io.FileNotFoundException: /alcala.ser: open failed: ENOENT (No > such file or directory) > > > How should I reference the file? Thanks in advance.
2016/03/01
[ "https://Stackoverflow.com/questions/35728722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5120619/" ]
> > The file is called alcala.ser and is in utils, a subfolder of java. > > > Move the file out of there and into `assets/`. Then, use `AssetManager` to `open()` an `InputStream` on the asset.
Check External and Internal Storage option in <http://developer.android.com/guide/topics/data/data-storage.html>. Depending on how do you want to handle privacy you have to chose one or the other.
42,454
I have an integrated ION GPU, which is supported by the proprietary drivers and I've never been able to get the open source drivers to work. I would like my left screen to be normal, but the right hand screen to be rotated. How do I achieve this?
2012/07/06
[ "https://unix.stackexchange.com/questions/42454", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/19208/" ]
It took me a while to work this out, so I wanted to share it with others.I will assume that the nvidia drivers and `nvidia-settings` are installed. (On Arch, run `sudo pacman -S nvidia nvidia-utils`.) First, we need to generate a `xorg.conf` using `nvidia-settings`. From a GUI terminal, run `sudo nvidia-settings`. 1. Select "X Server Display Configuration" from the menu on the left. 2. On the right-hand side, change "Configuration" to "Separate X screen (requires X restart". 3. Check "Enable Xinerama". 4. Click "Save to X Configuration File"; `/etc/xorg.conf` will work, or you could add it as a new file to `/etc/xorg.conf.d` - e.g. `/etc/xorg.conf.d/10-monitors.conf`. Now, we need to edit this file. Open it in your favourite editor as `root`. For example, run `gksu gedit /etc/xorg.conf` or `sudo vim /etc/xorg.conf`. Find the correct `Section "Screen"`. I did this by finding the correct `Section "Monitor"` and then finding the corresponding `Section "Screen"`. Find the line that looks like ``` Option "metamodes" "DFP-1: 1920x1080 +0+0" ``` and add `{ Rotation=Left }`, so it looks like ``` Option "metamodes" "DFP-1: 1920x1080 +0+0 { Rotation=Left }". ``` > > *Note* `DFP-1` could be `DFP-0`, depending on which monitor you are rotating; the resolution is also likely to be different. > > > Example ------- My `xorg.conf` reads as follows ``` Section "ServerLayout" Identifier "Layout0" Screen 0 "Screen0" 0 28 Screen 1 "Screen1" 1280 0 InputDevice "Keyboard0" "CoreKeyboard" InputDevice "Mouse0" "CorePointer" Option "Xinerama" "1" EndSection Section "Files" EndSection Section "InputDevice" Identifier "Mouse0" Driver "mouse" Option "Protocol" "auto" Option "Device" "/dev/psaux" Option "Emulate3Buttons" "no" Option "ZAxisMapping" "4 5" EndSection Section "InputDevice" Identifier "Keyboard0" Driver "kbd" EndSection Section "InputClass" Identifier "Keyboard Defaults" MatchIsKeyboard "yes" Option "XkbLayout" "gb" EndSection Section "Monitor" Identifier "Monitor1" VendorName "Unknown" ModelName "HP w2228h" HorizSync 24.0 - 83.0 VertRefresh 48.0 - 76.0 Option "DPMS" EndSection Section "Monitor" Identifier "Monitor0" VendorName "Unknown" ModelName "DELL 1703FP" HorizSync 30.0 - 80.0 VertRefresh 56.0 - 76.0 Option "DPMS" EndSection Section "Device" Identifier "Device1" Driver "nvidia" VendorName "NVIDIA Corporation" BoardName "ION" BusID "PCI:3:0:0" Screen 1 EndSection Section "Device" Identifier "Device0" Driver "nvidia" VendorName "NVIDIA Corporation" BoardName "ION" BusID "PCI:3:0:0" Screen 0 EndSection Section "Screen" Identifier "Screen1" Device "Device1" Monitor "Monitor1" DefaultDepth 24 Option "TwinView" "On" Option "Stereo" "0" Option "metamodes" "DFP-1: 1920x1080 +0+0 { Rotation=Left }" SubSection "Display" Depth 24 EndSubSection EndSection Section "Screen" Identifier "Screen0" Device "Device0" Monitor "Monitor0" DefaultDepth 24 Option "TwinView" "On" Option "Stereo" "0" Option "nvidiaXineramaInfoOrder" "DFP-0" Option "metamodes" "DFP-0: 1280x1024 +0+0" SubSection "Display" Depth 24 EndSubSection EndSection Section "Extensions" Option "Composite" "Disable" EndSection ``` ### References 1. [Linux Dual Monitor Setup: Nvidia & Xinerama Guide: Rotating just one monitor](http://zuttobenkyou.wordpress.com/2009/10/04/linux-nvidia-xinerama-guide-rotating-just-one-monitor-in-a-dual-head-setup/)
It seems the most recent version of the closed source NVIDIA drivers supports randr (see <http://www.phoronix.com/scan.php?page=news_item&px=MTA5NTY>). Just use the most recent driver and a RandR front-end of your choice. For example arandr will allow you to move monitors around and alter their orientation.
54,051,703
I have a created a simple Azure Logic App that sends a file via FTP to a customer. I have tested the Logic App and it works to my VM. I have an issue however that my customer whitelists IP addresses that FTP to them and Azure will only supply you with regional IP addresses meaning anyone who uses Logic App in my region will have access to my customer. I have done some reading and it seems that the recommended way to do this is by using API Management as a Reverse Proxy. <https://blogs.msdn.microsoft.com/david_burgs_blog/2017/05/19/whitelisting-and-logic-apps/> Can someone explain how to do this? It seems you ftp to your API Management Gateway and it then forwards the request to customer. Its the forwarding bit i don't understand how to do.
2019/01/05
[ "https://Stackoverflow.com/questions/54051703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10871330/" ]
You get `full_name` with these structs ( I specified only the relevant keys) ``` struct Root: Decodable { let graphql : Graphql } struct Graphql: Decodable { let user : User } struct User: Decodable { let fullName : String } ``` and decode the data ``` let data = Data(jsonData.utf8) do { let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase let result = try decoder.decode(Root.self, from: data) let fullname = result.graphql.user.fullName print(fullname) } catch { print(error) } ```
There are many ways of doing this First-Method: ``` do { let responseData = Data(data.utf8) let decodeData = try JSONDecoder().decode(Controller.self, from: responseData) if (decodeData.ErrorCode! == "0") { //Success } else { //Failure } } catch let jsonErr { //Failure } ``` Second-Method: ``` do { if let responseData = response.data, let decodedData = try JSONSerialization.jsonObject(with: responseData, options: []) as? [[String: Any]] { print(decodedData) } } catch let error as NSError { print(error) } ```
123,447
How do we get the url to thumbnail image of of a product through rest API. `/V1/products/{sku}/media` would get us the relative url such as `"/m/b/mb01-blue-0.jpg"` and the image url would be `baseurl/catalog/product/m/b/mb01-blue-0.jpg` This works fine. But how do we get the thumbnail which usually resides in the cache folder.
2016/06/29
[ "https://magento.stackexchange.com/questions/123447", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/41556/" ]
If you need the complete path of the thumbnail image with Magento 2 cache system through API, you can create your custom API based on the native ProductRepository class. Create a new module. (explained in other posts) Create a **etc/webapi.xml** file : ``` <?xml version="1.0"?> <routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd"> <route url="/V1/custom/products/{sku}" method="GET"> <service class="Vendor\ModuleName\Api\ProductRepositoryInterface" method="get"/> <resources> <resource ref="Magento_Catalog::products"/> </resources> </route> </routes> ``` Create a **etc/di.xml** file : ``` <?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <preference for="Vendor\ModuleName\Api\ProductRepositoryInterface" type="Vendor\ModuleName\Model\ProductRepository" /> </config> ``` Create your interface **Api\ProductRepositoryInterface.php** : ``` namespace Vendor\ModuleName\Api; /** * @api */ interface ProductRepositoryInterface { /** * Get info about product by product SKU * * @param string $sku * @param bool $editMode * @param int|null $storeId * @param bool $forceReload * @return \Magento\Catalog\Api\Data\ProductInterface * @throws \Magento\Framework\Exception\NoSuchEntityException */ public function get($sku, $editMode = false, $storeId = null, $forceReload = false); } ``` Create your model **Model\ProductRepository.php** : ``` namespace Vendor\ModuleName\Model; class ProductRepository implements \Magento\Catalog\Api\ProductRepositoryInterface { /** * @var \Magento\Catalog\Model\ProductFactory */ protected $productFactory; /** * @var Product[] */ protected $instances = []; /** * @var \Magento\Catalog\Model\ResourceModel\Product */ protected $resourceModel; /** * @var \Magento\Store\Model\StoreManagerInterface */ protected $storeManager; /** * @var \Magento\Catalog\Helper\ImageFactory */ protected $helperFactory; /** * @var \Magento\Store\Model\App\Emulation */ protected $appEmulation; /** * ProductRepository constructor. * @param \Magento\Catalog\Model\ProductFactory $productFactory * @param \Magento\Catalog\Model\ResourceModel\Product $resourceModel * @param \Magento\Store\Model\StoreManagerInterface $storeManager */ public function __construct( \Magento\Catalog\Model\ProductFactory $productFactory, \Magento\Catalog\Model\ResourceModel\Product $resourceModel, \Magento\Store\Model\StoreManagerInterface $storeManager, \Magento\Store\Model\App\Emulation $appEmulation, \Magento\Catalog\Helper\ImageFactory $helperFactory ) { $this->productFactory = $productFactory; $this->storeManager = $storeManager; $this->resourceModel = $resourceModel; $this->helperFactory = $helperFactory; $this->appEmulation = $appEmulation; } /** * {@inheritdoc} */ public function get($sku, $editMode = false, $storeId = null, $forceReload = false) { $cacheKey = $this->getCacheKey([$editMode, $storeId]); if (!isset($this->instances[$sku][$cacheKey]) || $forceReload) { $product = $this->productFactory->create(); $productId = $this->resourceModel->getIdBySku($sku); if (!$productId) { throw new NoSuchEntityException(__('Requested product doesn\'t exist')); } if ($editMode) { $product->setData('_edit_mode', true); } if ($storeId !== null) { $product->setData('store_id', $storeId); } else { // Start Custom code here $storeId = $this->storeManager->getStore()->getId(); } $product->load($productId); $this->appEmulation->startEnvironmentEmulation($storeId, \Magento\Framework\App\Area::AREA_FRONTEND, true); $imageUrl = $this->getImage($product, 'product_thumbnail_image')->getUrl(); $customAttribute = $product->setCustomAttribute('thumbnail', $imageUrl); $this->appEmulation->stopEnvironmentEmulation(); // End Custom code here $this->instances[$sku][$cacheKey] = $product; $this->instancesById[$product->getId()][$cacheKey] = $product; } return $this->instances[$sku][$cacheKey]; } /** * Retrieve product image * * @param \Magento\Catalog\Model\Product $product * @param string $imageId * @param array $attributes * @return \Magento\Catalog\Block\Product\Image */ public function getImage($product, $imageId, $attributes = []) { $image = $this->helperFactory->create()->init($product, $imageId) ->constrainOnly(true) ->keepAspectRatio(true) ->keepTransparency(true) ->keepFrame(false) ->resize(75, 75); return $image; } } ``` **Access** Go to `/rest/V1/custom/products/{sku}` You should retrieve the thumbnail image with the image frontend URL cached : ``` <custom_attributes> <item> <attribute_code>thumbnail</attribute_code> <value>http://{domain}/media/catalog/product/cache/1/thumbnail/75x75/e9c3970ab036de70892d86c6d221abfe/s/r/{imageName}.jpg</value> </item> </custom_attributes> ``` **Comments :** The third parameter of the function *startEnvironmentEmulation* is used to force the use of frontend area if you are already on the same storeId. (usefull for API area) I do not test this custom API, you may adapt the code but the logic is correct but I already tested the part to retrieve the image URL in other custom API. This workaround avoid you to have this kind of errors : ``` http://XXXX.com/pub/static/webapi_rest/_view/en_US/Magento_Catalog/images/product/placeholder/.jpg Uncaught Magento\Framework\View\Asset\File\NotFoundException: Unable to resolve the source file for 'adminhtml/_view/en_US/Magento_Catalog/images/product/placeh‌​older/.jpg' ```
It should be possible with the following url: `/rest/V1/products/{sku}` This will return the product and there should be a node for custom\_attributes which contains a thumbnail link ``` <custom_attributes> <item> <attribute_code>thumbnail</attribute_code> <value>/m/b/mb01-blue-0.jpg</value> </item> </custom_attributes> ```
123,447
How do we get the url to thumbnail image of of a product through rest API. `/V1/products/{sku}/media` would get us the relative url such as `"/m/b/mb01-blue-0.jpg"` and the image url would be `baseurl/catalog/product/m/b/mb01-blue-0.jpg` This works fine. But how do we get the thumbnail which usually resides in the cache folder.
2016/06/29
[ "https://magento.stackexchange.com/questions/123447", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/41556/" ]
The reasons why Magento doesn't provide this functionality out of the box are next: * To return image thumbnail URL as a part of Product with attribute or extension attribute that will mean to introduce support of Read-Only (non-modifiable) attributes in Data Objects. Because URL is a representation of some data. Data taken from different sources, as domain name belongs to system configuration, but path belongs to Catalog module. * For now Magento doesn't support read-only attributes or service for Query API. As a long term solution – Query APIs should address this question, as they will provide an ability for read-only and computed fields. As a solution we could provide for community nearest time – we could implement/introduce dedicated URL resolver service which will return URL for specific entity types (like Product, Category, Image etc.) For the same reason we don't provide Product URL as a part of ProductInterface Here is my response devoted to this issue (Product URL): <https://community.magento.com/t5/Programming-Questions/Retrieving-the-product-URL-for-the-current-store-from-a/m-p/55387/highlight/true#M1400>
It should be possible with the following url: `/rest/V1/products/{sku}` This will return the product and there should be a node for custom\_attributes which contains a thumbnail link ``` <custom_attributes> <item> <attribute_code>thumbnail</attribute_code> <value>/m/b/mb01-blue-0.jpg</value> </item> </custom_attributes> ```
123,447
How do we get the url to thumbnail image of of a product through rest API. `/V1/products/{sku}/media` would get us the relative url such as `"/m/b/mb01-blue-0.jpg"` and the image url would be `baseurl/catalog/product/m/b/mb01-blue-0.jpg` This works fine. But how do we get the thumbnail which usually resides in the cache folder.
2016/06/29
[ "https://magento.stackexchange.com/questions/123447", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/41556/" ]
If you need the complete path of the thumbnail image with Magento 2 cache system through API, you can create your custom API based on the native ProductRepository class. Create a new module. (explained in other posts) Create a **etc/webapi.xml** file : ``` <?xml version="1.0"?> <routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd"> <route url="/V1/custom/products/{sku}" method="GET"> <service class="Vendor\ModuleName\Api\ProductRepositoryInterface" method="get"/> <resources> <resource ref="Magento_Catalog::products"/> </resources> </route> </routes> ``` Create a **etc/di.xml** file : ``` <?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <preference for="Vendor\ModuleName\Api\ProductRepositoryInterface" type="Vendor\ModuleName\Model\ProductRepository" /> </config> ``` Create your interface **Api\ProductRepositoryInterface.php** : ``` namespace Vendor\ModuleName\Api; /** * @api */ interface ProductRepositoryInterface { /** * Get info about product by product SKU * * @param string $sku * @param bool $editMode * @param int|null $storeId * @param bool $forceReload * @return \Magento\Catalog\Api\Data\ProductInterface * @throws \Magento\Framework\Exception\NoSuchEntityException */ public function get($sku, $editMode = false, $storeId = null, $forceReload = false); } ``` Create your model **Model\ProductRepository.php** : ``` namespace Vendor\ModuleName\Model; class ProductRepository implements \Magento\Catalog\Api\ProductRepositoryInterface { /** * @var \Magento\Catalog\Model\ProductFactory */ protected $productFactory; /** * @var Product[] */ protected $instances = []; /** * @var \Magento\Catalog\Model\ResourceModel\Product */ protected $resourceModel; /** * @var \Magento\Store\Model\StoreManagerInterface */ protected $storeManager; /** * @var \Magento\Catalog\Helper\ImageFactory */ protected $helperFactory; /** * @var \Magento\Store\Model\App\Emulation */ protected $appEmulation; /** * ProductRepository constructor. * @param \Magento\Catalog\Model\ProductFactory $productFactory * @param \Magento\Catalog\Model\ResourceModel\Product $resourceModel * @param \Magento\Store\Model\StoreManagerInterface $storeManager */ public function __construct( \Magento\Catalog\Model\ProductFactory $productFactory, \Magento\Catalog\Model\ResourceModel\Product $resourceModel, \Magento\Store\Model\StoreManagerInterface $storeManager, \Magento\Store\Model\App\Emulation $appEmulation, \Magento\Catalog\Helper\ImageFactory $helperFactory ) { $this->productFactory = $productFactory; $this->storeManager = $storeManager; $this->resourceModel = $resourceModel; $this->helperFactory = $helperFactory; $this->appEmulation = $appEmulation; } /** * {@inheritdoc} */ public function get($sku, $editMode = false, $storeId = null, $forceReload = false) { $cacheKey = $this->getCacheKey([$editMode, $storeId]); if (!isset($this->instances[$sku][$cacheKey]) || $forceReload) { $product = $this->productFactory->create(); $productId = $this->resourceModel->getIdBySku($sku); if (!$productId) { throw new NoSuchEntityException(__('Requested product doesn\'t exist')); } if ($editMode) { $product->setData('_edit_mode', true); } if ($storeId !== null) { $product->setData('store_id', $storeId); } else { // Start Custom code here $storeId = $this->storeManager->getStore()->getId(); } $product->load($productId); $this->appEmulation->startEnvironmentEmulation($storeId, \Magento\Framework\App\Area::AREA_FRONTEND, true); $imageUrl = $this->getImage($product, 'product_thumbnail_image')->getUrl(); $customAttribute = $product->setCustomAttribute('thumbnail', $imageUrl); $this->appEmulation->stopEnvironmentEmulation(); // End Custom code here $this->instances[$sku][$cacheKey] = $product; $this->instancesById[$product->getId()][$cacheKey] = $product; } return $this->instances[$sku][$cacheKey]; } /** * Retrieve product image * * @param \Magento\Catalog\Model\Product $product * @param string $imageId * @param array $attributes * @return \Magento\Catalog\Block\Product\Image */ public function getImage($product, $imageId, $attributes = []) { $image = $this->helperFactory->create()->init($product, $imageId) ->constrainOnly(true) ->keepAspectRatio(true) ->keepTransparency(true) ->keepFrame(false) ->resize(75, 75); return $image; } } ``` **Access** Go to `/rest/V1/custom/products/{sku}` You should retrieve the thumbnail image with the image frontend URL cached : ``` <custom_attributes> <item> <attribute_code>thumbnail</attribute_code> <value>http://{domain}/media/catalog/product/cache/1/thumbnail/75x75/e9c3970ab036de70892d86c6d221abfe/s/r/{imageName}.jpg</value> </item> </custom_attributes> ``` **Comments :** The third parameter of the function *startEnvironmentEmulation* is used to force the use of frontend area if you are already on the same storeId. (usefull for API area) I do not test this custom API, you may adapt the code but the logic is correct but I already tested the part to retrieve the image URL in other custom API. This workaround avoid you to have this kind of errors : ``` http://XXXX.com/pub/static/webapi_rest/_view/en_US/Magento_Catalog/images/product/placeholder/.jpg Uncaught Magento\Framework\View\Asset\File\NotFoundException: Unable to resolve the source file for 'adminhtml/_view/en_US/Magento_Catalog/images/product/placeh‌​older/.jpg' ```
The reasons why Magento doesn't provide this functionality out of the box are next: * To return image thumbnail URL as a part of Product with attribute or extension attribute that will mean to introduce support of Read-Only (non-modifiable) attributes in Data Objects. Because URL is a representation of some data. Data taken from different sources, as domain name belongs to system configuration, but path belongs to Catalog module. * For now Magento doesn't support read-only attributes or service for Query API. As a long term solution – Query APIs should address this question, as they will provide an ability for read-only and computed fields. As a solution we could provide for community nearest time – we could implement/introduce dedicated URL resolver service which will return URL for specific entity types (like Product, Category, Image etc.) For the same reason we don't provide Product URL as a part of ProductInterface Here is my response devoted to this issue (Product URL): <https://community.magento.com/t5/Programming-Questions/Retrieving-the-product-URL-for-the-current-store-from-a/m-p/55387/highlight/true#M1400>
12,848,345
I'm using a dictionary in python to make what is basically an infinite 2d array by using a tuple as the key ``` grid = {} grid[(0,0)] = cell() ``` the value 'cell' is a new object. Can I have, say, a function within that object that is able to get its key value? ie. (0,0) I could just put that data in the object itself but then I'd have it existing twice which seems like bad programming. Thanks!
2012/10/11
[ "https://Stackoverflow.com/questions/12848345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1432808/" ]
``` class cell(object): def my_idx(self,grid): return grid.keys()[grid.values().index(self)] ``` then call it ``` some_cell.my_idx(grid) ```
This should work: ``` class Cell(object): def get_idx(self, grid): """ >>> cell = Cell() >>> cell.get_idx({(0, 0): cell}) (0, 0) >>> cell = Cell() >>> cell.get_idx({(0, 0): Cell(), (1, 1): cell, (2, 2): Cell()}) (1, 1) """ return [x[0] for x in grid.items() if x[1] == self][0] ``` Just notice that it won't give you realiable results if the object is more than once in the dict and it would raise an exception if the object isn't in the dict. Also it could be slow on very large grids.
12,848,345
I'm using a dictionary in python to make what is basically an infinite 2d array by using a tuple as the key ``` grid = {} grid[(0,0)] = cell() ``` the value 'cell' is a new object. Can I have, say, a function within that object that is able to get its key value? ie. (0,0) I could just put that data in the object itself but then I'd have it existing twice which seems like bad programming. Thanks!
2012/10/11
[ "https://Stackoverflow.com/questions/12848345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1432808/" ]
``` class cell(object): def my_idx(self,grid): return grid.keys()[grid.values().index(self)] ``` then call it ``` some_cell.my_idx(grid) ```
Your questions implies that there's a 1:1 mapping between dict keys and their values, which is not true. Take this code: ``` grid = {} c = cell() grid[(0,0)] = c grid[(0,1)] = c ``` That's perfectly valid in python, even if your use case does not allow it. What index should the function you are looking for return for `c`? Storing the data twice does not have to be bad programming style, but your memory might be limited. If your `cell` needs to know it's index, it must have that data. If you see your cells as a list of items, the dict becomes just a index for faster access. And having indexes for faster access is of course no bad programming style. ;-)
12,848,345
I'm using a dictionary in python to make what is basically an infinite 2d array by using a tuple as the key ``` grid = {} grid[(0,0)] = cell() ``` the value 'cell' is a new object. Can I have, say, a function within that object that is able to get its key value? ie. (0,0) I could just put that data in the object itself but then I'd have it existing twice which seems like bad programming. Thanks!
2012/10/11
[ "https://Stackoverflow.com/questions/12848345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1432808/" ]
``` class cell(object): def my_idx(self,grid): return grid.keys()[grid.values().index(self)] ``` then call it ``` some_cell.my_idx(grid) ```
Give your `cell` class an `address` attribute, which is a two-tuple, e.g. `(0,0)`. Give the `cell` class a `__hash__` method, which returns `hash(self.address)`. ``` class cell: def __init__(self,address): self.address = address def __hash__(self): return hash(self.address) def __eq__(self): return hash(self) == hash(other) ``` You can still access cells by their address, but the cells know where they belong. ``` >>> c = cell((0,0)) >>> c <so.cell instance at 0xb74c6a2c> >>> grid = dict() >>> grid[c] = c >>> grid[c] <so.cell instance at 0xb74c6a2c> >>> grid[(0,0)] <so.cell instance at 0xb74c6a2c> ``` I'm not sure what else your `cell`s need to know and/or do, but if you're just doing numerical stuff here, I'd highly recommend the [scipy.sparse](http://docs.scipy.org/doc/scipy/reference/sparse.html) module.
12,848,345
I'm using a dictionary in python to make what is basically an infinite 2d array by using a tuple as the key ``` grid = {} grid[(0,0)] = cell() ``` the value 'cell' is a new object. Can I have, say, a function within that object that is able to get its key value? ie. (0,0) I could just put that data in the object itself but then I'd have it existing twice which seems like bad programming. Thanks!
2012/10/11
[ "https://Stackoverflow.com/questions/12848345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1432808/" ]
``` class cell(object): def my_idx(self,grid): return grid.keys()[grid.values().index(self)] ``` then call it ``` some_cell.my_idx(grid) ```
There are two separate issues here... first, to access the grid from within cell, I would have `cell`'s constructor take a reference to grid as a mandatory argument. ``` grid = {} grid[(0,0)] = cell(grid) ``` and ``` class cell: def __init__(self, gridRef): self.grid = gridRef ``` But, accessing the key is more challenging. One reason is that a dictionary is not a one-to-one mapping, so the same cell object may have multiple keys in your dictionary. You'd need to iterate over your keys and look for it, either manually or through flipping the dictionary. How about making your `cell` constructor take the key as well? ``` grid = {} grid[(0,0)] = cell(grid, (0,0)) ``` If that's too redundant, then maybe something like this? ``` def addToGrid(myDict, myCell): myDict[myCell.key()] = myCell ``` and then... ``` grid = {} addToGrid(grid, cell(grid, (0, 0))) ``` where your `cell` class takes the dictionary key as the second argument and returns it via the `key()` method.
12,848,345
I'm using a dictionary in python to make what is basically an infinite 2d array by using a tuple as the key ``` grid = {} grid[(0,0)] = cell() ``` the value 'cell' is a new object. Can I have, say, a function within that object that is able to get its key value? ie. (0,0) I could just put that data in the object itself but then I'd have it existing twice which seems like bad programming. Thanks!
2012/10/11
[ "https://Stackoverflow.com/questions/12848345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1432808/" ]
This should work: ``` class Cell(object): def get_idx(self, grid): """ >>> cell = Cell() >>> cell.get_idx({(0, 0): cell}) (0, 0) >>> cell = Cell() >>> cell.get_idx({(0, 0): Cell(), (1, 1): cell, (2, 2): Cell()}) (1, 1) """ return [x[0] for x in grid.items() if x[1] == self][0] ``` Just notice that it won't give you realiable results if the object is more than once in the dict and it would raise an exception if the object isn't in the dict. Also it could be slow on very large grids.
Give your `cell` class an `address` attribute, which is a two-tuple, e.g. `(0,0)`. Give the `cell` class a `__hash__` method, which returns `hash(self.address)`. ``` class cell: def __init__(self,address): self.address = address def __hash__(self): return hash(self.address) def __eq__(self): return hash(self) == hash(other) ``` You can still access cells by their address, but the cells know where they belong. ``` >>> c = cell((0,0)) >>> c <so.cell instance at 0xb74c6a2c> >>> grid = dict() >>> grid[c] = c >>> grid[c] <so.cell instance at 0xb74c6a2c> >>> grid[(0,0)] <so.cell instance at 0xb74c6a2c> ``` I'm not sure what else your `cell`s need to know and/or do, but if you're just doing numerical stuff here, I'd highly recommend the [scipy.sparse](http://docs.scipy.org/doc/scipy/reference/sparse.html) module.
12,848,345
I'm using a dictionary in python to make what is basically an infinite 2d array by using a tuple as the key ``` grid = {} grid[(0,0)] = cell() ``` the value 'cell' is a new object. Can I have, say, a function within that object that is able to get its key value? ie. (0,0) I could just put that data in the object itself but then I'd have it existing twice which seems like bad programming. Thanks!
2012/10/11
[ "https://Stackoverflow.com/questions/12848345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1432808/" ]
Your questions implies that there's a 1:1 mapping between dict keys and their values, which is not true. Take this code: ``` grid = {} c = cell() grid[(0,0)] = c grid[(0,1)] = c ``` That's perfectly valid in python, even if your use case does not allow it. What index should the function you are looking for return for `c`? Storing the data twice does not have to be bad programming style, but your memory might be limited. If your `cell` needs to know it's index, it must have that data. If you see your cells as a list of items, the dict becomes just a index for faster access. And having indexes for faster access is of course no bad programming style. ;-)
Give your `cell` class an `address` attribute, which is a two-tuple, e.g. `(0,0)`. Give the `cell` class a `__hash__` method, which returns `hash(self.address)`. ``` class cell: def __init__(self,address): self.address = address def __hash__(self): return hash(self.address) def __eq__(self): return hash(self) == hash(other) ``` You can still access cells by their address, but the cells know where they belong. ``` >>> c = cell((0,0)) >>> c <so.cell instance at 0xb74c6a2c> >>> grid = dict() >>> grid[c] = c >>> grid[c] <so.cell instance at 0xb74c6a2c> >>> grid[(0,0)] <so.cell instance at 0xb74c6a2c> ``` I'm not sure what else your `cell`s need to know and/or do, but if you're just doing numerical stuff here, I'd highly recommend the [scipy.sparse](http://docs.scipy.org/doc/scipy/reference/sparse.html) module.
12,848,345
I'm using a dictionary in python to make what is basically an infinite 2d array by using a tuple as the key ``` grid = {} grid[(0,0)] = cell() ``` the value 'cell' is a new object. Can I have, say, a function within that object that is able to get its key value? ie. (0,0) I could just put that data in the object itself but then I'd have it existing twice which seems like bad programming. Thanks!
2012/10/11
[ "https://Stackoverflow.com/questions/12848345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1432808/" ]
There are two separate issues here... first, to access the grid from within cell, I would have `cell`'s constructor take a reference to grid as a mandatory argument. ``` grid = {} grid[(0,0)] = cell(grid) ``` and ``` class cell: def __init__(self, gridRef): self.grid = gridRef ``` But, accessing the key is more challenging. One reason is that a dictionary is not a one-to-one mapping, so the same cell object may have multiple keys in your dictionary. You'd need to iterate over your keys and look for it, either manually or through flipping the dictionary. How about making your `cell` constructor take the key as well? ``` grid = {} grid[(0,0)] = cell(grid, (0,0)) ``` If that's too redundant, then maybe something like this? ``` def addToGrid(myDict, myCell): myDict[myCell.key()] = myCell ``` and then... ``` grid = {} addToGrid(grid, cell(grid, (0, 0))) ``` where your `cell` class takes the dictionary key as the second argument and returns it via the `key()` method.
Give your `cell` class an `address` attribute, which is a two-tuple, e.g. `(0,0)`. Give the `cell` class a `__hash__` method, which returns `hash(self.address)`. ``` class cell: def __init__(self,address): self.address = address def __hash__(self): return hash(self.address) def __eq__(self): return hash(self) == hash(other) ``` You can still access cells by their address, but the cells know where they belong. ``` >>> c = cell((0,0)) >>> c <so.cell instance at 0xb74c6a2c> >>> grid = dict() >>> grid[c] = c >>> grid[c] <so.cell instance at 0xb74c6a2c> >>> grid[(0,0)] <so.cell instance at 0xb74c6a2c> ``` I'm not sure what else your `cell`s need to know and/or do, but if you're just doing numerical stuff here, I'd highly recommend the [scipy.sparse](http://docs.scipy.org/doc/scipy/reference/sparse.html) module.
15,752,200
I have created a windows service project using Visual Studio which needs to be installed on to the remote machine using MSBuild. I have had a look at lots of resources on good ways of deploying windows services. Most answer were using PowerShell scripts which i think of as an alternative. Can anyone provide me with good resource. Any ideas on how to deploy this. There are lots of security issues with deploying (.exe) files in enterprise environment so i am worried on picking any alternatives. I will really appreciate any suggestions.
2013/04/01
[ "https://Stackoverflow.com/questions/15752200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2155069/" ]
You can use Exec Task (<http://msdn.microsoft.com/en-us/library/x8zx72cd.aspx>) look at the link. Using powershell remoting would be another option for sure.
To install service to the remote machine you can try ServiceController task that can control a Windows service. From [here](http://weblogs.asp.net/scottgu/archive/2006/02/12/438061.aspx).
15,752,200
I have created a windows service project using Visual Studio which needs to be installed on to the remote machine using MSBuild. I have had a look at lots of resources on good ways of deploying windows services. Most answer were using PowerShell scripts which i think of as an alternative. Can anyone provide me with good resource. Any ideas on how to deploy this. There are lots of security issues with deploying (.exe) files in enterprise environment so i am worried on picking any alternatives. I will really appreciate any suggestions.
2013/04/01
[ "https://Stackoverflow.com/questions/15752200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2155069/" ]
you can use MSBuild example for install: ``` <MSBuild.ExtensionPack.Computer.WindowsService TaskAction="Install" ServiceName="SomeWindowsService" User="UserLocal" Password="PassLocal" ServicePath="\\RemoteComp2\PathForYourService\WindowsService.exe" RemoteUser="UserRemoteComp2" RemoteUserPassword="PassRemoteComp2" MachineName="RemoteComp2"/> ``` for more information look follow link <http://www.msbuildextensionpack.com/help/4.0.5.0/html/258a18b7-2cf7-330b-e6fe-8bc45db381b9.htm>
To install service to the remote machine you can try ServiceController task that can control a Windows service. From [here](http://weblogs.asp.net/scottgu/archive/2006/02/12/438061.aspx).
15,752,200
I have created a windows service project using Visual Studio which needs to be installed on to the remote machine using MSBuild. I have had a look at lots of resources on good ways of deploying windows services. Most answer were using PowerShell scripts which i think of as an alternative. Can anyone provide me with good resource. Any ideas on how to deploy this. There are lots of security issues with deploying (.exe) files in enterprise environment so i am worried on picking any alternatives. I will really appreciate any suggestions.
2013/04/01
[ "https://Stackoverflow.com/questions/15752200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2155069/" ]
You can use Exec Task (<http://msdn.microsoft.com/en-us/library/x8zx72cd.aspx>) look at the link. Using powershell remoting would be another option for sure.
Have a look at PSExec (<http://technet.microsoft.com/en-us/sysinternals/bb897553.aspx>) depending on your requirements and deployment scenario. It, combined with the MSBuild Exec task, would allow you to install the service remotely.
15,752,200
I have created a windows service project using Visual Studio which needs to be installed on to the remote machine using MSBuild. I have had a look at lots of resources on good ways of deploying windows services. Most answer were using PowerShell scripts which i think of as an alternative. Can anyone provide me with good resource. Any ideas on how to deploy this. There are lots of security issues with deploying (.exe) files in enterprise environment so i am worried on picking any alternatives. I will really appreciate any suggestions.
2013/04/01
[ "https://Stackoverflow.com/questions/15752200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2155069/" ]
You can use Exec Task (<http://msdn.microsoft.com/en-us/library/x8zx72cd.aspx>) look at the link. Using powershell remoting would be another option for sure.
you can use MSBuild example for install: ``` <MSBuild.ExtensionPack.Computer.WindowsService TaskAction="Install" ServiceName="SomeWindowsService" User="UserLocal" Password="PassLocal" ServicePath="\\RemoteComp2\PathForYourService\WindowsService.exe" RemoteUser="UserRemoteComp2" RemoteUserPassword="PassRemoteComp2" MachineName="RemoteComp2"/> ``` for more information look follow link <http://www.msbuildextensionpack.com/help/4.0.5.0/html/258a18b7-2cf7-330b-e6fe-8bc45db381b9.htm>
15,752,200
I have created a windows service project using Visual Studio which needs to be installed on to the remote machine using MSBuild. I have had a look at lots of resources on good ways of deploying windows services. Most answer were using PowerShell scripts which i think of as an alternative. Can anyone provide me with good resource. Any ideas on how to deploy this. There are lots of security issues with deploying (.exe) files in enterprise environment so i am worried on picking any alternatives. I will really appreciate any suggestions.
2013/04/01
[ "https://Stackoverflow.com/questions/15752200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2155069/" ]
you can use MSBuild example for install: ``` <MSBuild.ExtensionPack.Computer.WindowsService TaskAction="Install" ServiceName="SomeWindowsService" User="UserLocal" Password="PassLocal" ServicePath="\\RemoteComp2\PathForYourService\WindowsService.exe" RemoteUser="UserRemoteComp2" RemoteUserPassword="PassRemoteComp2" MachineName="RemoteComp2"/> ``` for more information look follow link <http://www.msbuildextensionpack.com/help/4.0.5.0/html/258a18b7-2cf7-330b-e6fe-8bc45db381b9.htm>
Have a look at PSExec (<http://technet.microsoft.com/en-us/sysinternals/bb897553.aspx>) depending on your requirements and deployment scenario. It, combined with the MSBuild Exec task, would allow you to install the service remotely.
27,417,705
I'm very new in AngularJS. I want to post registration data to a json file. Post request is working correctly,but data is not writing to file. I can't understand that position. Is there something wrong with my post request code? And how can I fix that? Thanks! ``` var regModel = { FirstName: 'Someone', LastName: 'Somebody', Address: 'somewhere', Email: 'something@gmail.com' }; $scope.insertUser = function () { $http.post('../DB/users.json', regModel). success(function(data, status, headers, config) { // this callback will be called asynchronously // when the response is available }). error(function(data, status, headers, config) { // called asynchronously if an error occurs // or server returns response with an error status. }); } ```
2014/12/11
[ "https://Stackoverflow.com/questions/27417705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4152306/" ]
try this: ``` private void sendSMSWithDelay(String number, String responseMessage, int delayInResponce) { Intent intent = new Intent(Global.getMyApplicationContext(), MyCallBroadcastReceiver.class); // Intent i = new Intent(MessageService.this, // ViewMessageActivity.class); intent.putExtra("number", number); intent.putExtra("message", responseMessage); PendingIntent pendingIntent = PendingIntent.getBroadcast( Global.getMyApplicationContext(), new Random().nextLong(), intent, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager alarmManager = (AlarmManager) Global .getMyApplicationContext().getSystemService( Global.getMyApplicationContext().ALARM_SERVICE); alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (delayInResponce * 60 * 1000), pendingIntent); } ```
Refer following link <https://developer.android.com/training/scheduling/alarms.html> For example:- alarmMgr.setRepeating(AlarmManager.RTC\_WAKEUP, calendar.getTimeInMillis(), System.currentTimeMillis() + (delayInResponce \* 60 \* 1000), pendingIntent);
40,257,164
I am struglling to start implementation or development for sitecore ecommerce connector. I tried to google to find some tutorials but there is not much information available. I have successfully install sitecore and commerce connector but i don't know how to start developing product and other services to sync product data. Please provide some links.
2016/10/26
[ "https://Stackoverflow.com/questions/40257164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/167689/" ]
On this youtube channel you will find a demo video how to start with commerce connect. It is connected to a NopCommerce website. <https://www.youtube.com/watch?v=JECKXgAOAZU> You can find also informations on github account : <https://github.com/Sitecore/Commerce-Connect-StarterKit/tree/release/8.2.281/master> This will be your starting point to choose correct version. <https://dev.sitecore.net/Downloads/Sitecore_Commerce_Connect.aspx> I hope it helps you.
Sitecore provides "Commerce Connect" to connect to external system. Commerce Connect is an integration layer between a front-end web shop solution and a back-end e-commerce system You can get more information on <http://www.sitecore.net/en/products/sitecore-experience-platform/cross-channel-delivery/commerce>
26,017,429
I am starting a Process with Process.Start("MyProcess.exe") function. "MyProcess.exe" uses a DLL. Exe and DLL are in same folder. I have modified this DLL and located it into a different path with same name. For some cases, I want to start MyProcess.exe with modified DLL and I do not want to delete original DLL. My Exe should work with seconds DLL that located different folder and should not work with DLL that located same folder. I have tried following codes but does not work for me ``` processStartInfo.EnvironmentVariables["PATH"] = "PATH_B;" + processStartInfo.EnvironmentVariables["PATH"]; processStartInfo.WorkingDirectory = Path.GetDirectoryName("PATH_B"); processStartInfo.UseShellExecute = false; myProcess = Process.Start(processStartInfo); ```
2014/09/24
[ "https://Stackoverflow.com/questions/26017429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2511092/" ]
Because of the built in [rules within the operating system](http://msdn.microsoft.com/en-us/library/windows/desktop/ff919712%28v=vs.85%29.aspx), the system always searches directories in the following order: * The directory from which the application loaded. * The system directory. * The 16-bit system directory. * The Windows directory. * The current directory. * The directories that are listed in the PATH environment variable.
If the DLL have the different version you casu use [Specifying an Assembly's Location](http://msdn.microsoft.com/en-us/library/4191fzwb(v=vs.110).aspx) in the config file of MyProcess.exe if is .Net
3,381,454
Say $E(X\_{n} 1\_{\vert X\_{n} \vert \geq 1 })=\frac{1}{n}$ for all $n \in \mathbb N$. Can I immediately deduce that $(X\_{n})\_{n}$ is uniformly integrable? My idea: $E(\vert X\_{n}\vert)= E(\vert X\_{n}\vert 1\_{\vert X\_{n} \vert \geq 1 })+E(\vert X\_{n}\vert 1\_{\vert X\_{n} \vert < 1 })\leq\frac{1}{n}+1$ Thus $\sup\limits\_{n} E(\vert X\_{n}\vert)\leq 2$ Let $\epsilon > 0$, then choose $N \in \mathbb N>1$ so that $\frac{1}{N} < \epsilon$ so that for all $n \geq N$: $E(\vert X\_{n}\vert 1\_{\vert X\_{n} \vert \geq n })=E(\vert X\_{n}\vert 1\_{\vert X\_{n} \vert \geq N })\leq E(\vert X\_{n}\vert 1\_{\vert X\_{n} \vert \geq 1 })\leq \frac{1}{n}\xrightarrow{n \to \infty} 0$ I still have not shown uniform integrability. Any ideas?
2019/10/05
[ "https://math.stackexchange.com/questions/3381454", "https://math.stackexchange.com", "https://math.stackexchange.com/users/512018/" ]
For given $\epsilon>0$ choose $N \in \mathbb{N}$ sufficiently large such that $1/N \leq \epsilon$. Then $$\int\_{|X\_n| \geq R} |X\_n| \, d\mathbb{P} \leq \int\_{|X\_n| \geq 1} |X\_n| \, d\mathbb{P} \leq \frac{1}{n} \leq \epsilon$$ for all $n \geq N$ and $R \geq 1$. On the other hand, the finite family $\{X\_1,\ldots,X\_{N-1}\}$ is uniformly integrable, and therefore there exists $R \gg 1$ sufficiently large such that $$\int\_{|X\_n| \geq R} |X\_n| \, d\mathbb{P} \leq \epsilon$$ for all $n \in \{1,\ldots,N-1\}$. Hence, $$\sup\_{n \geq 1} \int\_{|X\_n| \geq R} |X\_n| \,d \mathbb{P} \leq \epsilon$$ which proves that $(X\_n)\_{n \geq 1}$ is uniformly integrable.
If the assumption was $$ E\left(\lvert X\_{n}\rvert 1\_{\vert X\_{n} \vert \geq 1 }\right))=\frac{1}{n}, $$ then for all $R\geqslant 1$, $\limsup\_{n\to+\infty}E\left(\lvert X\_{n}\rvert 1\_{\vert X\_{n} \vert \geq R }\right))=0$ hence the uniform integrability follows. However, with the assumption $$E\left( X\_{n} 1\_{\vert X\_{n} \vert \geq 1 }\right))=\frac{1}{n},$$ the conclusion may not hold: let $X\_n$ be a random variable taking the values $n$, $-n$, $1$ and $0$ with respective probabilities $1/n$, $1/n$, $1/n$ and $1-3/n$.
36,950,296
Am trying to configure `Qt for Android development` on my windows 7 machine. I have downloaded the `latest Android Studio, NDK, Apache Ant 1.9.7 and Qt Creator from qt.io (Qt 5.6.0 for Android (Windows 32-bit, 1.1 GB))`. I am able to create AVD in Android Studio and was able to start AVD and deploy an application I created on Android studio successfully. Now, I wanted to configure Qt for Android, so that I can continue my development on Qt. I am able to build the Qt application for x86 desktop version. But, I have problem in creating ARM virtual device on Qt Creator to to deploy the application on to the target. I notice only x86 CPU/ABI while creating a new AVD as shown below: [![Create a new AVD, and unable to see ARM under CPU/ABI dropdown](https://i.stack.imgur.com/N87G0.png)](https://i.stack.imgur.com/N87G0.png)
2016/04/30
[ "https://Stackoverflow.com/questions/36950296", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2043014/" ]
It looks like your virtual devices are all x86 based, while your Qt kit builds for ARM. This will not matter for Android Studio, since it is not native code but Java, but Qt is C++ code and you cannot target a x86 device with an ARM compiler. Either install Qt for Android x86 or create an ARM virtual device.
Initially I was working on Android studio installed on my Windows 7 machine. And, when I wanted to work on "Qt for Android" I have set the Android SDK and NDK paths in Qt Creator to the same locations that I used in Android Studio, and for some reason I was unable to create an ARM virtual device in Qt Creator. Based on the previous answer provided by @ddriver I ran SDK Manager and installed ARM packages. Now am able to deploy my application.
7,043,141
I am building a TSQL query to parse through a FTP log from FileZilla. I am trying to figure out if there is a way to get information from a line preceding the current one? For example, I have parsed out the Following procedure: "STOR file.exe" With the FileZilla is doesn't say if the STOR wass successful until the next line. So I want to check the next line and see if the STOR was successful or was unsuccessful? Also people could try to STOR a files multiple times so I want to get the last version of its status. Example Info from Log file: ``` (000005) 4/10/2010 14:55:30 PM - ftp_login_name (IP Address)> STOR file.exe (000005) 4/10/2010 14:55:30 PM - ftp_login_name (IP Address)> 150 Opening data for transfer. (000005) 4/10/2010 14:55:30 PM - ftp_login_name (IP Address)> 226 Transfer OK ``` I want to add a column in my query that says that the STOR was successful or unsuccessful. Thanks!
2011/08/12
[ "https://Stackoverflow.com/questions/7043141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/781558/" ]
Assuming you have parsed these lines into actual columns, and you have SQL server 2005 or greater. You can use `CROSS APPLY` example query below (untested). I hope this helps. ``` select o.*, prev.* from FTPLog o cross apply ( select top 1 * from FTPLog P where P.LogDate < O.LogDate order by LogDate DESC ) prev ```
James has the right idea, though there may be some issues if you ever have log dates that are exactly the same (and from your sample it looks like you might). You may be able to add an identity column to force an order at the time the data is inserted, then you can use James' concept on the identity column. More than that though, TSQL may not be the best choice for this project, at least not by itself. While there are techniques you can use to make it iterate sequentially, it is not as good for that as certain other languages are. You may want to consider parsing your files in a tool, such as Python or Perl or even C#, that is better at text processing and better at processing data sequentially.
4,450,741
How can I show that $P(B|A) = P(B)$, given that $A$ and $B$ are independent?
2022/05/15
[ "https://math.stackexchange.com/questions/4450741", "https://math.stackexchange.com", "https://math.stackexchange.com/users/868990/" ]
$$f(x) = x^2 + 1$$ is irreducible over $\mathbb Q$, but $$f(x^3) = x^6 + 1 = (x^2 + 1)(x^4 - x^2 + 1)$$ obviously factors.
If $k\ne2$ then $f(x)=x^2-2^k$ is irreducible but $f(x^k)=(x^2)^k-2^k$ is reducible
4,450,741
How can I show that $P(B|A) = P(B)$, given that $A$ and $B$ are independent?
2022/05/15
[ "https://math.stackexchange.com/questions/4450741", "https://math.stackexchange.com", "https://math.stackexchange.com/users/868990/" ]
If $k\ne2$ then $f(x)=x^2-2^k$ is irreducible but $f(x^k)=(x^2)^k-2^k$ is reducible
Another sufficient condition is given in *Problems from the Book* by Titu Andreescu (Example 9, page 494): > > Let $f(x)$ be a monic polynomial with integer coefficients and let $p$ be a prime number. If $f(x)$ is irreducible in $\mathbb{Z}[x]$ and $\sqrt[p]{(-1)^{\deg f}f(0)}$ is irrational, then $f(x^p)$ is also irreducible in $\mathbb{Z}[x]$. > > >
4,450,741
How can I show that $P(B|A) = P(B)$, given that $A$ and $B$ are independent?
2022/05/15
[ "https://math.stackexchange.com/questions/4450741", "https://math.stackexchange.com", "https://math.stackexchange.com/users/868990/" ]
$$f(x) = x^2 + 1$$ is irreducible over $\mathbb Q$, but $$f(x^3) = x^6 + 1 = (x^2 + 1)(x^4 - x^2 + 1)$$ obviously factors.
Here is a sufficient condition: $f(x)$ is irreducible over $\mathbb{Q}$ and in some field $K$ (the splitting field of $f(x)$) we have $f(x) = (x-\alpha\_1)\cdot \ldots \cdot (x-\alpha\_n)$, and moreover each $x^k - \alpha\_i$, $1\le i \le n$, is irreducible over $K$. This applies in particular to your polynomial, see this [answer](https://math.stackexchange.com/questions/1204279/show-that-x4-10x21-is-irreducible-over-mathbbq/3437719#3437719). $\bf{Added:}$ The point is that over some extension $K$ the polynomial $f(x^k)$ factors into irreducibles that are polynomials in $x^k$. $\bf{Added:}$ Let $\alpha$ be any root of $f(x)$. We have $f(x^k)$ irreducible if and only if the degree of $\sqrt[k]{\alpha}$ over $\mathbb{Q}$ is $k n$. This is equivalent to: the degree of $\sqrt[k]{\alpha}$ over $\mathbb{Q}(\alpha)$ is $k$.
4,450,741
How can I show that $P(B|A) = P(B)$, given that $A$ and $B$ are independent?
2022/05/15
[ "https://math.stackexchange.com/questions/4450741", "https://math.stackexchange.com", "https://math.stackexchange.com/users/868990/" ]
$$f(x) = x^2 + 1$$ is irreducible over $\mathbb Q$, but $$f(x^3) = x^6 + 1 = (x^2 + 1)(x^4 - x^2 + 1)$$ obviously factors.
Another sufficient condition is given in *Problems from the Book* by Titu Andreescu (Example 9, page 494): > > Let $f(x)$ be a monic polynomial with integer coefficients and let $p$ be a prime number. If $f(x)$ is irreducible in $\mathbb{Z}[x]$ and $\sqrt[p]{(-1)^{\deg f}f(0)}$ is irrational, then $f(x^p)$ is also irreducible in $\mathbb{Z}[x]$. > > >
4,450,741
How can I show that $P(B|A) = P(B)$, given that $A$ and $B$ are independent?
2022/05/15
[ "https://math.stackexchange.com/questions/4450741", "https://math.stackexchange.com", "https://math.stackexchange.com/users/868990/" ]
Here is a sufficient condition: $f(x)$ is irreducible over $\mathbb{Q}$ and in some field $K$ (the splitting field of $f(x)$) we have $f(x) = (x-\alpha\_1)\cdot \ldots \cdot (x-\alpha\_n)$, and moreover each $x^k - \alpha\_i$, $1\le i \le n$, is irreducible over $K$. This applies in particular to your polynomial, see this [answer](https://math.stackexchange.com/questions/1204279/show-that-x4-10x21-is-irreducible-over-mathbbq/3437719#3437719). $\bf{Added:}$ The point is that over some extension $K$ the polynomial $f(x^k)$ factors into irreducibles that are polynomials in $x^k$. $\bf{Added:}$ Let $\alpha$ be any root of $f(x)$. We have $f(x^k)$ irreducible if and only if the degree of $\sqrt[k]{\alpha}$ over $\mathbb{Q}$ is $k n$. This is equivalent to: the degree of $\sqrt[k]{\alpha}$ over $\mathbb{Q}(\alpha)$ is $k$.
Another sufficient condition is given in *Problems from the Book* by Titu Andreescu (Example 9, page 494): > > Let $f(x)$ be a monic polynomial with integer coefficients and let $p$ be a prime number. If $f(x)$ is irreducible in $\mathbb{Z}[x]$ and $\sqrt[p]{(-1)^{\deg f}f(0)}$ is irrational, then $f(x^p)$ is also irreducible in $\mathbb{Z}[x]$. > > >
389,520
Let $K$ be a number field and let $D$ be a central division algebra over $K$. Let $d$ be the index so that $[D:K]=d^2$. What is the minimal $n$ such that there exists an embedding of $D$ into $\mathrm{Mat}\_{n \times n}(K)$? Of course, we can always embed $D$ into $\mathrm{Mat}\_{n \times n}(K)$ for $n=d^2$, but can we do better than this? Here's an explicit example. Let $\mathbb{H}=\mathbb{Q}\oplus\mathbb{Q}i\oplus\mathbb{Q}j \oplus\mathbb{Q}k$ with $i^2=j^2=k^2=-1$ and $ij=k=-ji$ be the division algebra of rational quaternions. Then $d=2$ and we can embed $\mathbb{H}$ into $\mathrm{Mat}\_{4 \times 4}(\mathbb{Q})$. We can't embed $\mathbb{H}$ into $\mathrm{Mat}\_{2 \times 2}(\mathbb{Q})$ because they have the same dimension. So in this case the question boils down to whether we can embed $\mathbb{H}$ into $\mathrm{Mat}\_{3 \times 3}(\mathbb{Q})$. My intuition tells me that this isn't possible, ~~but I can't pin down a proof~~. **Edit:** user44191 has given a proof in the comments below. But I'd still be interested in an answer to the more general question. Now $\mathbb{Q}(i)$ is maximal subfield of $\mathbb{H}$ and so we have an isomorphism $\mathbb{Q}(i) \otimes\_\mathbb{Q} \mathbb{H} \cong \mathrm{Mat}\_{2 \times 2}(\mathbb{Q}(i))$. Maybe something like this could help, but I don't quite see how. I've also thought about Brauer groups, but again I don't see how to take advantage of them for this problem. **Edit:** I should have said that I don't require an embedding to preserve the multiplicative identity.
2021/04/06
[ "https://mathoverflow.net/questions/389520", "https://mathoverflow.net", "https://mathoverflow.net/users/7443/" ]
Any embedding of $D$ into $M\_n(K)$ defines a $D$-module structure on $K^n$. But $D$ is a simple algebra and we know all its modules: they are $D^m\cong K^{km}$ where $k=[D:K]$. Thus, $m=1$ is the best you can do.
$n = [D : K]$. Assume $n < [D : K]$. Let $p: D \rightarrow \mathrm{Mat}\_{n \times n}$ be an embedding, and let $\{\alpha\_i\}\_{1 \leq i \leq d^2}$ be a basis for $D$ over $K$, where $d^2=[D:K]$. Choose any nonzero vector $v \in V \simeq K^n$. Then as there are $d^2$ elements of the set $\{p(\alpha\_i)(v)\}$, they must be linearly dependent, by dimension. Therefore, there is some nontrivial linear relation $\sum\_i c\_i p(\alpha\_i)(v) = 0$. As the embedding is linear, this implies that $p(\sum\_i c\_i \alpha\_i)(v) = 0$. Then as the $\alpha\_i$ form a basis, $\sum\_i c\_i \alpha\_i$ is nonzero, and therefore is invertible with some inverse $\beta$. Then as this is an algebra embedding, $p(1)(v) = p(\beta (\sum\_i c\_i \alpha\_i))(v) = p(\beta)(p(\sum\_i c\_i \alpha\_i)(v)) = p(\beta)(0) = 0$. But remember - this is true for *any* vector, so $p(1) = 0$, which contradicts this being an embedding.
67,737,215
I have the following JavaScript code and I get an error that says: Uncaught TypeError: Cannot read property 'value' of undefined" Specifically, at the line: const parola=form.parola.value; ```js <%- include('partials/header') %> <form action="/signup"> <h2>Kullanıcı Oluştur</h2> <label for="email">email</label> <input type="text" name="email" required/> <div class="email error"></div> <label for="email">Parola</label> <input type="password" name="email" required/> <div class="password error"></div> <button type="submit">Oluştur</button> </form> <%- include('partials/footer') %> <script> const form=document.querySelector('form'); form.addEventListener('submit',async (e)=>{ e.preventDefault(); const email=form.email.value; const parola=form.parola.value; // console.log(email,parola); try { const res=await fetch('/signup',{ method:'POST', body:JSON.stringify({email,parola}), headers:{'Content-Type':'application/json'} }); } catch (error) { console.log(error); } }); </script> ``` Any advise?
2021/05/28
[ "https://Stackoverflow.com/questions/67737215", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16058589/" ]
*The Outlooks* on Windows don’t support `background-image` in CSS nor the HTML `background` attribute. So VML is indeed the usual way to go. I wrote a post this year about mimicking [background properties in VML](https://www.hteumeuleu.com/2021/background-properties-in-vml/). You'll need the following corresponding VML attributes to the `<v:fill>` element. In your case, it'd be: * `background-size:cover` : `aspect="atleast"` * `background-repeat:no-repeat` : `type="frame"`
Please try this ``` <style> background { background-image: url('image-url.jpg'); background-repeat: no-repeat; background-attachment: fixed; background-size: cover; } </style> ```
51,261,939
I have made a Django employee portal which will be accessed by LAN only. It works when another employee opens it by typing the IP address of the server on their web browser. However I don't have much experience with Django and I think that this is not the proper way to do so. I run my server using python manage.py runserver and use sqlite3 as database. Is this the correct way to do so? How should I deploy my portal. I am very new to Django and would appreciate some help. **I am using a windows machine and I used pycharm to make my project.** And also I need to know how can I have the server running even when I close pycharm, as ctrl-C or closing pycharm breaks the server
2018/07/10
[ "https://Stackoverflow.com/questions/51261939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10042266/" ]
[Setting up Django and your web server with uWSGI and nginx](https://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html) There is not an official way to do it, what I do effectively, intranet solutions as well, is with nginx and uWSGI (on ubuntu). Serving with Windows? perhaps: <https://www.toptal.com/django/installing-django-on-iis-a-step-by-step-tutorial> is a proper way to do so.
I think for ip address issue you can use host names <https://wesbos.com/localhost-mobile-device-testing/> and for running server in background you can use gunicorn with supervisor check this out <https://www.agiliq.com/blog/2014/05/supervisor-with-django-and-gunicorn/>
51,261,939
I have made a Django employee portal which will be accessed by LAN only. It works when another employee opens it by typing the IP address of the server on their web browser. However I don't have much experience with Django and I think that this is not the proper way to do so. I run my server using python manage.py runserver and use sqlite3 as database. Is this the correct way to do so? How should I deploy my portal. I am very new to Django and would appreciate some help. **I am using a windows machine and I used pycharm to make my project.** And also I need to know how can I have the server running even when I close pycharm, as ctrl-C or closing pycharm breaks the server
2018/07/10
[ "https://Stackoverflow.com/questions/51261939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10042266/" ]
The simplest way to allow everyone on your network to access your Django webserver is to do `python manage.py runserver 0.0.0.0:8000` This allows anyone on the network to access it by using your IP address (or computer name) and the port 8000. (so something like 192.168.1.2:8000) This of course isn't really nice specially if you intent to use this as a production environment. panchicore's answer should help you setup a good production environment.
I think for ip address issue you can use host names <https://wesbos.com/localhost-mobile-device-testing/> and for running server in background you can use gunicorn with supervisor check this out <https://www.agiliq.com/blog/2014/05/supervisor-with-django-and-gunicorn/>
1,063,364
I am creating a file-oriented database of some test results performed by various users. For this I need to generate unique id for every entry in the database. The ids must satisfy following requirements: * Ids should be fairly small (6 characters at most) * For every test case and user combination each time same id should be generated What I tried was a simple BKDR hash function with seed value 31 and used ord() function as follows: ``` @chars = split(//,$hash_var); $hash = 0; $seed = 31; foreach $char ( @chars ) { if( $char !~ m/\d/ ) { $hash = ( $seed * $hash ) + ord( $char ); } else { $hash = ( $seed * $hash ) + $char ; } } $hash = ( $hash & 0x7FFFFFFF ) % 1000; $hash = "$chars[0]$chars[$#chars]$hash" ; ``` This sometimes leads to same results for various combinations i.e uniqueness is not observed. Is their any other way to accomplish this? Does changing seed value help accomplish uniqueness.
2009/06/30
[ "https://Stackoverflow.com/questions/1063364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91593/" ]
Do you have more than 256 users and/or more than 65536 test cases per user? If not, you can just index users from 0 .. 255 and test cases from 0 .. 65535 and encode it as a string of hexadecimal digits so six characters would be fine. If you have more users or test cases than that, I would again index the users and test cases and then combine them into a 32-bit integer which would actually only take 4 bytes and be trivial to implement but slightly harder on humans. In any case, I am assuming you are given user name and test case information. Just keep two tied hashes: `%users` and `%cases` to map users and test cases to their index numbers.
If you don't have a lot of users/testcases a simple solution like this might be enough. You'd have to add the limit (and probably pack the integer when storing it). ``` vinko@parrot:~# more hash.pl use strict; use warnings; my %hash; my $count = 0; sub getUniqueId { my $_user = shift; my $_test = shift; my $val; my $key = $_user."|".$_test; if (defined $hash{$key}) { $val = $hash{$key}; } else { $hash{$key} = $count; $val = $count; $count = $count + 1; } return $val; } my @users = qw{ user1 user2 user3 user4 user5 user3 user5 }; my @testcases = qw{ test1 test2 test3 test1 test1 }; for my $user (@users) { for my $test (@testcases) { print "$user $test: ".getUniqueId($user,$test)."\n"; } } vinko@parrot:~# perl hash.pl user1 test1: 0 user1 test2: 1 user1 test3: 2 user1 test1: 0 user1 test1: 0 user2 test1: 3 user2 test2: 4 user2 test3: 5 user2 test1: 3 user2 test1: 3 user3 test1: 6 user3 test2: 7 user3 test3: 8 user3 test1: 6 user3 test1: 6 user4 test1: 9 user4 test2: 10 user4 test3: 11 user4 test1: 9 user4 test1: 9 user5 test1: 12 user5 test2: 13 user5 test3: 14 user5 test1: 12 user5 test1: 12 user3 test1: 6 user3 test2: 7 user3 test3: 8 user3 test1: 6 user3 test1: 6 user5 test1: 12 user5 test2: 13 user5 test3: 14 user5 test1: 12 user5 test1: 12 ```
1,063,364
I am creating a file-oriented database of some test results performed by various users. For this I need to generate unique id for every entry in the database. The ids must satisfy following requirements: * Ids should be fairly small (6 characters at most) * For every test case and user combination each time same id should be generated What I tried was a simple BKDR hash function with seed value 31 and used ord() function as follows: ``` @chars = split(//,$hash_var); $hash = 0; $seed = 31; foreach $char ( @chars ) { if( $char !~ m/\d/ ) { $hash = ( $seed * $hash ) + ord( $char ); } else { $hash = ( $seed * $hash ) + $char ; } } $hash = ( $hash & 0x7FFFFFFF ) % 1000; $hash = "$chars[0]$chars[$#chars]$hash" ; ``` This sometimes leads to same results for various combinations i.e uniqueness is not observed. Is their any other way to accomplish this? Does changing seed value help accomplish uniqueness.
2009/06/30
[ "https://Stackoverflow.com/questions/1063364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91593/" ]
Part of your problem may be that you are using floating point math and BKDR is almost certainly wanting integer math. You can fix that bug by saying ``` my @chars = split(//,$hash_var); my $hash = 0; my $seed = 31; for my $char ( @chars ) { use integer; if( $char !~ m/\d/ ) { $hash = ( $seed * $hash ) + ord( $char ); } else { $hash = ( $seed * $hash ) + $char ; } } $hash = ( $hash & 0x7FFFFFFF ) % 1000; $hash = "$chars[0]$chars[$#chars]$hash" ; ``` Another tweak that might help is using characters other than the first and last. If the first and last characters tend to be the same, they add no uniqueness to the hash. You may also want to use a better hash function like MD5 (available in Digest::MD5) and trim the result to your desired size. However, the fact that you are using a hash at all means that you run the risk of having a collision.
If you don't have a lot of users/testcases a simple solution like this might be enough. You'd have to add the limit (and probably pack the integer when storing it). ``` vinko@parrot:~# more hash.pl use strict; use warnings; my %hash; my $count = 0; sub getUniqueId { my $_user = shift; my $_test = shift; my $val; my $key = $_user."|".$_test; if (defined $hash{$key}) { $val = $hash{$key}; } else { $hash{$key} = $count; $val = $count; $count = $count + 1; } return $val; } my @users = qw{ user1 user2 user3 user4 user5 user3 user5 }; my @testcases = qw{ test1 test2 test3 test1 test1 }; for my $user (@users) { for my $test (@testcases) { print "$user $test: ".getUniqueId($user,$test)."\n"; } } vinko@parrot:~# perl hash.pl user1 test1: 0 user1 test2: 1 user1 test3: 2 user1 test1: 0 user1 test1: 0 user2 test1: 3 user2 test2: 4 user2 test3: 5 user2 test1: 3 user2 test1: 3 user3 test1: 6 user3 test2: 7 user3 test3: 8 user3 test1: 6 user3 test1: 6 user4 test1: 9 user4 test2: 10 user4 test3: 11 user4 test1: 9 user4 test1: 9 user5 test1: 12 user5 test2: 13 user5 test3: 14 user5 test1: 12 user5 test1: 12 user3 test1: 6 user3 test2: 7 user3 test3: 8 user3 test1: 6 user3 test1: 6 user5 test1: 12 user5 test2: 13 user5 test3: 14 user5 test1: 12 user5 test1: 12 ```
73,008,449
``` String name = "Jack"; char letter = name.charAt(0); System.out.println(letter); ``` You know this is a java method **`charAt`** that it gives you a character of a String just by telling the index of the String. I'm asking for a method like this in Dart, does Dart have a method like that?
2022/07/17
[ "https://Stackoverflow.com/questions/73008449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19141096/" ]
You can use [`String.operator[]`](https://api.dart.dev/stable/dart-core/String/operator_get.html). ```dart String name = "Jack"; String letter = name[0]; print(letter); ``` Note that this operates on UTF-16 *code units*, not on Unicode code points nor on grapheme clusters. Also note that Dart does not have a `char` type, so you'll end up with another `String`. If you need to operate on arbitrary Unicode strings, then you should use [`package:characters`](https://pub.dev/packages/characters) and do: ```dart String name = "Jack"; Characters letter = name.characters.characterAt(0); print(letter); ```
You can use ``` String.substring(int startIndex, [ int endIndex ]) ``` Example -- ``` void main(){ String s = "hello"; print(s.substring(1, 2)); } ``` Output ``` e ``` Note that , endIndex is one greater than startIndex, and the char which is returned is present at startIndex.
73,008,449
``` String name = "Jack"; char letter = name.charAt(0); System.out.println(letter); ``` You know this is a java method **`charAt`** that it gives you a character of a String just by telling the index of the String. I'm asking for a method like this in Dart, does Dart have a method like that?
2022/07/17
[ "https://Stackoverflow.com/questions/73008449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19141096/" ]
Dart has two operations that match the Java behavior, because Java prints integers of the type `char` specially. Dart has [`String.codeUnitAt`](https://api.dart.dev/stable/2.17.6/dart-core/String/codeUnitAt.html), which does the same as Java's `charAt`: Returns an integer representing the UTF-16 code unit at that position in the string. If you print that in Dart, or add it to a `StringBuffer`, it's just an integer, so `print("Jack".codeUnitAt(0))` prints `74`. The other operations is [`String.operator[]`](https://api.dart.dev/stable/2.17.6/dart-core/String/operator_get.html), which returns a single-code-unit `String`. So `print("Jack"[0])` prints `J`. Both should be used very judiciously, since many Unicode characters are not just a single code unit. You can use [`String.runes`](https://api.dart.dev/stable/2.17.6/dart-core/String/runes.html) to get code *points* or [`String.characters`](https://pub.dev/documentation/characters/latest/characters/StringCharacters/characters.html) from package `characters` to get grapheme clusters (which is usually what you should be using, unless you happen to know text is ASCII only.)
You can use ``` String.substring(int startIndex, [ int endIndex ]) ``` Example -- ``` void main(){ String s = "hello"; print(s.substring(1, 2)); } ``` Output ``` e ``` Note that , endIndex is one greater than startIndex, and the char which is returned is present at startIndex.
14,109,259
I'm working on an application written in C# where I basically need to act as my own certificate authority. The data flow is something like this: * The end user generates a public/private key pair and sends me proof of their identity and a certificate request of some kind with their public key * The app validates their ID * When the validation is complete, the app generates an X.509 certificate, based on a local, self-signed root, and sends it to the user * The user signs a file using the certificate, and sends the file to the app * The app validates the file against the signature, and stores the results in SQL Server. My questions: * Do you know of a tutorial or code examples that describes how to create and use a X.509 certificate as described above, without relying on an external CA and without calling command line utilities or using COM objects? I've looked at the `X509Certificate2` class, but the examples in MSDN don't show what I'm after. * Is it possible to use SQL Server 2008+ to do some of the certificate handling? Perhaps using `CREATE CERTIFICATE FROM FILE` and `BACKUP CERTIFICATE`? * If it can't be done with the standard Windows libraries, can it be done with the C# Bouncy Castle library? If so, are there some good code examples?
2013/01/01
[ "https://Stackoverflow.com/questions/14109259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/211378/" ]
The concise example of certgen with Bouncy Castle <http://netpl.blogspot.com/2012/12/how-to-create-x509certificate2.html> I've also blogged on signing and validating of xml documents <http://netpl.blogspot.com/2012/12/interoperable-xml-digital-signatures-c_4247.html>
I think you will change you mind about using command-line utilities but assuming you don't, I don't have the answer because I haven't done it but here are a few tips. I'm confident This can be done with bouncycastle C# library. The library is basically undocumented though. What I would do is first download an *earlier* version of bouncycastle Java library, for example version 1.45. The reason for downloading the earlier version is because it more closely resembles the current C# library. The Java API underwent some radical changes as of the 1.47 release. The reason for downloading the Java library at all is because most of the functionality and classes are the same for both, and the Java API contains at least Javadocs that can be perused with a web browser. I always have the Javadocs, the Java source code, and C# source code for the library at hand when coding with the C# library. I know this sounds horrible but it is not that bad. The C# source code (and the Java as well) is very readable and well written, so progress can be made. The user's certificate request should be a PKCS10 certificate request. There is a class `Org.BouncyCastle.Pkcs.Pkcs10CertificationRequest` that you should use. Use the `Pkcs10CertificationRequest(byte [])` constructor to create an instance of this class. The superclass of this class, `Org.BouncyCastle.Asn1.Pkcs.CertificationRequest`, has a method `GetCertificationRequestInfo` that will return a `CertificationRequestInfo` instance. This can be used to extract the pieces of the certificate request, and then you can use Wiktor's answer to create an X509 certificate.
32,322,945
I have a two DATETIME columns: event\_start and event\_end. I'm not sure why this isn't working. ``` SELECT * FROM ibclc_schedules WHERE NOW() >= event_start AND NOW() <= event_end ORDER BY event_start ASC LIMIT 1 ``` I get a "Notice: Trying to get property of non-object" printed to the screen.
2015/09/01
[ "https://Stackoverflow.com/questions/32322945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1938311/" ]
I suggest you to debug current datetime of mysql server with query `SELECT NOW();` and check it is really between event\_start and event\_end of your needed result.
i think this is a php error kindly check your php code or write your code here so we have an idea about that, or first check this query in phpmyadmin weather its returning something or not
251,471
I have a server with 8TB data, and a tape with high numbered 400GB tape cartridges. What would be the best solution to backup this server with the least effort ? I think after one full backup, I can make many increments on one 400GB tape. But how can I make the full backup across the tapes (with manual tape change), and how can I restore one file from the full backup and the increments ? Is there any easy way to do that like disk based tar backup ?
2011/03/24
[ "https://serverfault.com/questions/251471", "https://serverfault.com", "https://serverfault.com/users/74590/" ]
Don't try and do it yourself. You should be using a program such as [amanda](http://www.amanda.org/) or [bacula](http://www.bacula.org/) to manage your backups. Use amanda when you don't have a tape library. Use bacula when you have a tape library available. --- *mini rant follows* Sure, just using `dump` or `tar` works and is simple. How easy is it to restore a certain file from a week ago? A month ago? How do you keep track of what's where? Remember, backups are easy, but restores are the important part. You can design a method to keep track of what's going on and do all that work yourself. Go ahead! Enjoy the pain when things get complicated. But what you gain from taking the short amount of time out of your schedule to configure amanda (okay, it's more for bacula, but it's more complex. Bigger investment, bigger setup, bigger return) you get back almost immediately. We use it for even single-server backup scenarios as it's so easy to set up and you gain what you spent many times over in the long run.
I would suggest to do full initial backup that spans multiple tapes and then do differential backups over 5-7 tapes on daily basis. When size of differential backup grows to fill a full tape take another full backup and start the cycle over. In your case it will be one full backup about once a year. You could use Amanda to set it up.
251,471
I have a server with 8TB data, and a tape with high numbered 400GB tape cartridges. What would be the best solution to backup this server with the least effort ? I think after one full backup, I can make many increments on one 400GB tape. But how can I make the full backup across the tapes (with manual tape change), and how can I restore one file from the full backup and the increments ? Is there any easy way to do that like disk based tar backup ?
2011/03/24
[ "https://serverfault.com/questions/251471", "https://serverfault.com", "https://serverfault.com/users/74590/" ]
I'd certainly recommend full backups over incremental backups - it just saves so much pain! While you can do it with tar (at least the you can with the Gnu version of tar), I'd recommend using something a bit more robust - I like afio (unlike tar where you put files in an archive then compress the archive, [afio](http://linux.die.net/man/1/afio) compresses the file first then adds it the archive - a much more robust solution - and it will use any program you have available for compression!). It handles multivolume stuff.
As always with backups, "Best" refers to what you are backing up, why you are backing up (i.e. what your are trying to mitigate through backups), what tools you have, how much data, how often, retention policy, etc. I do use `tar` for mine. Amanda and Backula are too big/complicated IMHO for a single machine backup, but it all depends on the things listed above.
251,471
I have a server with 8TB data, and a tape with high numbered 400GB tape cartridges. What would be the best solution to backup this server with the least effort ? I think after one full backup, I can make many increments on one 400GB tape. But how can I make the full backup across the tapes (with manual tape change), and how can I restore one file from the full backup and the increments ? Is there any easy way to do that like disk based tar backup ?
2011/03/24
[ "https://serverfault.com/questions/251471", "https://serverfault.com", "https://serverfault.com/users/74590/" ]
Don't try and do it yourself. You should be using a program such as [amanda](http://www.amanda.org/) or [bacula](http://www.bacula.org/) to manage your backups. Use amanda when you don't have a tape library. Use bacula when you have a tape library available. --- *mini rant follows* Sure, just using `dump` or `tar` works and is simple. How easy is it to restore a certain file from a week ago? A month ago? How do you keep track of what's where? Remember, backups are easy, but restores are the important part. You can design a method to keep track of what's going on and do all that work yourself. Go ahead! Enjoy the pain when things get complicated. But what you gain from taking the short amount of time out of your schedule to configure amanda (okay, it's more for bacula, but it's more complex. Bigger investment, bigger setup, bigger return) you get back almost immediately. We use it for even single-server backup scenarios as it's so easy to set up and you gain what you spent many times over in the long run.
Have look in this link has every small details for tap backup <http://www.cyberciti.biz/faq/linux-tape-backup-with-mt-and-tar-command-howto/>
251,471
I have a server with 8TB data, and a tape with high numbered 400GB tape cartridges. What would be the best solution to backup this server with the least effort ? I think after one full backup, I can make many increments on one 400GB tape. But how can I make the full backup across the tapes (with manual tape change), and how can I restore one file from the full backup and the increments ? Is there any easy way to do that like disk based tar backup ?
2011/03/24
[ "https://serverfault.com/questions/251471", "https://serverfault.com", "https://serverfault.com/users/74590/" ]
Don't try and do it yourself. You should be using a program such as [amanda](http://www.amanda.org/) or [bacula](http://www.bacula.org/) to manage your backups. Use amanda when you don't have a tape library. Use bacula when you have a tape library available. --- *mini rant follows* Sure, just using `dump` or `tar` works and is simple. How easy is it to restore a certain file from a week ago? A month ago? How do you keep track of what's where? Remember, backups are easy, but restores are the important part. You can design a method to keep track of what's going on and do all that work yourself. Go ahead! Enjoy the pain when things get complicated. But what you gain from taking the short amount of time out of your schedule to configure amanda (okay, it's more for bacula, but it's more complex. Bigger investment, bigger setup, bigger return) you get back almost immediately. We use it for even single-server backup scenarios as it's so easy to set up and you gain what you spent many times over in the long run.
I'd certainly recommend full backups over incremental backups - it just saves so much pain! While you can do it with tar (at least the you can with the Gnu version of tar), I'd recommend using something a bit more robust - I like afio (unlike tar where you put files in an archive then compress the archive, [afio](http://linux.die.net/man/1/afio) compresses the file first then adds it the archive - a much more robust solution - and it will use any program you have available for compression!). It handles multivolume stuff.
251,471
I have a server with 8TB data, and a tape with high numbered 400GB tape cartridges. What would be the best solution to backup this server with the least effort ? I think after one full backup, I can make many increments on one 400GB tape. But how can I make the full backup across the tapes (with manual tape change), and how can I restore one file from the full backup and the increments ? Is there any easy way to do that like disk based tar backup ?
2011/03/24
[ "https://serverfault.com/questions/251471", "https://serverfault.com", "https://serverfault.com/users/74590/" ]
I've used all sorts of backups. Certainly Bacula is a reliable way to perform backups, but I think part of the question revolved around security and simplicity. It is harder to find an easier or more reliable means of backing up a file system than to use good old dump. (This presumes that you are using a file system supported by dump. According to tests done over the years, it is certainly better than tar which has few error correcting capabilities, and after an initial level 0 dump you can easily perform incremental backups.
I would suggest to do full initial backup that spans multiple tapes and then do differential backups over 5-7 tapes on daily basis. When size of differential backup grows to fill a full tape take another full backup and start the cycle over. In your case it will be one full backup about once a year. You could use Amanda to set it up.
251,471
I have a server with 8TB data, and a tape with high numbered 400GB tape cartridges. What would be the best solution to backup this server with the least effort ? I think after one full backup, I can make many increments on one 400GB tape. But how can I make the full backup across the tapes (with manual tape change), and how can I restore one file from the full backup and the increments ? Is there any easy way to do that like disk based tar backup ?
2011/03/24
[ "https://serverfault.com/questions/251471", "https://serverfault.com", "https://serverfault.com/users/74590/" ]
I'd certainly recommend full backups over incremental backups - it just saves so much pain! While you can do it with tar (at least the you can with the Gnu version of tar), I'd recommend using something a bit more robust - I like afio (unlike tar where you put files in an archive then compress the archive, [afio](http://linux.die.net/man/1/afio) compresses the file first then adds it the archive - a much more robust solution - and it will use any program you have available for compression!). It handles multivolume stuff.
Have look in this link has every small details for tap backup <http://www.cyberciti.biz/faq/linux-tape-backup-with-mt-and-tar-command-howto/>
251,471
I have a server with 8TB data, and a tape with high numbered 400GB tape cartridges. What would be the best solution to backup this server with the least effort ? I think after one full backup, I can make many increments on one 400GB tape. But how can I make the full backup across the tapes (with manual tape change), and how can I restore one file from the full backup and the increments ? Is there any easy way to do that like disk based tar backup ?
2011/03/24
[ "https://serverfault.com/questions/251471", "https://serverfault.com", "https://serverfault.com/users/74590/" ]
I've used all sorts of backups. Certainly Bacula is a reliable way to perform backups, but I think part of the question revolved around security and simplicity. It is harder to find an easier or more reliable means of backing up a file system than to use good old dump. (This presumes that you are using a file system supported by dump. According to tests done over the years, it is certainly better than tar which has few error correcting capabilities, and after an initial level 0 dump you can easily perform incremental backups.
Have look in this link has every small details for tap backup <http://www.cyberciti.biz/faq/linux-tape-backup-with-mt-and-tar-command-howto/>
251,471
I have a server with 8TB data, and a tape with high numbered 400GB tape cartridges. What would be the best solution to backup this server with the least effort ? I think after one full backup, I can make many increments on one 400GB tape. But how can I make the full backup across the tapes (with manual tape change), and how can I restore one file from the full backup and the increments ? Is there any easy way to do that like disk based tar backup ?
2011/03/24
[ "https://serverfault.com/questions/251471", "https://serverfault.com", "https://serverfault.com/users/74590/" ]
I'd certainly recommend full backups over incremental backups - it just saves so much pain! While you can do it with tar (at least the you can with the Gnu version of tar), I'd recommend using something a bit more robust - I like afio (unlike tar where you put files in an archive then compress the archive, [afio](http://linux.die.net/man/1/afio) compresses the file first then adds it the archive - a much more robust solution - and it will use any program you have available for compression!). It handles multivolume stuff.
I would suggest to do full initial backup that spans multiple tapes and then do differential backups over 5-7 tapes on daily basis. When size of differential backup grows to fill a full tape take another full backup and start the cycle over. In your case it will be one full backup about once a year. You could use Amanda to set it up.
251,471
I have a server with 8TB data, and a tape with high numbered 400GB tape cartridges. What would be the best solution to backup this server with the least effort ? I think after one full backup, I can make many increments on one 400GB tape. But how can I make the full backup across the tapes (with manual tape change), and how can I restore one file from the full backup and the increments ? Is there any easy way to do that like disk based tar backup ?
2011/03/24
[ "https://serverfault.com/questions/251471", "https://serverfault.com", "https://serverfault.com/users/74590/" ]
I'd certainly recommend full backups over incremental backups - it just saves so much pain! While you can do it with tar (at least the you can with the Gnu version of tar), I'd recommend using something a bit more robust - I like afio (unlike tar where you put files in an archive then compress the archive, [afio](http://linux.die.net/man/1/afio) compresses the file first then adds it the archive - a much more robust solution - and it will use any program you have available for compression!). It handles multivolume stuff.
``` #!/bin/bash INCR_LOG = "/var/log/increment.snar" DAY_OF_WEEK = $(date +%u) if [ $DAY_OF_WEEK = 0 ]; then rm $INCR_LOG; fi tar -cf archive-$DAY_OF_WEEK.tar --listed-incremental=$INCR_LOG /dir/to/be/backed/up ``` Something similar to that, set it up to run everyday in crontab. Will make a weekly full backup and daily incrementals.
251,471
I have a server with 8TB data, and a tape with high numbered 400GB tape cartridges. What would be the best solution to backup this server with the least effort ? I think after one full backup, I can make many increments on one 400GB tape. But how can I make the full backup across the tapes (with manual tape change), and how can I restore one file from the full backup and the increments ? Is there any easy way to do that like disk based tar backup ?
2011/03/24
[ "https://serverfault.com/questions/251471", "https://serverfault.com", "https://serverfault.com/users/74590/" ]
As always with backups, "Best" refers to what you are backing up, why you are backing up (i.e. what your are trying to mitigate through backups), what tools you have, how much data, how often, retention policy, etc. I do use `tar` for mine. Amanda and Backula are too big/complicated IMHO for a single machine backup, but it all depends on the things listed above.
``` #!/bin/bash INCR_LOG = "/var/log/increment.snar" DAY_OF_WEEK = $(date +%u) if [ $DAY_OF_WEEK = 0 ]; then rm $INCR_LOG; fi tar -cf archive-$DAY_OF_WEEK.tar --listed-incremental=$INCR_LOG /dir/to/be/backed/up ``` Something similar to that, set it up to run everyday in crontab. Will make a weekly full backup and daily incrementals.
66,560
Is there any way to enable tabbed browsing of documents in Microsoft Word (at least in Office 2003) like we see in EditPlus or TextPad?
2008/10/03
[ "https://superuser.com/questions/66560", "https://superuser.com", "https://superuser.com/users/48287/" ]
It's possible with [**OfficeTabs**](http://hi.baidu.com/officecm/blog/item/19de9c6dcf6276f2431694b0.html). ![alt text](https://i.stack.imgur.com/NJUXu.jpg) Read more about it [here](http://www.mydigitallife.info/2009/09/07/officetab-add-on-tab-feature-for-microsoft-office/).
With Office Tab, you can bring tabbed browsing to Word, Excel and PowerPoint. [Office Tab](http://www.extendoffice.com/) ![enter image description here](https://i.stack.imgur.com/mQcp6.jpg)
203,231
What does link quality mean in WLAN ?
2010/10/25
[ "https://superuser.com/questions/203231", "https://superuser.com", "https://superuser.com/users/25930/" ]
It's dependent on several factors, from the [Federal Standard 1037C for Telecommunications](http://www.its.bldrdoc.gov/fs-1037/fs-1037c.htm): > > **link quality analysis (LQA):** In > adaptive high-frequency (HF) radio, > the overall process by which > measurements of signal quality are > made, assessed, and analyzed. > > **Note 1:** > In LQA, signal quality is determined > by measuring, assessing, and analyzing > link parameters, such as bit error > ratio (BER), and the levels of the > ratio of > signal-plus-noise-plus-distortion to > noise-plus-distortion (SINAD). > Measurements are stored at--and > exchanged between--stations, for use > in making decisions about link > establishment. > > **Note 2:** For adaptive HF > radio, LQA is automatically performed > and is usually based on analyses of > pseudo-BERs and SINAD readings. > > > [Bit error rate](http://en.wikipedia.org/wiki/Bit_error_ratio) (BER): In digital transmission, the number of bit errors is the number of received bits of a data stream over a communication channel that have been altered due to noise, interference, distortion or bit synchronization errors. [Signal-to-noise and distortion ratio](http://en.wikipedia.org/wiki/SINAD) (SINAD): Is calculated with power output/input from the radio waves.
I think there are a few types of link quality, but in simple terms, it means how much of the data you send and receive will make it to the destination in good condition. High link quality means the requests you send will make it there intact, and the responses should be in good condition as well. Low quality will give you oddities. You may see corrupt images (twisted strangely, funny colors, etc), random text, or the pages might not load at all. Obviously you want to get the highest quality you can, as low quality can slow down or break your internet.