Ember approach for setting controller computed property from action

Question: I'm new  to Ember and trying to follow the Data Down Action Up approach with my controller acting as the main parent 'component' with a number of components sending actions up to the controller to set values on models that will eventually trickle back down new value to the components. I know controllers are going away but I need this controller to hold all the state if you will...
I'm struggling with my approach in that I want to set a number of computed properties on my controller that watch model properties. Most difficult seemingly is setting the value of one of these computed properties that needs to set some other property when an action fires. Here is some of my controller (see updated exampled below, this left for reference):
//controllers/groupPlanning.js

import Ember from 'ember';

export default Ember.Controller.extend({

    groups: Ember.computed('model.@each.groups', function(){
        return this.get('model').get('groups');
    }),

    enrollmentGroup: Ember.computed('groups', function(){
        this.get('groups').forEach(function(group) {
            if (group.get('name') === 'Enrollment'){
                return group;
            }
        }):

    }),

    enrollmentGroupPercent: Ember.computed('enrollmentGroup', function() {
        var group = this.get('enrollmentGroup');
        return group.get('year') * this.get('someOtherNumber');
    }),

   ...

    actions: {
        setGroupYear: function(year){
            var group = this.get('enrollmentGroup');
            group.set('year', year);
            group.save();
        }
    }

});

UPDATE: The example above had a number flaws, the below code is to show the corrections per Lux's solution:
//controllers/groupPlanning.js

import Ember from 'ember';

export default Ember.Controller.extend({

    groups: Ember.computed('model.groups.[]', function(){
        return this.get('model.groups');
    }),

    enrollmentGroup: Ember.computed('groups', function(){
        return this.get('groups').findBy('name', 'Enrollment');
    }),

    enrollmentGroupPercent: Ember.computed('enrollmentGroup.year', 'someOtherNumber', function() {
        var group = this.get('enrollmentGroup');
        return group.year * this.get('someOtherNumber');
    }),

   ...

    actions: {
        setGroupYear: function(year){
            var group = this.get('enrollmentGroup');
            group.set('year', year);
            group.save();
        }
    }

});

Aside from asking if this approach seems reasonable, I'm having a problem actually setting the value of enrollmentGroup in my action:
group.set('year', year);
which throws and error of
Uncaught TypeError: Cannot read property 'set' of undefined
Any pointers here would be appreciated. Thanks!
Comment: I don't think `enrollmentGroup` computed property is returning anything, which would explain it being undefined. I suggest using [Ember.Array#find](http://emberjs.com/api/classes/Ember.Array.html#method_find).
Comment: Actually I dont think you need a computed property for groups. Just use model.groups? By the way, if you set a name of a group, the computed groups property will compute again. enrollmentGroup will be computed again and so on. Maybe what you need is just this.get('model.groups') and for the enrollmentGroup: this.get('model.groups').findBy({name':'Enrollment'})
Comment: it does appear to return a Class when I console.log it out, however thanks for sharing the .find method that looks helpful :)
Comment: whats odd is that i can set the value from within the enrollmentGroup computed property with `group.set('name', 'newName');` but not from within my action hook. Also fixed a typo.. now using `group.get('name')`
Comment: Thanks, but I'm pretty sure I need computed properties in order to chain some reactions to any one of the `model.groups` attributes (like `year`) as I need to run some computations after any model changes, and that could affect computations from models that weren't changed. I'm thinking observer might be the approach per @Remi solution but still looking to avoid observers here and see if computed can do it.
Answer: First, your dependency on the enrollmentGroupPercent is missing the year. Instead of
enrollmentGroupPercent: Ember.computed('enrollmentGroup', function() {

use
enrollmentGroupPercent: Ember.computed('enrollmentGroup.year', 'someOtherNumber', function() {

You definitely need the year because you modify it.

second, your problem:

Uncaught TypeError: Cannot read property 'set' of undefined

this looks like group is null/undefined at this time! maybe check this with the debugger!
So definitly enrollmentGroup returns nothing. Maybe you just have no group with the name Enrollment. But I think you maybe ran into something more tricky.
I assume your model is an ember-data model, and groups an hasMany relationship.
This code does not make any sense:
groups: Ember.computed('model.@each.groups', function(){
    return this.get('model').get('groups');
}),

First I would recommend to replace this.get('model').get('groups') with this.get('model.groups') or get(this, 'model.groups') after setting get to Ember.get.
Then you use @each on model, which makes only sense if model is an array.
Probably you want to recompute the CP when groups are added/removed. In that case use model.groups.[] as dependency key. If you want to aggregate data from the groups, for example calculate a total you can use model.groups.@each.quantity and the CP will recalculate whenever a quantity on any group changes.
You actually need this if name could change, because then the list of groups does not change only the name so maybe you set the name later to Enrollment?
Now you should be able to replace
enrollmentGroup: Ember.computed('groups', function(){

with
enrollmentGroup: Ember.computed('groups.@each.name', function(){

but due to a Bug in the current ember version this will not work!
It is important to understand then that the stores methods and model relationships don't return normal values but instances of ArrayProxy, ObjectProxy, PromiseArray and PromiseObject.
So actually groups is a PromiseArray of PromiseObjects. But you can unwrap the PromiseObjects in your groups CP:
groups: Ember.computed('model.groups.[]', function(){
    let promise = this.get('model.groups').then(groups => Ember.RSVP.all(groups));
    return DS.PromiseArray({promise});
}),

and then use content to observe the actual value:
enrollmentGroup: Ember.computed('groups.content.@each.name', function(){
    return this.get('groups').findBy('name', 'Enrollment');
}),

Now enrollmentGroup should always be up to date! So the only issue you might have is that you fire your action to early!
If you still have problems please provide a minimal example on ember-twiddle!
Comment: thank you a whole lot! I have some learning to do here as you've covered a lot... but i'm feeling like this is getting me real close. I'll report back.
Comment: This ended up setting me straight. My example code was flawed as you noted. Many thanks!
Answer: You are trying to set the value of a computed propery, which won't work like this. I would suggest the observer approach:
enrollmentGroupObserver: Ember.observer('groups', function(){
        this.get('groups').forEach(function(group) {
            if (group.get('name') === 'Enrollment'){
                this.set('enrollmentGroup', group);
            }
        }):

    }),
enrollmentGroup: null,

Comment: Thanks, this is a potential, although I'm trying to find a way to not use the observer, to avoid the [observer tip-jar](https://www.youtube.com/watch?v=7PUX27RKCq0), is there anyway to do something similar as a computed property? I'll play with this and report back as well.


cygwin64 :: ./configure returns "configure: exit 77"

Question: I've installed Cygwin64 and I now would like to install extundelete.
So I downloaded it, decompressed the file, but when I run ./configure it says:
$ ./configure
Configuring extundelete 0.2.4
configure: error: in `/cygdrive/c/Users/franc/Desktop/extundelete-0.2.4':
configure: error: C++ compiler cannot create executables
See `config.log' for more details

So I open the config.log file and I find some error:
configure:2876: $? = 0
configure:2865: CC -v >&5
Using built-in specs.
COLLECT_GCC=CC
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-pc-cygwin/9.2.0/lto-wrapper.exe
Target: x86_64-pc-cygwin
Configured with: /cygdrive/i/szsz/tmpp/gcc/gcc-9.2.0-2.x86_64/src/gcc-9.2.0/configure --srcdir=/cygdrive/i/szsz/tmpp/gcc/gcc-9.2.0-2.x86_64/src/gcc-9.2.0 --prefix=/usr --exec-prefix=/usr --localstatedir=/var --sysconfdir=/etc --docdir=/usr/share/doc/gcc --htmldir=/usr/share/doc/gcc/html -C --build=x86_64-pc-cygwin --host=x86_64-pc-cygwin --target=x86_64-pc-cygwin --without-libiconv-prefix --without-libintl-prefix --libexecdir=/usr/lib --enable-shared --enable-shared-libgcc --enable-static --enable-version-specific-runtime-libs --enable-bootstrap --enable-__cxa_atexit --with-dwarf2 --with-tune=generic --enable-languages=c,c++,fortran,lto,objc,obj-c++ --enable-graphite --enable-threads=posix --enable-libatomic --enable-libgomp --enable-libquadmath --enable-libquadmath-support --disable-libssp --enable-libada --disable-symvers --with-gnu-ld --with-gnu-as --with-cloog-include=/usr/include/cloog-isl --without-libiconv-prefix --without-libintl-prefix --with-system-zlib --enable-linker-build-id --with-default-libstdcxx-abi=gcc4-compatible --enable-libstdcxx-filesystem-ts
Thread model: posix
gcc version 9.2.0 (GCC)
configure:2876: $? = 0
configure:2865: CC -V >&5
CC: error: unrecognized command line option '-V'
CC: fatal error: no input files
compilation terminated.
configure:2876: $? = 1
configure:2865: CC -qversion >&5
CC: error: unrecognized command line option '-qversion'; did you mean '--version'?
CC: fatal error: no input files
compilation terminated.
configure:2876: $? = 1
configure:2896: checking whether the C++ compiler works
configure:2918: CC    conftest.cpp  >&5
CC: fatal error: cannot execute 'cc1plus': spawn: No such file or directory
compilation terminated.
configure:2922: $? = 1
configure:2960: result: no
configure: failed program was:
| /* confdefs.h */
| #define PACKAGE_NAME "extundelete"
| #define PACKAGE_TARNAME "extundelete"
| #define PACKAGE_VERSION "0.2.4"
| #define PACKAGE_STRING "extundelete 0.2.4"
| #define PACKAGE_BUGREPORT "extundelete.sourceforge.net"
| #define PACKAGE_URL ""
| #define PACKAGE "extundelete"
| #define VERSION "0.2.4"
| /* end confdefs.h.  */
|
| int
| main ()
| {
|
|   ;
|   return 0;
| }
configure:2965: error: in `/cygdrive/c/Users/franc/Desktop/extundelete-0.2.4':
configure:2967: error: C++ compiler cannot create executables
See `config.log' for more details

And the .log file ends up with configure: exit 77
Is it possible to compile files in Cygwin64?
Comment: Configuration output doesn't look like the one produced by CMake. Why do you use `cmake` tag?
Comment: @Tsyvarev, what command should I use instead? The output is longer, do you want all the >200 lines?
Comment: I don't mean that you use wrong command. I ask why do you use `cmake` tag for your question. How does this tag relate to the problem?
Comment: extundelete is a utility that can recover deleted files from an ext3 or ext4 partition. Why you install on cygwin ?
Comment: do NOT build under the Windows Home directories. The permissions inherited from `C:\Users\franc` can screw the execution permission need by the build process. Use the `/home/franc` or the `/usr/src` directories. PS: Of course it is possible to build under Cygwin 64bit; how do you think the packages were built ?
Answer: Your build problem is likely due to permissions inherited from C:\Users\franc that screw the execution permission needed by the build process.
Use the /home/franc or the /usr/src directories or other similar ones.
Do NOT build under the Windows Home directories.
Unfortunately you can not build the program on Cygwin for another reason; see below:
In a proper directory you will have:
$ ./configure
Configuring extundelete 0.2.4
Writing generated files to disk

To avoid some scope error, you can remove the restricting invocation from the makefiles
$ find . -name Makefile -exec sed -e "s/-std=c99//" -i {} \;
$ find . -name Makefile -exec sed -e "s/-std=c++0x -std=c++11//" -i {} \;

and then build
$ make
make -s all-recursive
Making all in src
...
insertionops.cc: In function 'std::ostream& operator<<(std::ostream&, const ext2_inode&)':
insertionops.cc:36:36: error: 'const struct ext2_inode' has no member named 'i_dir_acl'; did you mean 'i_file_acl'?
   36 |   os << "Directory ACL: " << inode.i_dir_acl << std::endl;
      |                                    ^~~~~~~~~
      |                                    i_file_acl
make[2]: *** [Makefile:437: extundelete-insertionops.o] Error 1
make[1]: *** [Makefile:268: all-recursive] Error 1
make: *** [Makefile:208: all] Error 2

and you can not overcome the lack of extended property from the Cygwin ext2 inode structure.
As Cygwin is a Windows user mode program it can not mount a filesystem not recognized by Windows as its support of ext2 is very limited and mainly focused on just making the file system on a external disk but it can not really use it.


What data is passed from the CPU to the GPU each frame?

Question: I've been reading a bit about the graphics pipeline for processing on a graphics card, and I'm interested to know in what kind of format data is passed from the CPU to the GPU when rendering 3D graphics, for example for a video game.
I understood that the CPU would calculate what's actually going on inside the game each frame, for example it might have some internal representation of the different characters on the screen and maybe calculate some collision detection between them, and then it might move them around a bit and output the change to the GPU. Then the GPU must receive some information corresponding to many different triangles in different locations, and it has rasterize them and add textures and then combine them all together into a HD pixel array.
So what would be a kind of schematic overview of the form of the data passed to the GPU each frame? I imagine something like a great big array of sets of three points which respond to the vertices of triangles, with associated textures or pointers to textures or something? I expect there would need to be additional information passed each frame as well as the actual triangles and textures, and I'm interested to know what this would be also.
Also, is there some kind of standard format for this, or does it depend on the hardware?
Answer: How much data is passed from the CPU to the GPU per frame depends on the engine you are using and its needs. Usually, you want to keep it minimal to avoid that the GPU needs to wait for data because the CPU can't deliver it fast enough. I can not guarantee you, that the following is always the same for all engines and graphic APIs since I have only written OpenGL code myself so far, but to my knowledge, it is quite similar.
What you usually do is that you send all data that doesn't change to the GPU at the beginning. Objects (meshes) and textures are typical candidates for this. Animated meshes like characters can also be loaded in advance by providing a default position.
The object data consists of vertices. They are control points that store the position of each point and an arbitrary set of additional information. A typical additional piece of information might be a color, surface normal, or texture coordinate (this does not specify which texture). Note, that there is no information at this point, how those vertices are connected. This is why I put "meshes" into parenthesis in the previous section.
Now you have a bunch of vertex groups and textures and it is time to render our scene. We assume, that all work that is not related to rendering is done by the CPU. Most of it can also be done by the GPU, but lets keep it simple.
The CPU calculates where every object is positioned in the current frame, including the camera. It also calculates the skeletal state of our animated characters. Now, to render a single object, we need to provide the following information to the GPU:

the object data we want to use
the textures we want to use
connectivity of the vertices
the shader program we want to use
the data the shader program requires to do its job (usually some transformation matrices and vectors)

The first two are just IDs we got from our API/engine when we uploaded the data. You should know for all your objects, which mesh and texture IDs they use. The third point, connectivity, actually tells the GPU how the single vertices are connected to each other. In OpenGL, there are several ways to specify this. A lot of them assume a specific order in the data, for example that 3 vertices in a row represent a single triangle. But there are also explicit ways by providing an index list to the GPU (This is usually also done at startup).
Now that the GPU knows which data to use and how it is connected, it needs to know what to do with it. This is done by selecting a shader program.
Shaders are small programs that run on the GPU. They have several stages that turn your mesh into actual pixels on your screen (see OpenGL rendering pipeline). You usually compile several of them at the beginning when uploading all the other data. Those programs generally also need some additional information to run and you need to pass that to the GPU. What that data is, strongly depends on the effects you want to use, but something you need very often are the transformations needed to place a vertex in relation to the camera and the projection you want to use (perspective, parallel). Now the shader program can calculate each vertex position on the screen, create triangles from it and color each of its pixel as desired (using the textures you specified). You do this for every object in your scene (that is not culled).
To sum it up:
For a single object in a basic OpenGL engine, you pass the IDs of its vertex data, textures and shader program to the GPU, which are just numbers. Then you pass all data needed by the shader program. This is mostly a bunch of floats for the transformations. Finally, you also tell the GPU how the data is connected for your current "draw call". There is also not much data transfer involved here, since you either have your data ordered in a specific way and need to tell the GPU just which method to use or you have uploaded a connectivity list upfront and tell the GPU the ID of the index list it should use.
Please note, that the described procedure is based on the approach that is described in most tutorials. Modern engines use several optimization techniques to balance CPU and GPU processing power so that they are always busy. This might require more involved data transfer. Also note, that the data transfer itself has bandwidth limitations that need to be considered.
Comment: Thanks for a great answer. Do you have a link to an explanation of some different ways to specify connectivity?
Comment: You can check the API description of [`glDrawArrays`](https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glDrawArrays.xhtml). It gives you a list of possible inputs like `GL_TRIANGLES` or `GL_TRIANGLE_STRIP`. However, it is not explained there how the data needs to be ordered and how the API uses it. Maybe you should read some simple tutorials like [this one](https://learnopengl.com/Getting-started/Hello-Triangle) and some of the following chapters. It should give you a good idea how the things that I described work. You don't need to code anything. Just read it. ;)
Answer: The short answer to this question is: everything
On any give frame almost any kind of data my be needed to render that new and wonderful object that just popped into view. It's shader needs to be loaded and compiled, its textures, buffer data, specializations, push constants, if you can dream it up for a render call then it needs to find its way to the GPU on a per frame basis.
This is the reason GPU's have rich and diverse paths for loading data, along with dedicated hardware and code for handling all the red tape that goes along with it.
What is its format:
Again the answer to this question is: everything GPU's handle specialized data types that we don't see on the CPU while doing c/c++/whatever programming. Normalized 8 bit floating point values for example.
For technology demo's and simple scene's much of that data can be preloaded, but for any program that is going to do meaningful work, expect any kind of data to be loaded on a per frame basis.
Don't imagine great big arrays, imagine rich and diverse data. Tutorials will focus on the great big arrays, but they are just the tip of the iceberg.
Finally, don't image the CPU as driving everything. Thanks to compute shaders the GPU is taking more control of the action.
Comment: I understood from the other answer that textures would be passed to the VRAM at the start rather than each frame. Are you saying they're passed each frame? Or just when a new texture is needed it's passed that frame?
Comment: Whenever possible the majority of textures are sent early on, but in a large program, the number and size of texture data will far surpass the available memory and texture data will need to be uploaded dynamically. (and textures that are no longer in needed will be removed or overwritten)
Comment: But you won't need to transfer that data every single frame. Loading and freeing data can usually be done less frequently, for example when hitting sector boundaries.
Comment: Now we are splitting hairs, keeping the hardware transfer units busy and avoiding bottlenecks is an interesting subject. One solution to long start up times is to load only the lower mip levels since they can be brought in exponentially faster, then continuing to load higher mip levels interactively will require a load every frame. This extends nicely to distance objects that get only the low mip levels loaded and higher mip levels are loaded only as the camera passes a certain distance from the object. Using this system textures are continually being loaded.
Comment: My answer was in support of the other answer here, with a slightly different take on the subject, the 40 thousand foot view so to speak.
Comment: Avoiding data transfer bottlenecks is indeed a valid point. I just haven't seen any engine where data uploading happens every frame, but I am no AAA game developer. Maybe it is really necessary for high-end production code. Anyways, good point.
Comment: What is 'mip level'?
Comment: @Joe Check [this link](https://en.wikipedia.org/wiki/Mipmap)


How to escape a single quote in a dynamic expression with functions?

Question: Need to insert a parameter into a string using the dynamic data function from the pipeline parameters.  Have tried backslash, double backslash, double single quote,@, @@, and other such nonsense.  Just need a simple way to escape a single quote in a string.
Answer: I actually found out.  It's 2 single quotes apparently.  I forgot to do it in both places, I had a single \ in the second place!
Comment: Thank you! I struggled for a while with this issue, and double apostrophes were the trick. My issue was to do with constructing a custom Lookup activity based on a parameter. Here is how the working query looks now: `@concat('select count(*) Count from ProcessedFiles where Filename=''', item().name, '''')`
Comment: No problem, glad someone else got some help out of my struggles!
Comment: @bdforbes in order to mimic formatted strings rather than endless concatenations :
 `@replace('select count(*) Count from ProcessedFiles where Filename=''{MyFileName}''', '{MyFileName}', item().name)`


Trying to summon an dropped diamond with a name and enchantment; only summons dropped diamond

Question: <code>/summon minecraft:item ~ ~ ~ {Item:{id:"minecraft:diamond",CustomModelData:775000,display:{Name:'[{"text":"Enchanted Diamond","italic":false}]'},Enchantments:[{id:mending,lvl:1}],HideFlags:1,Count:1b}}
</code>
It's supposed to summon a dropped item named "enchanted diamond" with a mending enchantment, but it just summons a dropped diamond.
Comment: Possible duplicate of [Where do I put item tags on items inside a chest or your inventory?](https://gaming.stackexchange.com/questions/272179/where-do-i-put-item-tags-on-items-inside-a-chest-or-your-inventory)
Comment: Welcome to Arqade! On Minecraft commands questions, please see our [guide on what to do before asking a Minecraft commands question](https://gaming.meta.stackexchange.com/q/13507/4797), especially the part about "what you've tried so far", and [edit] in the requested information to your post.
Comment: https://stackoverflow.com/help/minimal-reproducible-example
Answer: For things like this I suggest using the wonderful website mcstacker.net
I'm going to assume you don't actually need the enchantment to work and just want the enchantment glint, as mending does not work on diamonds.
This command is probably what you are looking for:
<code>/summon item ~ ~ ~ {Item:{id:"minecraft:diamond",Count:1b,tag:{display:{Name:'{"text":"Enchanted Diamond","italic":false}'},CustomModelData:775000,Enchantments:[{}]}}}
</code>
Anyone else is probably using a different CustomModelData value or none at all, so here is a general purpose command for anyone else who might need this:
<code>/summon item ~ ~ ~ {Item:{id:"minecraft:diamond",Count:1b,tag:{display:{Name:'{"text":"Enchanted Diamond","italic":false}'},Enchantments:[{}]}}}
</code>


How do I fix this error message "Initialization error (Eslint). Unexpected Identifier"?

Question: I have Eslint and JSCS setup to reformat some code base with airbnb js style guide in WebStorm. I have been using this setup effectively for the past 2 days, but all of a sudden, WebStorm started throwing this error...

Problem with ESLint reformatting:index.js: Initialization error (ESLint). Unexpected identifier

I thought maybe I had some error in my .eslintrc but then I had used the same config to successfully refactor about 150 files before this sudden error.
Prior to this, the JSCS compiler was occasionally throwing "less than a minute timeout" exceptions, but then I would fix this with closing and reopening the file. The eslint though seems not to be falling for this trick.
This is my .eslintrc config

{
  "extends": "airbnb",
  "env": {
    "browser": true,
    "node": true
  },
  "globals": {
    "document": false
  },
  "rules": {
    "validateIndentation": 4,
    "func-names": [
      "error",
      "never"
    ],
    "react/jsx-filename-extension": [
      1,
      {
        "extensions": [
          ".js",
          ".jsx"
        ]
      }
    ],
    "jsx-a11y/label-has-for": [
      2,
      {
        "components": [
          "Label"
        ],
        "required": {
          "some": [
            "nesting",
            "id"
          ]
        },
        "allowChildren": false
      }
    ],
    "jsx-a11y/anchor-is-valid": [
      "error",
      {
        "components": [
          "Link"
        ],
        "specialLink": [
          "to",
          "hrefLeft",
          "hrefRight"
        ],
        "aspects": [
          "noHref",
          "invalidHref",
          "preferButton"
        ]
      }
    ]
  }
}

Some part of package.json

{
    "eslint": "^4.14.0",
    "eslint-config-airbnb": "^16.1.0",
    "eslint-loader": "^1.9.0",
    "eslint-plugin-flowtype": "^2.40.1",
    "eslint-plugin-import": "^2.8.0",
    "eslint-plugin-jsx-a11y": "^6.0.3",
    "eslint-plugin-react": "^7.5.1",
    "extract-text-webpack-plugin": "^3.0.2",
    "prop-types": "^15.6.0",
    "react": "^16.2.0",
    "react-dev-utils": "^4.2.1",
    "react-dom": "^16.2.0",
    "react-redux": "^5.0.6",
    "react-router-dom": "^4.2.2",
  },
  "babel": {
    "presets": [
      "react-app",
      "flow"
    ]
  },
  "eslintConfig": {
    "extends": "react-app"
  }
}

Can some one throw me some pointers on how I can go about fixing this. I suspect it might be more of a WebStorm error than Eslint.
PS: Forgive me if this question might be better suited at superuser. I just thought it's most likely someone here might have faced the same issue.
Comment: @Rikard's fix works. If you need to do this inside WebStorm, open Preferences, go to Language and Frameworks->Node.js and NPM->Node interpreter. Mine defaulted to the first version of Node I'd installed, but I also use nvm. I fixed my issue by pointing to a newer version of Node from within nvm.
Comment: @lena,  was not able to recreate the issue with a fresh project the were passing the linting with the same setup. However testing the eslint on non `js` files produced a much more detailed error pointing to eslinting in lodash.   `yarn upgrade` helped
Comment: I had a simular problem, but mine got solved by updating node from version 8 to 14. Simplest way was just to download a new version of node from nodejs.org and run the installer.
Comment: @lena, `Problem with ESLint reformatting:index.js: Initialization error (ESLint). Unexpected identifier` is the same message that appears on clicking show ballon link. It just re formats the same message in a better looking ballon tooltip box.
Comment: no idea:( please share a sample project that can be used to recreate the issue, plus your idea.log (https://intellij-support.jetbrains.com/hc/en-us/articles/207241085-Locating-IDE-log-files)
Comment: As corinna000 already hinted, this also applies to other JetBrains products such as RubyMine. (Tested on `2022.3`)
Answer: i use this pattern for my eslint configuraion in phpstorm and error has gone now,
{**/*,*}.{js,ts,jsx,tsx,html,vue},{!node_modules/*}

Comment: Good point using **,{!node_modules/*}**, It solved the error for me
Comment: I agree with A-Palgy. You set this pattern in the ESLint settings at "Run for files". It fixed [`ESLint: Inizielization error (ESLint). Unexpected token ...` for me](https://i.stack.imgur.com/fTOoX.png). These settings are directly linked at the end of this error message line.
Answer: Solved by a yarn upgrade

My attempts at recreating the issue with a fresh project failed, with the same configs, both eslint and jscs were running successfully.
However on using the WebStorm context menu command Apply ESlint Code Style Rules on non js files(tested on .eslintrc itself), i got a much more detailed error.

Error on attempt to find parent and base ESLint configuration files of '.eslintrc': [projectpath]\node_modules\lodash\lodash.js:386 '\u0149': ''n', '\u017f': 's',

I double checked lodash package node_modules and package.json, tripple checked the settings configs(Eslint & JSCS) and was sure I had identical setup to the test projects that were linting without errors.
Running yarn upgrade lodash saved my hair. Since I was already running the latest lodash, I think yarn's Resolving and Rebuilding the packages did the trick.
Hope someone might find this helpful somewhere along the line.
Comment: `npm upgrade` saved me
Comment: I get the same error after adding a newer package. `yarn upgrade eslint` fixed my PyCharm issue.


Could you lose your data if something goes wrong when you upgrade your OS to version 16?

Question: I also would like to know a few other things. I need to know roughly the size that would be downloaded (roughly). Would it be in GB's, or in hundreds of MB's or anything else that I need to know. Can I work on my system while the files are being downloaded?
Thank you.
Answer: You can always lose data if something goes wrong, but it's not that likely. Even if the upgrade messes up, you can use the Live Environment to copy files to a USB drive and reinstall.
The upgrade will tell you exactly how much it is going to download when you start it. You can cancel it then if it's too much. The size varies per user, as everyone has a slightly different setup, but a near-fresh install of 15.10 with all packages fully updated says the upgrade will download 789MB. This is probably different on 14.04, and is a very low estimate, since there are only the default packages installed. The Ubuntu 16.04 ISO itself is around 1.4GB, but that's not accurate for an upgrade.
You can use Ubuntu throughout the whole upgrade process, but that's not necessarily a good idea. It's perfectly fine to keep using your computer while the upgrade downloads, but keep an eye on it and stop doing stuff when it actually begins upgrading.
Comment: From looking at the questions flowing in on Ask Ubuntu recently, the upgrade paths to 16.04 seem not that solid yet, so I strongly suggest making a full backup before starting the upgrade. And about performance... A fresh reinstall of the new release, overwriting the old installation (after backing up all the data so that you can copy it back afterwards) will always result in the best performance you can get. Upgraded systems *may* become slower, but this varies very much from system to system and depends on many factors.
Comment: Does upgrading to 16 provide me any benefit in terms of performance?
Comment: I downloaded the ISO and tried to install it, and there are three options it provides me: 1. To create a separate partition if I need to retain all the data in it. 2. To erase disk completely and install, 3. The data of ubuntu 14.04 would be removed and 16 would be installed. I need to retain all the data and install 16 instead of 14, not create a separate partition for it. So How do I go about it? What does the third option mean when he said files related to 14.04 would be lost? Thank you.
Comment: if you're keeping your data and installing 16.04 without creating a new partition, you're upgrading. Check ou thte guides on putting /home on a separate partition and go from there.


Finding prime numbers in c++

Question: I'm currently learning c++ for the first time and I've written a cpp bool function to find if an integer is a prime number.
The code was:
bool isPrime(int n) {
    for (int i = 2; i < n; i++) {
        if (n % i == 0)
            return false;
        else
            return true;
    }
}

However, it turns out that 9 is also considered as a prime number with this function.
I found a solution just by removing the else statement,
bool isPrime(int n) {
    for (int i = 2; i < n; i++) {
        if (n % i == 0)
            return false;
    }
}

but I still don't get why the else statement had anything to do with it in the first place. Can anyone help me out?
Comment: @Matt `sqrt(n)`
Comment: You need the `return true` to be outside the `for` loop.  If all checks fail than it's true.  The `else` statements means it returns true the first time the test fails.
Comment: And you only need to check up to `n/2`
Comment: second version is missing `return true` at the end.
Comment: `9%2` is `1`.   So, on the first iteration of the loop, the first code returns `true` when `i == 2`.       More generally, the first code only ever checks `i` with a value of `2`, and immediately returns.   The loop is never executed for `i` with values greater than `2`.     The second version runs through all loop iterations, before concluding that a value is prime.
Comment: @S.M - better `isqrt(n)` - where `isqrt()` is specified as being the largest integer less than or equal to the square root.   There are plenty of algorithms for computing `isqrt()` without use of floating point.
Comment: There are undoubtedly other questions that this could be made a duplicate of.
Comment: Why is this a duplicate ?  She's not asking how to find prime numbers, she is asking what is wrong with her approach.
Answer: Because of the if statement.
    if (n % i == 0)
        return false;
    else
        return true;

The condition reads "if n is divisible by the current number".  The condition will either be true (in which case n is not prime) or false (it might be prime) so one of the branches must be taken and the function will exit in either case, possibly prematurely.
Removing the else prevents early return, however, it also prevents true being returned by the function. You can simply add return true to the end of the function:
bool isPrime(int n) {
    for (int i = 2; i < n; i++) {
        if (n % i == 0)
            return false;
    }
    return true;    // must be prime
}

Answer: Because it will return in the first loop!
When the function enters the else, it will return true.
Any odd number will return true — and 9 is the first odd number bigger than 1 which is not a prime.
Try this:
bool isPrime(int n) {
    for (int i = 2; i < n; i++) {
        if (n % i == 0)
            return false;
        else
            continue;
    }
    return true;
}

Comment: `else continue` is redundant - the loop will continue without it.
Comment: I know. I put it to be more explanatory.
Answer: The only way a number is prime is when the loop completes, so the return true; statement should be outside the loop.  You only have to check numbers up to the square root of n.
Also, you need to handle the case where n is less than 2.
#include <cmath>

bool isPrime(int n)
{
    if (n < 2)
    {
        return false;
    }
    for (int i = 2; i <= sqrt(n); i++)
    {
        if (n % i == 0)
        {
            return false;
        }
    }
    return true;
}

Comment: It's probably better to precalculate `sqrt(n)` to ensure that it is not recalculated on each iteration.  That said, the gain in performance over the original code is so dramatic that it wouldn't matter all that much — and a good optimizer might hoist the `sqrt()` call out of the loop — but it is probably better not to assume that it will.
Comment: @JonathanLeffler, That's a valid point, although I think most compilers will take care of it.  I guess the loop header could be written as `for (int i = sqrt(n); i > 1; i--)`.  I think that would add more confusion than necessary considering the question that was asked, though,
Comment: You want to start at the small end; more numbers are multiples of 2 and 3 than are multiples of 29 and 31 (at least for computers and finite arithmetic — infinities are funny things).  Another optimization is to check for even outside the loop, and then have the loop only increment over odd numbers from 3.  Or you can check 2 and 3 outside the loop and then only check values of the form 6N±1 (for N = 1, 2, …).  Etc.  These do fewer modulo operations.
Comment: Another good point, but it also serves to illustrate what I just said - this is quickly getting way too complicated for the question at hand.
Comment: Agreed, and it isn't fair to pick on only your answer because others have the same (or at least similar) issues.  Actually, two of them don't even have the `sqrt()` optimization, which makes a fantastic difference even when the numbers being checked are quite small.  The other changes are definitely second-order improvements.
Answer: 9 is odd. Which means it's not divisible by 2. In fact it's the first odd number after 1 that is not prime. Your code explicitly returns true if n is not divisible by 2.
for (int i = 2; i < n; i++) {
    if (n % i == 0)
        return false;
    else
        return true;
}

The first time the for loop runs, i is 2. Either n % i == 0 is true or it is false. If true, your function immediately returns false. If false, your function immediately returns true.
You need to move the return true statement outside the loop. Only after checking all possible divisors by completing the for loop do you know if the number n is prime.

Finding prime numbers in c++


Button will not change color (HTML5)

Question: I have three buttons that act much like radio buttons - where only one can be selected at one time:
<button id="btn-bronze" name="btn-bronze" type="button" class="blue-selected">Bronze</button>
<button id="btn-silver" name="btn-silver" type="button">Silver</button>
<button id="btn-gold" name="btn-gold" type="button">Gold</button>

For the normal, unselected state, all the buttons use a gradient background:
#btn-bronze
{
    float: left;
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0.0, #F8F8F8), color-stop(1.0, #AAAAAA));
    -webkit-border-top-left-radius: 6px;
    -webkit-border-bottom-left-radius: 6px;
    width: 33%;
    height: 100%;
}

#btn-silver
{
    float: left;
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0.0, #F8F8F8), color-stop(1.0, #AAAAAA));
    width: 33%;
    height: 100%;
}

#btn-gold
{
    float: left;
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0.0, #F8F8F8), color-stop(1.0, #AAAAAA));
    -webkit-border-top-right-radius: 6px;
    -webkit-border-bottom-right-radius: 6px;
    width: 33%;
    height: 100%;
}

When selected, the selected button should add this class to modify the background color:
.blue-selected
{
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0.0, #FFFFFF), color-stop(1.0, #6699CC));;
}

This is done using jQuery in the method that is called when the body loads:
$("#btn-bronze").click(function()
{

    console.log("bronze");
    $(this).addClass('blue-selected');
    $("#btn-silver").removeClass('blue-selected');
    $("#btn-gold").removeClass('blue-selected');
});

$("#btn-silver").click(function()
{
    console.log("silver");
    $("#btn-broze").removeClass('blue-selected');
    $(this).addClass('blue-selected');
    $("#btn-gold").removeClass('blue-selected');
});

$("#btn-gold").click(function()
{
    console.log("gold");
    $("#btn-broze").removeClass('blue-selected');
    $("#btn-silver").removeClass('blue-selected');
    $(this).addClass('blue-selected');
});

When I click one of these buttons, the console log message appears, but the background color remains the same. What am I doing wrong? Here is the fiddle.
Comment: I've made a simplified version of your jsfiddle to address your problem: http://jsfiddle.net/9qZZR/
Answer: I would fix a couple of things.
Use class instead of ID targeting. I left the IDs in, but you don't really need them now:
<button class="btn" id="btn-bronze" name="btn-bronze" type="button" class="blue-selected">Bronze</button>
<button class="btn" id="btn-silver" name="btn-silver" type="button">Silver</button>
<button class="btn" id="btn-gold" name="btn-gold" type="button">Gold</button>

Then I would use these styles. This way I could add more buttons without creating new styles:
 .btn
 {
   float: left;
   background: -webkit-gradient(linear, left top, left bottom, color-stop(0.0, #F8F8F8), color-stop(1.0, #AAAAAA));
   width: 33%;
   height: 100%;
}

.btn:first-child {
   -webkit-border-top-left-radius: 6px;
   -webkit-border-bottom-left-radius: 6px;
}

.btn:last-child {
   -webkit-border-top-right-radius: 6px;
   -webkit-border-bottom-right-radius: 6px;
}

.btn.blue-selected
{
   background: -webkit-gradient(linear, left top, left bottom, color-stop(0.0, #FFFFFF), color-stop(1.0, #6699CC));
}

Finally, I would simplify the hell out of the javascript:
$(".btn").click(function () {
    $(".btn").removeClass("blue-selected");
    $(this).addClass('blue-selected');
});

http://jsfiddle.net/4ZygH/1/
Comment: Wow, Thanks for this fix/simplification!
Answer: #btn-bronze has a higher specificity than .blue-selected, so its background takes precedence.
You can get around this by using !important, but that's probably not the best solution.
The most reliable would be if the parent element also has an ID, then you can select #parent-element>.blue-selected and get a higher specificity.
Answer: A ID selector have a more priority then an class selector. You could use important in your css code.

Button will not change color (HTML5)


Does the level of a gym's badge affect the gameplay?

Question: Since the last update you can now obtain a badge for a specific gym when you spin its photo disc. It is then possible to level it up by defending it, feeding the Pokemons from your team with berries or attacking it if another team is controlling it. Leveling the badges up apparently awards you with a new badge rarity, going from Bronze to Gold, as you can see from the picture below.

Does the rarity of a badge affect the gym it's linked to? For instance, can you get additional loots, or will your own Pokemon's motivation decrease more slowly?
Answer: Leveling the Gym badge does have an affect on the game play.  According to Niantic's post:

You can earn the opportunity to receive bonus items and increased rewards from Gyms by raising the level of your Gym Badge.

Having a higher Gym Badge level will yield more rewards and bonus items from Gyms.  At the moment, this appears to be the only thing that the Gym Badges do that I can find.
Comment: @Isuka definitely from the spinning disc as pointed out in the linked question in my answer. I don't think the coins are impacted in any way for the badge.  It looks like the coins are based [solely off time](https://www.primagames.com/games/pokemon-go/tips/pokemon-go-how-collect-coins) (1 hour grants 1 coin per pokemon in a gym up to 100 coins a day).  It also looks like the pokemon must be defeated before you can collect coins.
Comment: Interesting! What do you mean by "rewards" there, just to be sure? Do you get more coins for defending your gym, or does the rarity of the items you get for spinning the photo disc increases?
Answer: My observation is that:

a bronze gym badge grants you +1 bonus items
a silver gym badge grants you +2 bonus items
a gold gym badge grants you +3 bonus items

In addition, you get bonuses if if your team controls the gym:

If your team controls the gym and you do not have a gold gym badge, you get +1 bonus items.
If your team controls the gym and you do have a gold gym badge, then you get +2 bonus items (for a total of +5 bonus items, including the gold gym badge bonus).
Comment: And each bonus is multiplied by 5 on the ene of your 7 day streak.
Answer: In addition to receiving bonus items you also get more XP for spinning:
Enemy gym:

badgeless: 25 XP
bronze: 50 XP
silver: 75 XP
gold: 100 XP

Friendly gym:

badgeless: 31 XP
bronze: 63 XP
silver: 94 XP
gold: 125 XP
Answer: It also seems to add to your XP reward. I currently get 94 XP just for flipping my home stop (which is silver, halfway to gold, est. 16.000 badge XP).
Answer: My observation is gold gyms that hold exraids give me an advantage for catching Mewtwo.


Is the product of two stable asymmetric matrices also stable?

Question: Given two square asymmetric matrices $A$ and $B$ that are Hurwitz stable (with maximum eigenvalue less than one), is the product $AB$ also stable?
This is clearly true when $A$ and $B$ are symmetric, since the induced norm has the property that $||AB|| \leq ||A|| ||B||$ and $||A|| = \lambda_{\max}(A)$. However, because the maximum eigenvalue is not necessarily equal to the matrix norm in the asymmetric case, I am not sure if this still holds.
Answer: The answer is no. As a counterexample, consider
$$
A = \pmatrix{0&2\\0&0}, \quad B = \pmatrix{0&0\\2&0}.
$$
$A$ and $B$ each have $0$ as their only eigenvalue but $AB$ has eigenvalues $0,4$.
Comment: Thank you. Would it be true if only $A$ were symmetric and not $B$?
Comment: Nevermind, there is a counterexample with $A=[[0,0.75],[0.75,0]]$ and $B$ from your example


Read Excel file from Share point office 365 in c#

Question: I am trying to read excel file from office 365 link.In this link, I can read and write records. Can anyone help how to access/read data from online excel file and update the same file.
Answer: You could use graph api to read excel file stored in SharePoint online.
Sample endpoint:
<code>https://graph.microsoft.com/v1.0/sites/siteid/drives/driveid/items/itemid/workbook
</code>


How can I find servers for Primal Carnage?

Question: I just bought Primal Carnage on the current Steam sale; the original version, not its sequel, Primal Carnage: Extinction.
It's a multi-player game. There's no single player mode; you need to join a server. But I can't find any.

The list is empty. Refreshing doesn't help, nor changing the settings.
I've searched with Google for where can I find primal carnage servers -extinction and variations thereof, and dug up some old threads on the Steam forums, including one with a proposed solution: verify the game cache, which I did, but to no avail.
What else can I do to find the servers?
Version is 1.3.0; build ID is 132188.

Addendum 2018-05-03
Well, it may be a bug. After installing it on a new machine, a list of servers showed up and I'm able to play. Upon reloading it is empty occasionally, though.
Comment: @DanmakuGrazer why did you remove the [tag:networking] tag? This may very well turn out to be a networking issue; perhaps ports I need to open somewhere.
Comment: Tags are about the question, not the answers. Your question is about not seeing servers from the ingame browser, not specifically about networking.
Comment: @DanmakuGrazer fair enough.
Answer: After some quick searching, it seems that Primal Carnage: Extinction is a remake, not exactly a sequel, of the original which includes both multiplayer and new single player mode.
Going to the Primal Carnage forums shows that the last post in the 1.3 version of the original was 8/27/2016. Whereas the last post in the section for PC:E was 6/16/2017. This could mean there are simply no servers to join as nobody is online.
I would request a refund from steam assuming you have under 2 hours played. Or find out if there are other small active communities still playing the game.
Answer: I have 250 hours of Primal Carnage. I only play the night between 21h and 1h30 ( France), and there are like 10/20 players. And rarely but sometimes you have like 30/40 players at the beginning of the night.
The server browser is bugged, when you leave it for settings and comes back for searching a server, it bugs and it can't find any ( even with refreshing). So you have to leave the game and restart it, and go directly in server browser and never go back.
But sometimes too, at 1h30 of the night, all the servers are shutdown, even if players were playing in. And in this case, you have to wait +/- 30min when the server are up. It's maybe a maintenance idk.


Installing ubuntu partitions problem

Question: I'm an Ubuntu newbie and I'm using it for the first time. During the installation I chose install Ubuntu over Windows, thinking that this will keep the partitions and install Ubuntu on the partition where the Windows was installed (C:) and keep the other one (D:) with all the files on it. After I installed I couldn't find the D:\ partition. Was It formatted as well, and if yes is there some way to retrieve it? Please help I'm desperate, I had some really important files on that partition!
Comment: You can run GParted Partition Editor to view all your current disk drives/partitions. Linux/Ubuntu does not have these letters, but sda1, sda2, etc.
Comment: http://pastebin.com/ZQu8aADv
Comment: It seems you have Ubuntu installed on sda1 and there's only sda5 left out. And if you cannot see your files there, you should do nothing else with this disk before recovering all the data overwritten during installation process.
Comment: Please specify how do I recover the data. I will be very thankfull :)
Comment: Unfortunately I'm not experienced in this area, but it should be possible if you make sure that you don't do anything at all especially that involves writing data to disk (overwriting previous data) before such a data/partition recovery. Good luck.
Answer: I am a newbie also, so take this answer with a grain of salt.  Check your directory and see if you have a /Home directory.  This might be where you important files will be found.
Good luck.
Comment: This would not be the answer. The data is on a separate partition, and is not migrated/imported into Ubuntu in any way.s

Installing ubuntu partitions problem


Calculate angle $x$ in the figure

Question: For reference:

My progress:

\begin{align*}
& AH \perp FD \\
& \triangle AFD \text{ is isosceles}
\quad
\therefore \measuredangle BFA  = \measuredangle FDA = x \\
& AF = FD \\
& \measuredangle HBA = 180-135^\circ = 45^\circ
\quad
\therefore \triangle HBA \text{ is isosceles}
\end{align*}
I drew some auxiliary lines but it wasn't enough to reach the solution.
Comment: Answer: $18^o30'$
Comment: Is that an exact answer, I am getting $\cot^{-1}(3)$, which is somewhat close to $18.5^\circ$.
Comment: Would someone solve by geometry?
Answer: Build a parallelogram $ABDE$. Then $$\angle DEA = \angle ABD = 135^\circ = \angle DCA,$$ hence $ADEC$ is cyclic. Moreover, $\angle EAD = \angle BDA = x$, hence $$\angle CAE = \angle CAD - \angle EAD = 2x-x=x.$$ As a consequence, $CE=DE$ because the angles subtended by arcs $CE$, $DE$ of the red circle are equal.

Now, it is easy to calculate that angle $CBD$ equals $90^\circ + x$ and that the concave angle $CED$ equals $180^\circ + 2x$. Since $CE=DE$, it follows that $B$ lies on the circle with center $E$ and radius $CE=DE$. Hence $\angle DEB = 2\angle DCB = 90^\circ$. Since $DE=BE$, the right triangle $DEB$ is isosceles.
Let $F$ be the midpoint of $BE$. Let $G$ be the midpoint of $BD$ and $H$ be the midpoint of $BG$. Easy to see that triangles $GFB$ and $GFH$ are isosceles right triangles, hence $HF = HB = \frac 12BG = \frac 14 BD$, so $HD = BD - BH = 4HF - HF = 3HF$. This yields $\tan x = \frac{HF}{HD} = \frac 13$ so the answer is $$x = \arctan \frac 13.$$
Answer: I have a trigonometry solution. Looking at the form of the answer, I don't think there will exist a purely synthetic approach.
With some angle chasing, we get that
$$\angle ADC=45-2x$$
$$\angle ABC=45-x$$
Using law of sines on $\Delta ACD$, we get
$$\frac{AC}{\sin (45-2x)}=\frac{AD}{\sin 135}$$
Using law of sines on $\Delta ABD$, we get
$$\frac{AB}{\sin (x)}=\frac{AD}{\sin 135}$$
Combining these two equations gives
$$\frac{AC}{\sin (45-2x)}=\frac{AB}{\sin (x)}$$
$$\frac{AC}{AB}=\frac{\sin (45-2x)}{\sin (x)}$$
With simple trig definitions on right triangle $\Delta ABC$, we get that
$$\sin (45-x)=\frac{AC}{AB}$$
Hence,
$$\frac{\sin (45-2x)}{\sin (x)}=\sin (45-x)$$
Using angle sum/difference identities along with others, this simplifies to
$$\frac{\sqrt{2}}{2}(\cos (2x)-\sin (2x))=\frac{\sqrt{2}}{2}(\sin (x)\cos (x)-\sin^2 x)$$
$$\cos^2 (x)-\sin^2 (x)-2\sin (x)\cos (x)=\sin (x)\cos (x)-\sin^2 (x)$$
$$\cos^2 (x)=3\sin (x)\cos (x)$$
Note that if $\cos (x)=0$, then $x=\frac{\pi}{2}$. However, it is clear by the diagram that $x$ is acute (we can get even better bounds, but it is unnecessary).
Hence, we have $\cos (x)\neq 0\implies$
$$\cos (x)=3\sin (x)$$
$$x=\boxed{\cot^{-1} (3)}$$
Comment: I believe there must be a geometric solution drawing auxiliary lines... the exercise is from a geometry book
Answer:
Hints: You can easily see that:
$2x+\widehat {ADC}=45^o$
Now try to find another relation between these two angles using data the figures give.
Comment: would be FG or FC?
Comment: @petaarantes, FC is correct . I corrected it.
Comment: @sirous..sorry  i sorry, i couldn't find this relation
Answer: Once again, Pythagoras theorem does the job.

Say, $BC = a, AC = b$. Drop a perp from $B$ to $AD$. Notice that right triangles $\triangle ABC \cong \triangle ABH$, given $\angle ABC = \angle BAH = 45^\circ - x$ and $AB~$ is hypotenuse to both triangles.
So, $AH = BC = a, BH = AC = b$
Similarly notice that $\triangle DBE \cong \triangle BDH$. So, $DE = BH = b, DH = BE$ but $BE = CF = DF = a + b$
That leads to $DF = a + b, AF = a + 2b, AD = 2a + b$
Applying Pythagoras,
$(a+b)^2 + (a+2b)^2 = (2a+b)^2 \implies (a + b) (a-2b) = 0$
So we get $a = 2b$ and that shows $\triangle ADF$ is $3:4:5$ triangle.
Hence, $2x \approx 37^\circ$
Comment: excellent...great..thansk

Calculate angle $x$ in the figure


Changing multi select bind key in QGraphicsScene

Question: I'm subclassing QGraphicsScene in PyQT and want to use Shift key (modifier) for multi-select items instead of control key.
I can do so by subclassing it and making my own mousePressedEvent, but then when I do that, the graphicsItem in the scene acting weird when I start dragging them.
All I need is to change the control key to shift key for multi select. I would appreciate if anyone could help.
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class GraphicsScene(QGraphicsScene):
    def __init__(self, parent=None, ns=""):
        super(GraphicsScene, self).__init__(parent)
        self.parent = parent
        self.prevItem = []
        self.ns = ns
        self.setBackgroundBrush(QBrush(QColor(50,50,50) , Qt.SolidPattern))

    def mouseReleaseEvent(self, event):
        if event.button() == 2: #Right mouse click
            #Set previous selections selected
            for item in self.prevItem:
                item.setSelected(1)

            item = self.itemAt(event.lastScenePos ().x(), event.lastScenePos ().y())
            if item:
                item.setSelected(1)

        if event.button() == 1: # Left mouse click
            #Get selected item
            items = self.selectedItems()

            #Shift click
            if event.modifiers() & Qt.ShiftModifier:
                #Set previous items selected
                for item in self.prevItem:
                    item.setSelected(1)

                for item in items:
                    self.prevItem.append(item)

                item = self.itemAt(event.scenePos ().x(), event.scenePos ().y())
                if item == None:
                    self.clearSelection()

            else:
                self.prevItem = []
                for item in items:
                    self.prevItem.append(item)

        super(GraphicsScene, self).mouseReleaseEvent(event)

    def mousePressEvent(self, event):
        if event.modifiers() & Qt.ShiftModifier:
            item = self.itemAt(event.scenePos ().x(), event.scenePos ().y())
            if item:
                item.setSelected(1)

        super(GraphicsScene, self).mousePressEvent(event)

class MainClass(QMainWindow):
    def __init__(self, parent=None):
        super(QMainWindow, self).__init__(parent)

        self.setGeometry(50,50,400,600)

        widget = QWidget()
        self.setCentralWidget(widget)
        layout = QGridLayout()
        layout.setMargin(3)

        widget.setLayout(layout)

        view = QGraphicsView()
        view.setMouseTracking(1)
        view.setDragMode(QGraphicsView.RubberBandDrag)
        view.setRenderHint(QPainter.Antialiasing)
        view.setRenderHint(QPainter.TextAntialiasing)
        view.setTransformationAnchor(QGraphicsView.AnchorUnderMouse)
        view.setAlignment(Qt.AlignJustify)

        scene = GraphicsScene(self)
        scene.setSceneRect(0,0, 300, 500)

        view.setScene(scene)
        layout.addWidget(view)

        elipseOne = QGraphicsEllipseItem (30,30,30,30, parent=None, scene=scene)
        elipseOne.setFlags(QGraphicsItem.ItemIsSelectable | QGraphicsItem.ItemIsFocusable | QGraphicsItem.ItemIsMovable)

        elipseTwo = QGraphicsEllipseItem (60,60,30,30, parent=None, scene=scene)
        elipseTwo.setFlags(QGraphicsItem.ItemIsSelectable | QGraphicsItem.ItemIsFocusable | QGraphicsItem.ItemIsMovable)

win = MainClass()
win.show()

Comment: here is a possible hack: http://stackoverflow.com/a/19162605/3565696
Answer: Modified your mousePress and mouseRelease events hope it's helpful
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys
from collections import deque

class GraphicsScene(QGraphicsScene):
    def __init__(self, parent=None, ns=""):
        super(GraphicsScene, self).__init__(parent)
        self.parent = parent
        self._selectedItemVec = deque()
        self.ns = ns
        self.setBackgroundBrush(QBrush(QColor(50,50,50) , Qt.SolidPattern))

    def mouseReleaseEvent(self, event):
        item = self.itemAt(event.scenePos ().x(), event.scenePos ().y())
        if item:
            item.setSelected(1)
        else:
            if len(self._selectedItemVec):
                self._selectedItemVec.popleft()
                return QGraphicsScene.mouseReleaseEvent(self, event)
        if event.modifiers() & Qt.ShiftModifier:
            for item in self._selectedItemVec:
                item.setSelected(1)
        else:
            self._selectedItemVec.popleft()

    def mousePressEvent(self, event):

        item = self.itemAt(event.scenePos ().x(), event.scenePos ().y())
        if item:
            item.setSelected(1)
            self._selectedItemVec.append(item)
        else:
            return QGraphicsScene.mousePressEvent(self, event)

class MainClass(QMainWindow):
    def __init__(self, parent=None):
        super(QMainWindow, self).__init__(parent)

        self.setGeometry(50,50,400,600)

        widget = QWidget()
        self.setCentralWidget(widget)
        layout = QGridLayout()
        layout.setMargin(3)

        widget.setLayout(layout)

        view = QGraphicsView()
        view.setMouseTracking(1)
        view.setDragMode(QGraphicsView.RubberBandDrag)
        view.setRenderHint(QPainter.Antialiasing)
        view.setRenderHint(QPainter.TextAntialiasing)
        view.setTransformationAnchor(QGraphicsView.AnchorUnderMouse)
        view.setAlignment(Qt.AlignJustify)

        scene = GraphicsScene(self)
        scene.setSceneRect(0,0, 300, 500)

        view.setScene(scene)
        layout.addWidget(view)

        elipseOne = QGraphicsEllipseItem (30,30,30,30, parent=None, scene=scene)
        elipseOne.setFlags(QGraphicsItem.ItemIsSelectable | QGraphicsItem.ItemIsFocusable | QGraphicsItem.ItemIsMovable)

        elipseTwo = QGraphicsEllipseItem (60,60,30,30, parent=None, scene=scene)
        elipseTwo.setFlags(QGraphicsItem.ItemIsSelectable | QGraphicsItem.ItemIsFocusable | QGraphicsItem.ItemIsMovable)
if __name__ == '__main__':

    app = QApplication(sys.argv)
    win = MainClass()
    win.show()
    sys.exit(app.exec_())


ssh permission denied in terminal but not inNautilus

Question: I have two Ubuntu machines on the same network. I installed openssh-server and client. When I try to connect through the terminal I get the following message:
Permission denied, please try again

Then after attempting to type my password in get the last message:
Permission denied (publickey,password)

However I can ssh to the computer through Nautilus, with no problem.
Comment: Can you share the ssh command line you are using? Do you have a .ssh/config file on the guest machine?
Answer: Logging in from the terminal by default tries to log into the remote machine with your username on the local machine. In Nautilus you have to explicitly type in your username on the remote machine. I am guessing that your local and remote usernames do not match.
Use ssh user@server to log in with a different username.


Trouble Using Swift NSDate "timeIntervalSinceNow"

Question: I've searched around and am flummoxed by this riddle.
In Swift, Xcode 6.2, these lines work:
let day_seconds = 86400
let one_day_from_now = NSDate(timeIntervalSinceNow:86400)

But the following returns an error:
let day_seconds = 86400
let one_day_from_now = NSDate(timeIntervalSinceNow:day_seconds)

Console output:

"Playground execution failed: /var/folders/4n/88gryr0j2pn318sw_g_mgkgh0000gn/T/lldb/10688/playground625.swift:24:30: error: extra argument 'timeIntervalSinceNow' in call
  let one_day_from_now = NSDate(timeIntervalSinceNow:day_seconds)"

What's going on here? Why the NSDate trickiness?
Comment: Unrelated to your problem, but don't assume that one day has 86400 seconds (think of daylight saving time transitions). Better use NSCalendar methods for all calendrical calculations.
Comment: It isn't NSDate trickiness. It is Swift numerics trickiness... :(
Answer: It's because timeIntervalSinceNow expect NSTimeInterval which is Double.
If you do:
let day_seconds = 86400

day_second is Int  type which is not what the method expect.
However when you type the number itself:
let one_day_from_now = NSDate(timeIntervalSinceNow:86400)

compiler implicit that you are passing Double, because it's what the method expect, which is ok.
The solution cancould be using
NSTimeInterval(day_seconds) or Double(day_seconds) which is the same or when you declare constant make sure it's double, for example:
let day_seconds = 86400.0

or
let day_seconds: Double = 86400

or
let day_seconds: NSTimeInterval = 86400

Comment: Verbose but correct. :)
Comment: Thank you, Greg, for the very clear explanation. I now have an understanding of Swift numerics trickiness. I apologize for the duplicate question, Matt!


My List(OF Strings) are being saved as system.string (Empty)

Question: I'm trying to delete a selected row, then save the rest into a file. However, when I save it, it totally empties the file.
    Console.Write("Please eneter the first name of the student you wish to search for: ")
    searchfname = Console.ReadLine
    searchfname = StrConv(searchfname, VbStrConv.ProperCase)
    Console.Write("Please enter the second name of the student you wish to search for: ")
    searchsname = Console.ReadLine
    searchsname = StrConv(searchsname, VbStrConv.ProperCase)
    Dim foundItem() As String = Nothing
    Dim foundline As String = Nothing
    Dim fnsearch As String = String.Join(searchfname, searchsname)
    Dim lines As New List(Of String)(File.ReadAllLines("F:\Computing\Spelling Bee\stdnt&staffdtls.csv"))
    For Each line As String In lines
        If searchfname = item(3) And searchsname = item(4) Then
            Console.WriteLine(line)
            Console.WriteLine()
            Console.WriteLine("Are you sure you wish to delete this record? (y/n)")
        End If
        Dim answer As String
        answer = Console.ReadLine
        If answer = "y" Or answer = "Y" Then
            Console.Clear()
            lines.Remove(line)
            Using sw As New StreamWriter("F:\Computing\Spelling Bee\stdnt&staffdtls.csv")
                sw.WriteLine(lines.ToString)
            End Using
        ElseIf answer = "n" Or answer = "N" Then
            staffmenu()
        End If
    Next

Comment: You are not writing the file correctly.  Use File.WriteAllLines() instead.
Comment: you got several very good answers here - and on 7 of previous questions.  You should start accepting answers when they help.
Comment: nothing to do with your question but is your search for JoeBlogs or Joe Blogs.... If the latter then change your join so that it includes a space between searchfname and searchsname
Answer: The method List(Of T).ToString does not produce a value that includes the elements of the collection.  Instead it will just return the type name.
The API you are looking for is File.WriteAllLines.  Using this instead of StreamWriter and the Using block
File.WriteAllLines("F:\Computing\Spelling Bee\stdnt&staffdtls.csv", lines)

Answer: Look at this line in your code:
sw.WriteLine(lines.ToString)

Extract the lines.ToString expression from that statement. The result of that expression is "System.String". You are telling your stream writer to write the text "System.String" to the file.
To fix it, you need something more like this:
Using sw As New StreamWriter("F:\Computing\Spelling Bee\stdnt&staffdtls.csv")
    For Each line As String In lines
        sw.WriteLine(line)
    Next line
End Using

Answer: I can see that this issue can be resolved from the given answers and comment, but I would like to add an alternative to use Join function in writing to a file. Try like this may be of help:
Using sw As New StreamWriter(.....)
   sw.WriteLine(Join(lines.ToArray(), Environment.NewLine))
End Using

Since using VB.Net, this is a vb.net specific solution can not be used in C#. For C#, use string.join instead.
Hope it helps too!


Count the number of transaction based on day in oracle

Question: I have a table which maintain the transaction history for various study, want to fetch the study group by study id (which is TIM) for last week, last month and last 6 month
SELECT CREATED_DATE,TIMS,COUNT(TIMS) FROM STUDY_HISTORY
WHERE CREATED_DATE >= DATE'2023-03-06'
GROUP BY CREATED_DATE,TIMS
ORDER BY CREATED_DATE

Above query is not adding up properly and also dont know how to retrieve it for last month and 6 month.
Comment: **Hint** : `systimestamp - interval '6' month`
Comment: Do you mean, what I can observe from the image that it should show, e.g. 247012 should show 2 for 06-03-2023 and hence forth ?
Answer: Your query can't work; if you're grouping by date column, you get ... well, what you got. Try conditional aggregation:
select
  sum(case when created_date >= add_months(sysdate, -6) then 1 else 0 end) last_6_months,
  sum(case when created_date >= add_months(sysdate, -1) then 1 else 0 end) last_month,
  sum(case when created_date >= sysdate - 7             then 1 else 0 end) last_week
from study_history

Comment: Thank you this should be included in my query ?
Comment: No, this *is* your "new" query.


Stereoscopic 3D app development

Question: I want to create an application to visualize image pairs in stereoscopic 3D. I want it to have a cursor that can move left and right, but also in and out. I think the way to achieve this is to draw a cursor on top of each image and then draw the images on screen (which would be a 3D capable screen).
How do I create such an application?
The experience I have is console programming in C, C++, Python. And I once used GTK+ to create a windowed app.
I've searched around and my problem is that I don't know where to start learning.
More details:
This app is meant to run on windows (although it would be nice if I could made multi-platform)
Answer: This is a very broad question. The basic way to do this is to generate 2 frames - one for each eye. You can do this using any modern 3D API from OpenGL to DirectX to Vulkan, Metal, or DX12.
You'll need to understand things like interocular distance, depth cues, and 3D compositing.
You'll also need some way to allow the user to move the curser in and out, so you'll want to read up on various user interface, visual interface, and user experience (UI, VI, and UX, respectively) techniques.

Stereoscopic 3D app development


Consider set $\mathbb{Z}[\sqrt{-5}] = \{a+b\sqrt{5}i : a,b \in \mathbb{Z} \}$ show that it is a ring

Question: Consider set $\mathbb{Z}[\sqrt{-5}] = \{a+b\sqrt{5}i : a,b \in \mathbb{Z} \}$.
My task is to show some features listed below:

Show that $\mathbb{Z}[\sqrt{-5}]$ is a ring.

I would like to show that $\mathbb{Z}[\sqrt{-5}]$ is a subring of $\mathbb{C}$.
Let $z,w \in \mathbb{Z}[\sqrt{-5}]$ and $z = a + b\sqrt{5}i, w = c+d\sqrt{5}i$, where $a,b,c,d \in \mathbb{Z}$.
It is sufficient to show that
$z+w, -z, zw \in \mathbb{Z}[\sqrt{-5}]$
$z+w = a+b\sqrt{5}i + c+d\sqrt{5}i = (a+c) + (b+d)\sqrt{5}i \in \mathbb{Z}[\sqrt{-5}]$
$-z = -(a+b\sqrt{5}i) = (-a) + (-b)\sqrt{5}i \in \mathbb{Z}[\sqrt{-5}]$
$zw = (a+b\sqrt{5}i)(c+d\sqrt{5}i) = (ac - 5bd) + (ad+bd)\sqrt{5}i \in \mathbb{Z}[\sqrt{-5}]$
Hence $\mathbb{Z}[\sqrt{-5}]$ as a subring of ring $\mathbb{C}$ then it is also a ring.

Let $z = 2+\sqrt{5}i$. Show that $z$ is irreducible.

I know the definition of being irreducible, it has to be non invertible and the following has to  be true:
$\forall x,y \in \mathbb{Z}[\sqrt{-5}]$ if $ z = xy \Rightarrow x$ or $y$ has to be invertible.
Hint is to use that fact that norm $\lvert z\rvert = 3$. Hence all divisiors of $z$ have norm lower or equal than $3$.
I do not know how to use this hint.

Show that $z \lvert 3\cdot 3$ and $z$ does not divide $3$.

For the first one I was thinking about
$3 \cdot 3 = 9 = (2+\sqrt{5}i)(2-\sqrt{5}i) \Rightarrow z \lvert 3\cdot 3$
For the second one I was thinking about dividing $3$ by $z$ in $\mathbb{C}$.
Then $$\frac{3}{z} = \frac{3}{2+\sqrt{5}i} = \frac{2}{3} + (\frac{-1}{3})\sqrt{5}i$$ which is not an element of $\mathbb{Z}[\sqrt{-5}]$.
Is this point correct?

Show that $z$ is irreducible element, but not a prime element.

This can be obtained from points 2. and 3.
Since $z\lvert 3\cdot 3$, but $z$ does not divide $3$.
Comment: 3. is not correct. For 2., you can compare with [this duplicate](https://math.stackexchange.com/questions/94999/irreducible-in-mathbbz-sqrt-5) for a proof. Everything has been proved at MSE about this question.
Comment: Yes,  we indeed have have $(2+\sqrt{-5})(2-\sqrt{5})=3\cdot 3$.
Comment: janusz, everything is well explained here, e.g., at [this post](https://math.stackexchange.com/questions/2256878/showing-that-2-sqrt-5-is-not-divisible-by-3-in-mathbbz-sqrt-5?rq=1).  Did you see this?
Comment: But is the first part of 3 at least correct?
Comment: I have a question about showing that $z$ does not divide $3$. Is it correct to assume that if $z$ divide $3$ then $zw = 3$ for some $w$ in our ring. But the norm argument gives us that $\lvert w \rvert = 1$ hence $zw \neq 3$?
Comment: Thank you sir, now everything is clear.
Answer: If, for some $x, y \in \mathbb{Z}(\sqrt{-5})$, we have $$ z = 2 + \sqrt{-5} \iota = xy, $$
then we must also have
$$3 = \lvert z \rvert = \lvert x \rvert \, \lvert y \rvert,   $$
and since $\lvert x \rvert, \lvert y \rvert \in \mathbb{N}$, therefore we must have
$$
\lvert x \rvert, \lvert y \rvert \in \{ 1, 3 \}. $$
Thus we have the following two cases:

$\lvert x \rvert = 1$, $\lvert y \rvert = 3$
$\lvert x \rvert = 3$, $\lvert y \rvert = 1$

If $x = a + b \iota \sqrt{5}$ is such that
$$ \lvert x \rvert = \sqrt{ a^2 + 5b^2 } = 1, $$
where $a, b \in \mathbb{Z}$, then we must have
$$
a^2 + 5 b^2 = 1,
$$
and so $b = 0$ and $a = \pm 1$, which gives
$$
x = \pm 1,
$$
and then
$$
z = 1z \ \mbox{ or } \ z = (-1)(-z).
$$
And, similarly, for the case when $\lvert x \rvert = 3$ and $\lvert y \rvert = 1$.


hive join select very slow

Question: hi,i have Two tables: user_info, ip_location, one is 50,000 and the other is 100,000.
now Need to use the ip of the user table to check the attribution,Convert ip to int and compare interval with ip_location。
my hive version is 3.0.0,this version no index。
ip_location:
enter image description here
This operation is very fast in pg:
set search_path=res;
select * from(
select ip,
(split_part(ip,'.',1)::bigint*256*256*256
+split_part(ip,'.',2)::bigint*256*256
+split_part(ip,'.',3)::bigint*256
+split_part(ip,'.',4)::bigint)::int8 as ipvalue
from user_info) t1
left join ip_location t2 on
ipv4_val_begin=(select max(ipv4_val_begin) from ip_location where ipv4_val_begin <= ipvalue);

But I did not find an alternative to this syntax on hive:
select ip,
t2.location_country
cast(split(ip,"\\.")[0] as bigint)*256*256*256
+cast(split(ip,"\\.")[0] as bigint)*256*256
+cast(split(ip,"\\.")[0] as bigint)*256
+cast(split(ip,"\\.")[0] as bigint) as ipvalue
from source.v_dm_vip_user t1
left join res.ip_location t2 on
ipv4_val_begin=(select max(ipv4_val_begin) from res.ip_location where ipv4_val_begin <= ipvalue);

error:
enter image description here
Change to the following sql, you can query successfully, but it is very slow, it takes 1 day:
select ip,
t2.location_country
cast(split(ip,"\\.")[0] as bigint)*256*256*256
+cast(split(ip,"\\.")[0] as bigint)*256*256
+cast(split(ip,"\\.")[0] as bigint)*256
+cast(split(ip,"\\.")[0] as bigint) as ipvalue
from source.v_dm_vip_user t1
left join res.ip_location t2 on
cast(split(ip,"\\.")[0] as bigint)*256*256*256
+cast(split(ip,"\\.")[0] as bigint)*256*256
+cast(split(ip,"\\.")[0] as bigint)*256
+cast(split(ip,"\\.")[0] as bigint) > ipv4_val_begin
and
cast(split(ip,"\\.")[0] as bigint)*256*256*256
+cast(split(ip,"\\.")[0] as bigint)*256*256
+cast(split(ip,"\\.")[0] as bigint)*256
+cast(split(ip,"\\.")[0] as bigint) < ipv4_val_end;

Is there a better and faster sql? I tried a lot but it didn't work, thanks.
Comment: Does hive version you have support `with` clause ?
Comment: The ```with``` clause can't increase the speed,It still takes about a day,postgres only took 20 sec
Answer: I tried the view and row group index, but it can't speed up much. I would like to ask how to use hive to speed up the IP address range like this, and the speed of hive on spark is also slow.

hive join select very slow


Visio VBA Script

Question: I'm trying to figure out how to go through a 50 page Visio Doc and take out the text within all of a particular shape. They are all "subprocess" shapes. I'm not sure what the best way to go about it is, and I attempted to just go through each shape on every page and check if it's name matches to "Subprocess." + iterated number. It would basically iterate through like 200 shape names for each shape: crazy and won't work. Not sure how to do this as they all have unique names, but I do know that each name starts with "Subprocess."
Code so far:
Public Sub FindOffPageShapes()
Dim shp As Visio.Shape
Dim pagShape As Visio.Shape
Dim myInt As Integer
    Set pagShape = Visio.ActivePage.PageSheet
    For Each shp In Visio.ActivePage.Shapes
        While shp.Name <> "Subprocess." & CStr(myInt) Do
            Do myInt = myInt + 1
        If shp.TextFrame.Characters.Name = "Subprocess." & CStr(myInt) Then
            shp.Text = ""
        End If
Next shp
End Sub

Thanks!
Answer: You can just use the Like keyword to test whether a string matches the 'Subprocess' pattern.  See below.
Option Compare Text
Public Sub FindOffPageShapes()
Dim shp As Visio.Shape
Dim pagShape As Visio.Shape
Dim myInt As Integer
    Set pagShape = Visio.ActivePage.PageSheet
    For Each shp In Visio.ActivePage.Shapes
        If shp.Name like "Subprocess*" Then
            shp.Text = ""
        End If
    Next shp
End Sub

Comment: Paul, if this solution works for you this site is set up where you'd accept my answer, which is thanks enough.

Visio VBA Script


Aptik Doesn't Appear in Search Results

Question: I just performed a fresh install of Kubuntu 18.04, and installed Aptik from the ppa shown in the output of apt policy aptik. The thing is that Aptik is not found when searching using the application launcher. Just nothing comes up. Given that the Aptik GUI is dependent on this mechanism, how can I resolve this or get the Aptik GUI back?
apt policy aptik Shows:

sarah@ConvergentRefuge:~$ apt policy aptik
  aptik:
    Installed: 18.5.2-0~201805120407~ubuntu18.04.1
    Candidate: 18.5.2-0~201805120407~ubuntu18.04.1
    Version table:
   *** 18.5.2-0~201805120407~ubuntu18.04.1 500
          500 http://ppa.launchpad.net/teejee2008/ppa/ubuntu bionic/main amd64 Packages
          100 /var/lib/dpkg/status
Comment: Does "Install the `aptik-gtk` package and type aptik-gtk in a terminal" from https://github.com/teejee2008/aptik/issues/6#issuecomment-386788217
Comment: @DKBose Nice, that worked. If you post it as the answer, I'll accept it and upvote it.
Answer: According to the developer's comment on the GitHub issues page for Aptik, installing the aptik-gtk package will help resolve the issue.
Comment: This. As of this release, `aptik` is a terminal app, and `aptik-gtk` is the GUI. It confused me too.

Aptik Doesn't Appear in Search Results


Mob in distance 1.15.2

Question: Im using this command:
/execute if entity @e[type=minecraft:zombie,distance=100] run say HEY!
ignore the say part, but I want it to detect a zombie in a radius from the command block, logically this should work right or am I just being an idiot?
Comment: Possible duplicate of [What is the difference between the single dot, double dot and triple dot operators in Minecraft commands](https://gaming.stackexchange.com/questions/360777/what-is-the-difference-between-the-single-dot-double-dot-and-triple-dot-operato)
Comment: There's probably a better duplicate target, but I can't find it right now, and the duplicate question I suggested does explain why you need the `..` in your `distance` selector.
Answer: As of 1.13, the distance you specify is no longer considered a range from 0 to the number you wrote. Instead, the command will only execute if the distance between the entity and the command block is exactly n number of blocks. So in your command, you are testing for a zombie that is exactly at the 100 block mark from the command block.
You can specify a range by using two dots (..) before or after a number. Here is the command you should use:
<code>/execute if entity @e[type=minecraft:zombie,distance=..100] run say HEY!
</code>
in this example, the two dots mean that the distance has to be lower or equal to 100. If you were to write the dots after the number (100..), that means the value has to be greater or equal to 100.

Mob in distance 1.15.2


How to use unique symbol as object property in TypeScript?

Question: I need to use unique symbol in TypeScript in order to be able to dynamically compose an object literal. If I use regular symbol, I get this error:

A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type.

However, I'm not sure how to use unique symbol as an object property.
const bar: unique symbol = Symbol("bar"); // This is fine

interface MyInterface {
    readonly id: unique symbol;
}

const foo: MyInterface = {
    id: Symbol("id"),
};

// Error: Type 'symbol' is not assignable to type 'unique symbol'

What am I doing wrong?
Comment: It's either me, or handling symbols in TypeScript is VERY lacking. I encounter new problems all the time.
Comment: Perhaps you should show how you are creating the new object using the symbol as a key.
Comment: @kelsny I have a quite complex use case, I will consider creating a question for it.
Comment: Seems like your actual problem is whatever's causing the "A computed property name in an interface" error, but you haven't shown it so I'm not sure. Could you provide a [mre] of whatever is doing that so we can suggest alternatives?
Answer: The answer for this behavior lies in the documentation (as most things are :p):

To enable treating symbols as unique literals a special type unique symbol is available. unique symbol is a subtype of symbol, and are produced only from calling Symbol() or Symbol.for(), or from explicit type annotations. This type is only allowed on const declarations and readonly static properties, and in order to reference a specific unique symbol, you'll have to use the typeof operator.

Unfortunately, it's not possible to achieve what you are looking for. Trying to extract the symbol into its own const declaration yields a different error:
const id: unique symbol = Symbol("id");

const foo: MyInterface = {
    id,
//  ~~
// Type 'typeof id' is not assignable to type 'typeof foo.id'.(2322)
};

I guess it's because the unique symbol type of id is unique, it isn't assignable to the unique symbol type that MyInterface expects... It appears that this is the intended behavior of unique symbols. See ms/TS#23388, an exact copy of your question.
Playground

Of course, I could be proven wrong and maybe there is a way you could get this to work.
Comment: I'm trying to just have an interface of specific symbols mapped to specific types. Couldn't do it for `Map`, because `Map` is very limited in TypeScript. Can't do it for plain objects neither?
Comment: It appears to be the case. However, you could always ignore the compiler and abstract away the lie you tell it: https://tsplay.dev/w1Q42w
Comment: Sure, but I wanted to do this in order to achieve type safety of the value anyway, so it's of no use to cheat here.
Answer: To use unique symbol as a property, you need
const bar: unique symbol = Symbol("bar"); // This is fine

interface MyInterface {
  readonly [bar]: 123;
}

const foo: MyInterface = {
  [bar]: 123
}

It has no difference of string literals
interface MyInterface {
  readonly "bar": 123;
}

const foo: MyInterface = {
  "bar": 123
}


iSCSI: ubuntu tgt with Windows Initiator

Question: A Question from my iSCSI-Lab: I'm trying to configure Windows systems (10 + Server 2019) to connect to an Ubuntu iSCSI target, using tgt on Ubuntu and the Windows built-in initiator. Windows initiators connect happily to Windows, FreeNAS and AsusTor targets. Ubuntu initiators connect happily to the Ubuntu target. My only issue is with Windows initiators and Ubuntu / tgt as the target.
On Windows "Quick Connect" finds the target, but the GUI says "The target name is not found or is marked as hidden from login." and Event log says "iSCSIPrt / ID 10 / Login request failed".
On Ubuntu tgt doesn't seem to log much, only service starts and such.
I've tried no authentication, IQN, IP and (mutual) CHAP for authentication, no luck...
Does anybody know how to fix this? Or is there a better way?
Answer: Problem solved: Ubuntu does not conform to RFC 3722 "String Profile for iSCSI Names" which states "In addition, any upper-case characters input via a user interface MUST be mapped to their lower-case equivalents."
My host is named UV1, so I set up an IQN like "iqn....:UV1-test" but the Windows initiator connects to "iqn....:uvi1-test" which is met with a "Target not found" ...


How to edit the assets in the jar version file in minecraft?

Question: I want to edit the assets, like the textures of the blocks, in the Minecraft .jar file. For example, I want to change the textures of bottles without using a texture pack, and directly change what Minecraft thinks the default is.
The process I've tried so far is:

turn version.jar, in this case 1.10.jar into a .zip file
unzip it into a folder, now just a folder called 1.10
navigate to 1.10/assets/minecraft/textures/items/bottle.png
edit that texture
compress the folder back into a .zip file
change it to a .jar file
replace the original version.jar with mine

But when I try to launch it, Minecraft refuses to launch it. Why, and how can I edit Minecraft correctly?
Comment: .jar files are signed and made executable through a complicated process, they're not just renamed .zip files. You could try replacing the file without unpacking and repacking by using the command line version of 7zip, I did that to an Android app once and it worked. In the worst case you would have to decompile and recompile the entire game. But the more important question is: **WHY** do you not want to use resource packs?
Comment: Which resources? And no, having a resource pack for one file is much more normal than what you're attempting. I have a resource pack that just replaces one texture, it's 2728 Bytes big. I also have one that changes only redstone dust in a certain configuration, it's 4929 Bytes big. I made two resource packs myself recently that only disable a bunch of subtitles, they are 27109 and 27265 Bytes big. There's not really any downside to this, except if you have hundreds of those tiny resource packs that clutter the resource pack menu in the game.
Comment: Loot tables are part of data packs as well.
Comment: @FabianRöling because I think it would be silly to have a whole resourse pack just to change the look of one block. Also, there are other assets I might want to change that a resource pack can't.
Comment: @FabianRöling the loot tables. I think name tags and lily pads are junk and water bottles and leather are treasure.
Answer: You will need to delete the folder called META-INF otherwise Minecraft will detect that its textures have have been modified and crash.


Create a customized slave of postgresql

Question: I need to create a slave for BI purposes and I need to modify some tables (e.g., remove all passwords or sensitive data). My database is PostgreSQL. I wonder if I can do it in database layer or I should do it programmatically by writing a code to do the replication.
Answer: You could use logical replication and have replica enabled triggers (that fire ony on replication) that modify the data when they are applied:
<code>ALTER TABLE mytab DISABLE TRIGGER mytrig;
ALTER TABLE mytab ENABLE REPLICA TRIGGER mytrig;
</code>
You have to make sure that no replication conflicts can arise from these modifications. For example, never modify a key column.
Replication conflicts would stop replication and break your system.
The traditional way to solve this problem is to use an ETL process. That way you can have a different data model on the target database and for example pre-aggregate data so that the data warehouse doesn't grow too big and has a data model optimized for analytical queries.

Create a customized slave of postgresql


Image migration script - Allowed memory size of 134217728 bytes exhausted

Question: I am trying to import around 130k images via url. I thought it would be convenient to write a cli artisan command.
I am using laravel and "Spatie/MediaLibrary".
This is my script:
public function handle()
    {
       Article::where('index_block_position',0)->each(function($article){
            if($article->featured_image != ''){
                try{
                    $featuredImage = $this->mediaLibrary->addMediaFromUrl($article, 'http://myoldwebsite.com' . $article->featured_image, 'featured_image');
                    $libraryImage = $this->mediaLibrary->addMediaFromUrl(MediaLibrary::first(), 'http://myoldwebsite.com' . $article->featured_image);
                    $article->index_block_position = 1;
                    $article->save();
                    $this->info("Article {$article->id} image: {$featuredImage->id} - Library image: {$libraryImage->id} - added");
                    Log::useDailyFiles(storage_path().'/logs/featured-image-migration.log');
                    Log::info("Article {$article->id} image: {$featuredImage->id} - Library image: {$libraryImage->id} - added");
                }catch (\Exception $e){
                    $this->info("image: {$article->featured_image} - exception: {$e->getMessage()}");
                    Log::useDailyFiles(storage_path().'/logs/featured-image-migration.log');
                    Log::info($e->getMessage());
                }
            }
        });
        $this->info('All done!');
    }

Unfortunately, after 10 or so images added I get the following error:
Symfony\Component\Debug\Exception\FatalErrorException: Allowed memory size of 134217728 bytes exhausted (tried to allocate 24576 bytes)

I am not sure how i can make this work because i have 130k images to import and the memory limit of 128M is already exhausted after 10 images...
I would appreciate suggestions.
Answer: If you are using Laravel, consider breaking the upload down into jobs which can then be queued and processed over time.
https://laravel.com/docs/5.4/queues
You may also run into file upload limits set in your /etc/php/x.x/fpm/php.ini. More specifically these settings:

upload_max_filesize
post_max_size


Want to insert a logo as the middle menu item in Wordpress theme

Question: EDIT: I adjusted my parameters to insert the logo directly into the menu, instead of padding a specific menu item. The padding method can easily drive a centered menu off-center. This insertion method should resolve that issue.
I'm working on a theme, and want to create a menu split by a logo. I realize I could just create two menus, but I want this to be as streamlined for the user as possible. I've already been able to get the number of items and target the menu item I want, but I'm not sure how to use my functions.php file to add the class "pad-item" to the
.
Here is what I have to find and target the specified item. All it's returning, though, is an index number of top level items.
$locations = get_nav_menu_locations();
$menu = wp_get_nav_menu_object($locations['primary']);
$items = wp_get_nav_menu_items($menu->term_id);
$top_level = 0;
foreach ($items as $val) {
    if ($val->menu_item_parent === '0') {
        $top_level++;
    }
}
$index = round($top_level / 2) - 1;
return $index;

Any help would be greatly appreciated. Thanks.
Answer: I was able to figure out the issue, and I wanted to post my solution in case someone else was looking for the same answer.
function main( $items, $args ) {

    // Checks to see if the menu passed in is the primary one, and creates the logo item for it
    if ( $args->theme_location == 'primary' ) {
        $logo_item = '
' . get_logo() . '
';
    }

    //Gets the location of the menu element I want to insert the logo before
    $index = round( count_top_lvl_items() / 2 ) + 1;
    //Gets the menu item I want to insert the logo before
    $menu_item = get_menu_item( $index );
    $insert_before = '
ID;

    $menu_update = substr_replace( $items, $logo_item, strpos( $items, $insert_before ), 0 );

    return $new_menu;
}

//Counts the number of top level items in the menu
function count_top_lvl_items() {
    $items = get_menu_items();
    $counter = 0;
    foreach ( $items as $val ) {
        if ( $val->menu_item_parent === '0' ) {
            $counter++;
        {
    return $counter;
}

//Returns the menu item to insert the logo before
function get_menu_item( $index ) {
    $items = get_menu_items();
    $counter = 0;
    foreach ( $items as $val ) {
        if ( $val->menu_item_parent === '0' ) {
            $counter++;
        }
        if ( $counter == $index ) {
            return $val;
        }
    }
}

//Returns the logo menu item. I have it separated because my theme allows for varied logos
function get_logo() {
    $home = get_option( 'home' );
    $logo = get_option( 'logo' );
    $logo_item = <<<EOD

EOD;

    return $logo_item;
}

function get_menu_items() {
    $locations = get_nav_menu_locations();
    $menu = wp_get_nav_menu_object( $locations['primary'] );
    $items = wp_get_nav_menu_items( $menu );
    return $items;
}

Please feel free to tell me if I missed something, or if this could be done in a different way.
Thanks!
Answer: Your function name might be used by other plugins or themes and may cause a problem.
I suggest you either change the function name or use function_exists within if else statement.
Here is the manual > http://php.net/manual/bg/function.function-exists.php
Quick suggestion:
`
if(!function_exists('main'){
   function main(){
       $do_stuff = 'Currently doing';
       return $do_stuff;
   }
}

`
Answer: I am using the theme Page Builder Framework, then when you customize the appearance you can choose a centered menu where the logo is in the middle and the menu is split.


Does gifting items in TF2 to another player give them Premium status?

Question: Concurrently me and my friends are F2P players on TF2, and I'm planning to upgrade to Premium soon (by buying a key from the shop).
If I gift him an item from the shop, like a key, or a hat, or anything, does this grant him a premium status?
In other words, If I buy something for him, will he become Premium?  Or will he stay F2P?
Also, if I gift something to him, do I myself become Premium?  Then I could really save and let me simply send out a key or something.
Answer: As of November 21st, 2012, the item Upgrade to Premium Gift was released:

The Upgrade to Premium Gift is a tool. When used, it will grant the
  user a premium account granting them perks such as a 300 slot
  backpack, access to all crafting recipes, and the ability to trade
  their items to other players. Gifting this item to another player will
  give the sender the Professor Speks item.

Essentially, if you gift this item to someone else, not only will they become Premium, but you will also receive the Professor Speks item as well.
Answer: No, to obtain premium you must purchase atleast ONE item on the steam store, meaning that you have to charge your Steam wallet with a minimum of 5€.
Comment: @BlaXpiri what could possibly be clearer than "to become premium you need purchase something from the store"?
Comment: So if I gifted a key, which I would have to "purchase" out of the Steam Store, do I become premium?  This answer is somewhat vague....And would the other player become Premium?
Comment: @MrSmooth I'm almost certain that they eliminated that method.
Comment: There are actually ways to charge as little as you want, but I can't remember how, it's really annoying and out of the way though.
Comment: The person who Purchases and item gets premium, not the one who receives it,
Comment: Please improve the answer, some aspects are still unclear.
Answer: To become a Premium player, one must purchase something from the Mann Co. Store. However, in order to do this, one must also have money in their Steam Wallet. While the cheapest item in the store is 50 cents, the minimum amount of money to drop into your Steam account is five dollars. That being said, you can add five dollars to your Steam account, buy a Upgrade to Premium gift, gift it to your friend, and you would both have premium. However, this is not very efficient, as it would normally only cost a dollar (if you were both willing to add money to your Steam Wallet.
Answer: Your friend could sell anything they can on the steam Community market for $0.13 so they can get $0.10 to buy a giftapult. That would give them premium. So its really the cheapest way. The only item an f2p can really sell or trade is paint. I know because I sold some paint :P.