text:
Q: React-Native with Expo. I don´t undestand this errors I am developing a mobile app with React-Native with Expo. I followed a tutorial on Youtube to start with the packages and installation. In the video the man uses a Eslint configuration, when I tried to do the same error messages began to pop-up in the terminal. I just simply tried to run it and it worked fine. I wanna know why this appear and if I could do something to resolve this.
Here is my package-lock.json (the code with the babel or eslint mentions).
{
  "name": "xxx",
  "version": "1.0.0",
  "lockfileVersion": 2,
  "requires": true,
  "packages": {
    "": {
      "name": "xxx",
      "version": "1.0.0",
      "dependencies": {
        "@react-native-masked-view/masked-view": "0.2.6",
        "@react-navigation/material-top-tabs": "^6.2.1",
        "@react-navigation/native": "^6.0.10",
        "@react-navigation/stack": "^6.2.1",
        "@rneui/base": "^4.0.0-rc.2",
        "@rneui/themed": "^4.0.0-rc.2",
        "@types/react": "~17.0.21",
        "accordion-collapse-react-native": "^1.1.1",
        "expo": "^45.0.6",
        "expo-av": "~11.2.3",
        "expo-status-bar": "~1.3.0",
        "expo-updates": "~0.13.2",
        "lodash.filter": "^4.6.0",
        "react": "17.0.2",
        "react-dom": "17.0.2",
        "react-native": "0.68.2",
        "react-native-gesture-handler": "~2.2.1",
        "react-native-image-pan-zoom": "^2.1.12",
        "react-native-maps": "0.30.2",
        "react-native-modal": "^13.0.1",
        "react-native-pager-view": "5.4.15",
        "react-native-reanimated": "~2.8.0",
        "react-native-safe-area-context": "4.2.4",
        "react-native-screens": "~3.11.1",
        "react-native-tab-view": "^3.1.1",
        "react-native-table-component": "^1.2.0",
        "react-native-web": "0.17.7",
        "react-native-webview": "11.18.1"
      },
      "devDependencies": {
        "@babel/core": "^7.12.9",
        "babel-eslint": "^10.1.0",
        "eslint-config-standard": "^17.0.0",
        "eslint-config-standard-jsx": "^11.0.0",
        "eslint-config-standard-react": "^11.0.1",
        "eslint-plugin-import": "^2.26.0",
        "eslint-plugin-node": "^11.1.0",
        "eslint-plugin-promise": "^6.0.0",
        "eslint-plugin-react": "^7.29.4"
      }
    },
    "node_modules/eslint-config-standard-react": {
      "version": "11.0.1",
      "resolved": "https://registry.npmjs.org/eslint-config-standard-react/-/eslint-config-standard-react-11.0.1.tgz",
      "integrity": "sha512-4WlBynOqBZJRaX81CBcIGDHqUiqxvw4j/DbEIICz8QkMs3xEncoPgAoysiqCSsg71X92uhaBc8sgqB96smaMmg==",
      "dev": true,
      "funding": [
        {
          "type": "github",
          "url": "https://github.com/sponsors/feross"
        },
        {
          "type": "patreon",
          "url": "https://www.patreon.com/feross"
        },
        {
          "type": "consulting",
          "url": "https://feross.org/support"
        }
      ],
      "peerDependencies": {
        "eslint": "^7.12.1",
        "eslint-plugin-react": "^7.21.5"
      }
    },
    "eslint-config-standard-react": {
      "version": "11.0.1",
      "resolved": "https://registry.npmjs.org/eslint-config-standard-react/-/eslint-config-standard-react-11.0.1.tgz",
      "integrity": "sha512-4WlBynOqBZJRaX81CBcIGDHqUiqxvw4j/DbEIICz8QkMs3xEncoPgAoysiqCSsg71X92uhaBc8sgqB96smaMmg==",
      "dev": true,
      "requires": {}
    },
    "node_modules/babel-eslint": {
      "version": "10.1.0",
      "resolved": "https://registry.npmjs.org/babel-eslint/-/babel-eslint-10.1.0.tgz",
      "integrity": "sha512-ifWaTHQ0ce+448CYop8AdrQiBsGrnC+bMgfyKFdi6EsPLTAWG+QfyDeM6OH+FmWnKvEq5NnBMLvlBUPKQZoDSg==",
      "deprecated": "babel-eslint is now @babel/eslint-parser. This package will no longer receive updates.",
      "dev": true,
      "dependencies": {
        "@babel/code-frame": "^7.0.0",
        "@babel/parser": "^7.7.0",
        "@babel/traverse": "^7.7.0",
        "@babel/types": "^7.7.0",
        "eslint-visitor-keys": "^1.0.0",
        "resolve": "^1.12.0"
      },
      "engines": {
        "node": ">=6"
      },
      "peerDependencies": {
        "eslint": ">= 4.12.1"
      }
    },
    "babel-eslint": {
      "version": "10.1.0",
      "resolved": "https://registry.npmjs.org/babel-eslint/-/babel-eslint-10.1.0.tgz",
      "integrity": "sha512-ifWaTHQ0ce+448CYop8AdrQiBsGrnC+bMgfyKFdi6EsPLTAWG+QfyDeM6OH+FmWnKvEq5NnBMLvlBUPKQZoDSg==",
      "dev": true,
      "requires": {
        "@babel/code-frame": "^7.0.0",
        "@babel/parser": "^7.7.0",
        "@babel/traverse": "^7.7.0",
        "@babel/types": "^7.7.0",
        "eslint-visitor-keys": "^1.0.0",
        "resolve": "^1.12.0"
      }
    },

Here is my package.json
{
  "name": "xxx",
  "version": "1.0.0",
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    "start": "expo start",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "web": "expo start --web",
    "eject": "expo eject"
  },
  "dependencies": {
    "@react-native-masked-view/masked-view": "0.2.6",
    "@react-navigation/material-top-tabs": "^6.2.1",
    "@react-navigation/native": "^6.0.10",
    "@react-navigation/stack": "^6.2.1",
    "@rneui/base": "^4.0.0-rc.2",
    "@rneui/themed": "^4.0.0-rc.2",
    "@types/react": "~17.0.21",
    "accordion-collapse-react-native": "^1.1.1",
    "expo": "^45.0.6",
    "expo-av": "~11.2.3",
    "expo-status-bar": "~1.3.0",
    "expo-updates": "~0.13.2",
    "lodash.filter": "^4.6.0",
    "react": "17.0.2",
    "react-dom": "17.0.2",
    "react-native": "0.68.2",
    "react-native-gesture-handler": "~2.2.1",
    "react-native-image-pan-zoom": "^2.1.12",
    "react-native-maps": "0.30.2",
    "react-native-modal": "^13.0.1",
    "react-native-pager-view": "5.4.15",
    "react-native-reanimated": "~2.8.0",
    "react-native-safe-area-context": "4.2.4",
    "react-native-screens": "~3.11.1",
    "react-native-tab-view": "^3.1.1",
    "react-native-table-component": "^1.2.0",
    "react-native-web": "0.17.7",
    "react-native-webview": "11.18.1"
  },
  "devDependencies": {
    "@babel/core": "^7.12.9",
    "babel-eslint": "^10.1.0",
    "eslint-config-standard": "^17.0.0",
    "eslint-config-standard-jsx": "^11.0.0",
    "eslint-config-standard-react": "^11.0.1",
    "eslint-plugin-import": "^2.26.0",
    "eslint-plugin-node": "^11.1.0",
    "eslint-plugin-promise": "^6.0.0",
    "eslint-plugin-react": "^7.29.4"
  },
  "private": true,
  "eslintConfig": {
    "parser": "@babel-eslint",
    "extends": [
      "standard",
      "standard-jsx",
      "standard-react"
    ],
    "rules": {
      "react/prop-types": "off"
    }
  }
}

And the output from the terminal
PS C:\Users\xxx\Documents\xxx\xxx> npm install
npm WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead.
npm ERR! code ERESOLVE
npm ERR! ERESOLVE could not resolve
npm ERR!
npm ERR! While resolving: eslint-config-standard-react@11.0.1
npm ERR! Found: eslint@8.18.0
npm ERR! node_modules/eslint
npm ERR!   peer eslint@">= 4.12.1" from babel-eslint@10.1.0
npm ERR!   node_modules/babel-eslint
npm ERR!     dev babel-eslint@"^10.1.0" from the root project
npm ERR!   peer eslint@"^8.0.1" from eslint-config-standard@17.0.0
npm ERR!   node_modules/eslint-config-standard
npm ERR!     dev eslint-config-standard@"^17.0.0" from the root project
npm ERR!   10 more (eslint-config-standard-jsx, eslint-plugin-es, ...)
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer eslint@"^7.12.1" from eslint-config-standard-react@11.0.1
npm ERR! node_modules/eslint-config-standard-react
npm ERR!   dev eslint-config-standard-react@"^11.0.1" from the root project
npm ERR!
npm ERR! Conflicting peer dependency: eslint@7.32.0
npm ERR! node_modules/eslint
npm ERR!   peer eslint@"^7.12.1" from eslint-config-standard-react@11.0.1
npm ERR!   node_modules/eslint-config-standard-react
npm ERR!     dev eslint-config-standard-react@"^11.0.1" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See C:\Users\xxx\AppData\Local\npm-cache\eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\xxx\AppData\Local\npm-cache\_logs\2022-07-01T13_57_30_035Z-debug-0.log

Here is also the log that mentions:
    0 verbose cli C:\Program Files\nodejs\node.exe C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js
    1 info using npm@8.11.0
    2 info using node@v16.15.1
    3 timing npm:load:whichnode Completed in 0ms
    4 timing config:load:defaults Completed in 2ms
    5 timing config:load:file:C:\Program Files\nodejs\node_modules\npm\npmrc Completed in 8ms
    6 timing config:load:builtin Completed in 8ms
    7 timing config:load:cli Completed in 1ms
    8 timing config:load:env Completed in 1ms
    9 timing config:load:file:C:\Users\jbocci\Documents\GitHub\MendozaCiudadReactNativeApp\.npmrc Completed in 1ms
    10 timing config:load:project Completed in 3ms
    11 timing config:load:file:C:\Users\jbocci\.npmrc Completed in 0ms
    12 timing config:load:user Completed in 0ms
    13 timing config:load:file:C:\Users\jbocci\AppData\Roaming\npm\etc\npmrc Completed in 0ms
    14 timing config:load:global Completed in 1ms
    15 timing config:load:validate Completed in 0ms
    16 timing config:load:credentials Completed in 1ms
    17 timing config:load:setEnvs Completed in 1ms
    18 timing config:load Completed in 18ms
    19 timing npm:load:configload Completed in 18ms
    20 timing npm:load:mkdirpcache Completed in 1ms
    21 timing npm:load:mkdirplogs Completed in 0ms
    22 verbose title npm install
    23 verbose argv "install"
    24 timing npm:load:setTitle Completed in 1ms
    25 timing config:load:flatten Completed in 4ms
    26 timing npm:load:display Completed in 6ms
    27 verbose logfile logs-max:10 dir:C:\Users\jbocci\AppData\Local\npm-cache\_logs
    28 verbose logfile C:\Users\jbocci\AppData\Local\npm-cache\_logs\2022-07-01T13_57_30_035Z-debug-0.log
    29 timing npm:load:logFile Completed in 11ms
    30 timing npm:load:timers Completed in 0ms
    31 timing npm:load:configScope Completed in 0ms
    32 timing npm:load Completed in 38ms
    33 timing arborist:ctor Completed in 0ms
    34 silly logfile start cleaning logs, removing 2 files
    35 silly logfile done cleaning log files
    36 timing idealTree:init Completed in 839ms
    37 timing idealTree:userRequests Completed in 0ms
    38 silly idealTree buildDeps
    39 timing idealTree:#root Completed in 0ms
    40 silly fetch manifest eslint@^7.12.1
    41 timing arborist:ctor Completed in 0ms
    42 http fetch GET 200 https://registry.npmjs.org/eslint 950ms (cache revalidated)
    43 timing idealTree Completed in 1838ms
    44 timing command:install Completed in 1856ms
    45 verbose stack Error: could not resolve
    45 verbose stack     at PlaceDep.failPeerConflict (C:\Program Files\nodejs\node_modules\npm\node_modules\@npmcli\arborist\lib\place-dep.js:549:25)
    45 verbose stack     at PlaceDep.place (C:\Program Files\nodejs\node_modules\npm\node_modules\@npmcli\arborist\lib\place-dep.js:199:21)
    45 verbose stack     at new PlaceDep (C:\Program Files\nodejs\node_modules\npm\node_modules\@npmcli\arborist\lib\place-dep.js:73:10)
    45 verbose stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\@npmcli\arborist\lib\arborist\build-ideal-tree.js:990:31
    45 verbose stack     at Array.map (<anonymous>)
    45 verbose stack     at Arborist.[buildDepStep] (C:\Program Files\nodejs\node_modules\npm\node_modules\@npmcli\arborist\lib\arborist\build-ideal-tree.js:990:8)
    45 verbose stack     at async Arborist.buildIdealTree (C:\Program Files\nodejs\node_modules\npm\node_modules\@npmcli\arborist\lib\arborist\build-ideal-tree.js:218:7)
    45 verbose stack     at async Promise.all (index 1)
    45 verbose stack     at async Arborist.reify (C:\Program Files\nodejs\node_modules\npm\node_modules\@npmcli\arborist\lib\arborist\reify.js:153:5)
    45 verbose stack     at async Install.exec (C:\Program Files\nodejs\node_modules\npm\lib\commands\install.js:156:5)
    46 verbose cwd C:\Users\jbocci\Documents\GitHub\MendozaCiudadReactNativeApp
    47 verbose Windows_NT 10.0.18362
    48 verbose node v16.15.1
    49 verbose npm  v8.11.0
    50 error code ERESOLVE
    51 error ERESOLVE could not resolve
    52 error
    53 error While resolving: [1meslint-config-standard-react[22m@[1m11.0.1[22m
    53 error Found: [1meslint[22m@[1m8.18.0[22m[2m[22m
    53 error [2mnode_modules/eslint[22m
    53 error   [35mpeer[39m [1meslint[22m@"[1m>= 4.12.1[22m" from [1mbabel-eslint[22m@[1m10.1.0[22m[2m[22m
    53 error   [2mnode_modules/babel-eslint[22m
    53 error     [33mdev[39m [1mbabel-eslint[22m@"[1m^10.1.0[22m" from the root project
    53 error   [35mpeer[39m [1meslint[22m@"[1m^8.0.1[22m" from [1meslint-config-standard[22m@[1m17.0.0[22m[2m[22m
    53 error   [2mnode_modules/eslint-config-standard[22m
    53 error     [33mdev[39m [1meslint-config-standard[22m@"[1m^17.0.0[22m" from the root project
    53 error   10 more (eslint-config-standard-jsx, eslint-plugin-es, ...)
    53 error
    53 error Could not resolve dependency:
    53 error [35mpeer[39m [1meslint[22m@"[1m^7.12.1[22m" from [1meslint-config-standard-react[22m@[1m11.0.1[22m[2m[22m
    53 error [2mnode_modules/eslint-config-standard-react[22m
    53 error   [33mdev[39m [1meslint-config-standard-react[22m@"[1m^11.0.1[22m" from the root project
    53 error
    53 error Conflicting peer dependency: [1meslint[22m@[1m7.32.0[22m[2m[22m
    53 error [2mnode_modules/eslint[22m
    53 error   [35mpeer[39m [1meslint[22m@"[1m^7.12.1[22m" from [1meslint-config-standard-react[22m@[1m11.0.1[22m[2m[22m
    53 error   [2mnode_modules/eslint-config-standard-react[22m
    53 error     [33mdev[39m [1meslint-config-standard-react[22m@"[1m^11.0.1[22m" from the root project
    53 error
    53 error Fix the upstream dependency conflict, or retry
    53 error this command with --force, or --legacy-peer-deps
    53 error to accept an incorrect (and potentially broken) dependency resolution.
    53 error
    53 error See C:\Users\jbocci\AppData\Local\npm-cache\eresolve-report.txt for a full report.
    54 verbose exit 1
    55 timing npm Completed in 2071ms
    56 verbose unfinished npm timer reify 1656683850227
    57 verbose unfinished npm timer reify:loadTrees 1656683850242
    58 verbose unfinished npm timer idealTree:buildDeps 1656683851083
    59 verbose unfinished npm timer idealTree:node_modules/eslint-config-standard-react 1656683851085
    60 verbose code 1
    61 error A complete log of this run can be found in:
    61 error     C:\Users\jbocci\AppData\Local\npm-cache\_logs\2022-07-01T13_57_30_035Z-debug-0.log

If I run npm install whit --force or --legacy-peer-deps it remains the same, nothing changes.
If anyone knows how to resolve this please help. ^_^


text:
Q: Is there possibility of sum of ArrayList without looping Is there possibility of sum of ArrayList without looping?
PHP provides sum(array) which will give the sum of array.
The PHP code is like
$a = array(2, 4, 6, 8);
echo "sum(a) = " . array_sum($a) . "\n";

I wanted to do the same in Java:
List tt = new ArrayList();
tt.add(1);
tt.add(2);
tt.add(3);

A: Write a util function like
public class ListUtil{

    public static int sum(List<Integer> list){
      if(list==null || list.size()<1)
        return 0;

      int sum = 0;
      for(Integer i: list)
        sum = sum+i;

      return sum;
    }
}

Then use like
int sum = ListUtil.sum(yourArrayList)

A: for me the clearest way is this:
doubleList.stream().reduce((a,b)->a+b).get();

or
doubleList.parallelStream().reduce((a,b)->a+b).get();

It also use internal loops, but it is not possible without loops.

A: Then write it yourself:
public int sum(List<Integer> list) {
     int sum = 0;

     for (int i : list)
         sum = sum + i;

     return sum;
}

A: You can use apache commons-collections API.
class AggregateClosure implements org.apache.commons.collections.Closure {
        int total = 0;

        @Override
        public void execute(Object input) {
            if (input != null) {
                total += (Integer) input;
            }
        }

        public int getTotal() {
            return total;
        }
    }

Then use this closure as shown below:
public int aggregate(List<Integer> aList) {
        AggregateClosure closure = new AggregateClosure();
        org.apache.commons.collections.CollectionUtils.forAllDo(aList, closure);
        return closure.getTotal();
}

A: This can be done with reduce using method references reduce(Integer::sum):
Integer reduceSum = Arrays.asList(1, 3, 4, 6, 4)
        .stream()
        .reduce(Integer::sum)
        .get();

Or without Optional:
Integer reduceSum = Arrays.asList(1, 3, 4, 6, 4)
        .stream()
        .reduce(0, Integer::sum);

A: Once java-8 is out (March 2014) you'll be able to use streams:
If you have a List<Integer>
int sum = list.stream().mapToInt(Integer::intValue).sum();

If it's an int[]
int sum = IntStream.of(a).sum();

A: The only alternative to using a loop is to use recursion.
You can define a method like
public static int sum(List<Integer> ints) {
   return ints.isEmpty() ? 0 : ints.get(0) + ints.subList(1, ints.length());
}

This is very inefficient compared to using a plain loop and can blow up if you have many elements in the list.
An alternative which avoid a stack overflow is to use.
public static int sum(List<Integer> ints) {
    int len = ints.size();
    if (len == 0) return 0;
    if (len == 1) return ints.get(0);
    return sum(ints.subList(0, len/2)) + sum(ints.subList(len/2, len));
}

This is just as inefficient, but will avoid a stack overflow.

The shortest way to write the same thing is
int sum = 0, a[] = {2, 4, 6, 8};

for(int i: a) {
    sum += i;
}

System.out.println("sum(a) = " + sum);

prints
sum(a) = 20

A: If you know about the map function, then you know that a map is also can be recursive loop or recursive loop. But obviously you have to reach each element for that.   so, I could not work out the Java 8, because some syntax mismatch but wanted a very short so this is what I got.
int sum = 0
for (Integer e : myList) sum += e;

A: Given that a list can hold any type of object, there is no built in method which allows you to sum all the elements. You could do something like this:
int sum = 0;

for( Integer i : ( ArrayList<Integer> )tt ) {
  sum += i;
}

Alternatively you could create your own container type which inherits from ArrayList but also implements a method called sum() which implements the code above.

A: ArrayList is a Collection of elements (in the form of list), primitive are stored as wrapper class object but at the same time i can store objects of String class as well. SUM will not make sense in that. BTW why are so afraid to use for loop (enhanced or through iterator) anyways?

A: Or switch to Groovy, it has a sum() function on a collection.
[1,2,3,4,5,6].sum()
http://groovy.codehaus.org/JN1015-Collections
Runs on the same JVM as your java classes.

A: This link shows three different ways how to sum in java, there is one option that is not in previous answers using Apache Commons Math..
Example:
public static void main(String args []){
    List<Double> NUMBERS_FOR_SUM = new ArrayList<Double>(){
         {
            add(5D);
            add(3.2D);
            add(7D);
         }
    };
    double[] arrayToSume = ArrayUtils.toPrimitive(NUMBERS_FOR_SUM
            .toArray(new Double[NUMBERS_FOR_SUM.size()]));
    System.out.println(StatUtils.sum(arrayToSume));

}

See StatUtils api

A: You can use GNU Trove library:
TIntList tt = new TIntArrayList();
tt.add(1);
tt.add(2);
tt.add(3);
int sum = tt.sum();

redpajama_set_name: RedPajamaStackExchange


text:
Q: Calling one feature file as background step into another using cucumber ruby I have a feature file A with 8-9 lines of steps which is covering one scenario. Now I need to use feature file A as a background step in feature file B by reducing number of steps to 3-4.
My approach:

*

*In feature file B - Reduce steps(from feature file A) to 3-4 lines, use helper methods and add as background steps.

Feature file A:

Feature: I want to create an event

  Background: User is Logged In
    Given a logged in user

Scenario: Creating an event
  Given I select event
  And I add event details
  And I add start and end time
  Then Timings will be added successfully
  When I add ticket information and continue
  And Publish my event
  Then I verify event will be created successfully

Feature file B

Feature: Place an order

Background: Event is created

Given a logged in user

When I select event and fill in required details

Then event should be published

I'm concern about duplication. I'm using feature file A as a background step in feature file B by reducing number of steps but functionally both feature files are testing same feature.
Please suggest a better approach if possible. Thank you

A: So fundamentally using helper methods to reduce number of steps is only something you should do if the compressed steps are also conveying the information correctly. So here is an example (You don't need helpers here either), that would be a good use case.
Given I have a party of 2/1/0 # This means adults/children/infants
And the child is under 12
And I am flexible on my flights
And I am going to Spain
When I search for flights

Given I have Spanish flights displayed # You could also add the pax in here if you wanted

Now if you're wanting to use helper methods, that is also fine, but you need to remember cucumber is primarily a tool for encouraging collaboration as well as providing documentation, testing and specification in the same place. So once you try to DRY up your lines, think about whether actually you just want to "compress" the lines down.
i.e.
Given('I am {int} years old') do |age|
  @person.age = age
end

Given('my name is {word}') |name|
  @person.name = name
end

Given('my hometown is {string}') |hometown|
  @person.location = hometown
end

Can become
Given('I am {word}, {int} years old from {string}') |name, age, hometown|
  @person.name = name
  @person.age = age
  @person.location = hometown
end

Hopefully some of these tips will have given you some thought.


text:
Q: Converting a Column with a list of names into a string with associated email I have a list of peoples names in a column (on sheet 12) and in that column each cell can have one or more person inside of it separated by a comma and and an alt+enter. What I want to do is take the contents of this column, convert it into a list of emails, and then convert this into a single string which only has unique entries with the peoples email addresses (i.e. if the name is repeated in the column, after the persons email has been added it does not get included in the string again).
I would like to avoid including an additional column in the sheet with the emails, so I have another tab with a list of peoples names against their email addresses which I used an index match to obtain the emails with.
The below code is the only way I can think of doing it but as the number of people in  each cell increases the number of possible combinations increases so it gets too unwieldy to create, hence, I have come here in the hopes there is a way to overcome this.
Sub Macro1()

Dim i As Integer
Dim P As Integer
Dim Email_To As String
Dim Email_Rng As Range
Dim Num_of_Emails As Integer
Dim Last_Cell_TWDS As Integer
Dim Last_Cell_TWDP As Integer
Dim Last_Cell_RCAR As Integer
Dim Last_Cell_Specs As Integer
Dim Last_Cell_Minutes As Integer
Dim First_Row As Integer
Dim Owner_Column As Integer
Dim Email_Check As String
Dim Email_Check_P1 As String
Dim Email_Check_P2 As String
Dim Email_Check_P3 As String
Dim Email_Check_P4 As String
Dim Num_People_Cell As Integer
Dim Cell_Value As String
Dim P1 As String
Dim P2 As String
Dim P3 As String
Dim P4 As String

'Setting Email to to empty
Email_To = ""

'Email to TWDS
    Sheet12.Select
    Last_Cell_TWDS = Range("Admin!U2").Value
    First_Row = 5
    Owner_Column = 5
    Email_Check = ""

    For i = First_Row To (Last_Cell_TWDS + 4)

    If Cells(i, Owner_Column).Value <> "" Then 'check if the cell is empty and if not set the cell value to check the email

        Num_People_Cell = Len(Cells(i, Owner_Column).Value) - Len(Replace(Cells(i, Owner_Column).Value, ",", "")) + 1 ' Checking the number of people in the cell using the number of commas

    End If

        If Cells(i, Owner_Column).Value <> "" Then 'check if the cell is empty and if not set the cell value to check the email

            For P = 1 To Num_People_Cell ' +1 because 2 people = 1 comma

               If P = 1 Then '////////////////////////////////////////////////////////////////////////////////////////////1 Person

                    If Num_People_Cell = 1 Then

                        Email_Check = WorksheetFunction.Index(Range("Admin!Q4:Q200"), WorksheetFunction.Match(Cells(i, Owner_Column).Value, Range("Admin!P4:P200"), 0)) 'define what the current email is for the name in the cell

                    End If

                     If Cells(i, Owner_Column).Value = "" Then ' if the cell is Blank do nothing
                         Email_To = Email_To

                     ElseIf Email_To = "" Then 'if the cell is not blank then take the contents of the cell and add it to email_To string

                             Email_To = Email_To & WorksheetFunction.Index(Range("Admin!Q4:Q200"), WorksheetFunction.Match(Cells(i, Owner_Column).Value, Range("Admin!P4:P200"), 0))

                     ElseIf InStr(1, Email_To, Email_Check) <> 0 Then 'if Email_To is not blank then check if the cell value is already in the Email_To string

                             Email_To = Email_To

                     Else

                         Email_To = Email_To & "; " & WorksheetFunction.Index(Range("Admin!Q4:Q200"), WorksheetFunction.Match(Cells(i, Owner_Column).Value, Range("Admin!P4:P200"), 0))

                    End If

                ElseIf P = 2 Then '////////////////////////////////////////////////////////////////////////////////////////////2 People

                     'define the two peoples names
                     P1 = Left(Cells(i, Owner_Column).Value, InStr(1, Cells(i, Owner_Column).Value, ",") - 1)
                     P2 = Right(Cells(i, Owner_Column).Value, (Len(Cells(i, Owner_Column).Value) - 3 - InStr(1, Cells(i, Owner_Column).Value, ",")))
                     Email_Check_P1 = WorksheetFunction.Index(Range("Admin!Q4:Q200"), WorksheetFunction.Match(P1, Range("Admin!P4:P200"), 0)) 'define what the current email is for the name in the cell
                     Email_Check_P2 = WorksheetFunction.Index(Range("Admin!Q4:Q200"), WorksheetFunction.Match(P2, Range("Admin!P4:P200"), 0)) 'define what the current email is for the name in the cell

                     If Email_To = "" Then 'if the cell is not blank then take the contents of the cell and add it to email_To string

                             Email_To = P1 & "; " & P2

                    ElseIf InStr(1, Email_To, Email_Check_P1) <> 0 And InStr(1, Email_To, Email_Check_P2) <> 0 Then

                         Email_To = Email_To

                    ElseIf InStr(1, Email_To, Email_Check_P1) = 0 And InStr(1, Email_To, Email_Check_P2) = 0 Then

                         Email_To = Email_To & "; " & WorksheetFunction.Index(Range("Admin!Q4:Q200"), WorksheetFunction.Match(P1, Range("Admin!P4:P200"), 0)) & "; " & WorksheetFunction.Index(Range("Admin!Q4:Q200"), WorksheetFunction.Match(P2, Range("Admin!P4:P200"), 0))

                    ElseIf InStr(1, Email_To, Email_Check_P1) > 0 Then

                         Email_To = Email_To & "; " & WorksheetFunction.Index(Range("Admin!Q4:Q200"), WorksheetFunction.Match(P1, Range("Admin!P4:P200"), 0))

                    ElseIf InStr(1, Email_To, Email_Check_P2) > 0 Then

                         Email_To = Email_To & "; " & WorksheetFunction.Index(Range("Admin!Q4:Q200"), WorksheetFunction.Match(P2, Range("Admin!P4:P200"), 0))

                    End If

                End If

            Next P

        End If

    Next i

End Sub

A: This might be a way to handle it:
EDIT: added getting a single string with all unique mails
Sub Tester()

    Dim c As Range, v, arr, nm, email, emails, sep
    Dim dict As Object, rngEmails As Range

    Set dict = CreateObject("scripting.dictionary") 'for tracking unique values

    'email lookup table: name|email
    Set rngEmails = ThisWorkbook.Sheets("Admin").Range("P4:Q4")

    For Each c In sheet12.Range("E5:E" & sheet12.Cells(Rows.Count, "E").End(xlUp).Row)
        v = c.Value
        If Len(v) > 0 Then                    'ignore empy cells
            v = Replace(v, vbLf, ",")         'get a single thing to split on...
            arr = Split(v, ",")               'get an array of names
            For Each nm In arr                'loop over the array
                nm = Trim(nm)                 'remove leading/trailing spaces
                If Not dict.exists(nm) Then   'if a new name then get the email
                    email = Application.VLookup(nm, rngEmails, 2, False)
                    If Not IsError(email) Then
                        dict(nm) = email
                    Else
                        Debug.Print "No email found for '" & nm & "'"
                    End If
                End If
            Next nm
        End If
    Next c

    emails = Join(dict.items, ";") 'get single string from dictionary items
    'do something with `emails`

End Sub


text:
Q: Scrollable DIV in TD works in WebKit, but not in Gecko I'm working on a school project, and I have to create a simple presentation webpage. The problem is that the webpage doesn't work as expected in Firefox, while in Chrome and othet WebKit browser it's all fine.
My problem is here: http://c303.usv.ro/~HPC/ (please don't change the language in English, as you will not be able to see my problem). If you go to "Echipamente" in Chrome, you'll see that the "#content" div has some nice scrollbarls and the footer stays at the bottom. If you'll do that in Firefox, the scrollbars no longer appears and the footer seems to go somewhere under the visible part of the webpage. As a workaround I use:
function mozillaFix(){
    return; // we shouldn't use this
    $('#content').height($('#maindiv').height() - $('#topheader').height() - $('#copynote').height() - 40)
    $('#leftmenu').height($('#maindiv').height() - $('#topheader').height() - $('#copynote').height() - 40)
}

but I guess that this is not the mos elegant solution. Where could be the issue?

A: Set the max-height with Javascript to the desired height (I tested it with FireBug to with max-height: 400px;). Then, Firefox will make a nice scrollbar, and show the footer as you wanted.

As found on the internet, the solution is defining the height of the container of the div. If you have the following CSS it should work:
html, body {
    height: 100%;
}


text:
Q: Am I thinking the AngularJS way? I'm attempting to dabble with AngularJS and would like to know if the code that I've put below is inline with the AngularJS way of writing or could something be improved?
Intention: Hide the reset button and show it when the user keys-in something in the username and password input boxes. And validate username and show info text when username validation fails.
<!DOCTYPE html>

    <title>Playing with some ng-directives</title>

          Username:
          <input type="text" ng-model="username" ng-change="validateUsername();resetRequired()"/>

 Username can only contain alphabets and numbers. Nothing else is allowed!

          Password:
          <input type="password" ng-model="password" ng-change="resetRequired()"/>

          <input type="submit" value="Login" ng-hide="hideLoginButton"/>
          <input type="button" value="Reset" ng-hide="hideResetButton"/>

Appreciate your feedback in advance.

A: Looks just fine to me, couple of pointers.
I would turn validateUsername();resetRequired() into a single method on the scope, reducing clutter in your HTML.
The ternary ? true : false is redundant, Just use the boolean expression you had in the first place:
$scope.hideResetButton = !$scope.username.length && !$scope.password.length

(note that == 0 is falsy, so you can just check for a truthy length value)
Lastly, if it were up to me, I'd validate with a watch expression, rather than on change events. This would further clean up your code. Example:
$scope.$watch('username + password', function () {
    $scope.invalidateReset();
});

The results of the 'username + password' expression aren't particularly important, we just want the watch to fire if any of the values change. The fact that you won't need to actively add a check on all DOM elements which might change the model, but rather sit back and let the changes come to you, warrant the refactor.


text:
Q: Hyperlink to servlet I have a java program that accesses a database with columns ID, FirstName, LastName, Age. (ID is the primary key, no two elements in the database have the same ID).
In part of my program, a Servlet displays all of the elements in the database in a HTML table, except it only displays the ID and FirstName-fields. I have set up the ID field to be a hyperlink. So far so good.
However, when the user clicks the ID hyperlink, I want this to forward them to a Servlet that displays ID, FirstName, LastName, and Age of the particular element they clicked on. So, let's say this is the table the HTML displays:

*

*Row 1: [ID=1, FirstName=Jim], and

*Row 2: [ID=2, FirstName=Joe].

The actual data in the database is:

*

*Row 1: [ID=1, FirstName=Jim, LastName=Smith, Age=25], and

*Row 2: [ID=2, FirstName=Joe, LastName=Chang, Age=37].

In the display table ID fields are hyperlinks for both Jim and Joe. This is all working so far.
However, when I actually click one, it doesn't do what I want. Say I clicked on the hyperlinked 2, in front of Joe. Then I would expect it to display 2, Joe, Chang, 37, from the database, but I don't know how to do this.
All the hyperlink is doing is forwarding the request to a Servlet, whose URL pattern is DisplayPerson.do, and attempting to get the ID parameter so it can get the element with that ID and display all of the other fields.
I know how to display all the fields IF I can get the ID parameter- but I don't know how to set or send different ID parameters when each different hyperlinked ID is clicked, they all just forward to the same Servlet but this doesn't know which one the request was sent from.
I would also like to avoid URL appending if possible, but if that's the only way to do it then I could do that. Can someone explain how this can be done (or even if)?

A: It looks like with your first response you already have all the stuff you need, then why do you want to send another request to the server? Unless you want to do some totally new/different on the server, a better approach would to use client side javascript to show the stuff you want on click of the URL. Basically, send everything back to the client as the response from your (first) servlet but have the information that you don't want to display hidden at first. Form the URL such that it has onclick event attached to a javascript function. The java script function can accept an identifier or something and then show the stuff dynamically on the client.

A: So the basic problem is ..
 but I don't know how to set or send different ID parameters when each different hyperlinked ID is clicked, they all just forward to the same Servlet but this doesn't know which one the request was sent from.
..
How are the hyperlinks being created? They need to include the id associated with the particular record. So the hyperlink should look like  'http://yourservername/yourservletname?id=123'
While creating the URL int he first step, you need to embed the id parameter in the link itself.
That should make it work.
Another tip is to install firebug in your browser and see how the request is being sent.

A: if you dont want to append parameters to the link, an alternative would be to declare an html form for the table (form.method=post and form.action=DisplayPerson.do). assuming you only want to pass one param, personid in this case

*

*for each row, make the link call a javascript function, taking the personId associated with the row as parameter, for example postViewPerson('1'), where the parameter '1' is dynamically generated

*have a special hidden input named as clickedPersonid

*the js function (ex. postViewPerson) will assign the parameter value to the clickedPersonid and will submit the form

*the hidden input now has a value which the servlet can get through request.getParameter("clickedPersonid")

A: Two Options:

*

*Append parameter to URL, but you dont want to do it.

*Instead of link, create submit buttons, with multiple forms for each record where you can even specify POST for your request.


text:
Q: Auto-generate person_id and student_id for SINGLE_TABLE inheritance model I have two entities person and Student, the student entity extends person and has its own identifier studentNumber. When creating a new student, i want to auto-generate both identification numbers.
The following snippet fails with: person_id being NULL
@RooEntity(identifierColumn = "personID", inheritanceType = "SINGLE_TABLE")
@DiscriminatorColumn(name = "TYPE", discriminatorType = DiscriminatorType.STRING, length = 20)
@DiscriminatorValue("P")
public class Person {
}

The student Entity
@RooEntity
@DiscriminatorValue("S")
public class Student extends Person {

    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "studentNumber")
    private long studentNumber;
}

Here is where i create a new student and the student number is generated but personid is not?
    private Student student;

    /**
     * @method Create a new student using our persistence model---Not Null variables
     */

    public void CreateNewStudent(String firstName, String lastName, String telephone, Date birthday, GenderType gender){

        student = new Student();
        //set our variables and persist
        student.setFirstName(firstName);
        student.setLastName(lastName);
        student.setTelephone(telephone);
        student.setBirthDay(birthday);
        student.setGender(gender);

        student.persist();
    }
}

is there any way i can create both studentNumber and personID when a student is created?

A: Based on your follow-up comments what you want is to have a primary key identifier for Person, and a unique identifier for Student. Note that with your current setup, only one of the keys can be auto generated (many DBMSes only allow one column per table to be auto incremented). So I would recommend that you first define your primary key column for Person:
@Entity
@Table(name="person")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="TYPE", discriminatorType=DiscriminatorType.STRING,length=20)
@DiscriminatorValue("P")
public class Person {
    @Basic
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="personId")
    private Long id;
}

Note that in your DB you will want to have the personId column as the auto-increment. Then define a separate generated value annotation for your student numbers. The example I show below uses a table generator but you can do whatever you want:
@Entity
@DiscriminatorValue("S")
public class Student extends Person {
   @Basic
   @TableGenerator(name="ID_GEN", table="identifier_table", pkColumnName="seq_name",
        valueColumnName="seq_count", pkColumnValue="student_seq")
   @GeneratedValue(strategy = GenerationType.TABLE, generator = "ID_GEN")
   @Column(name = "studentNumber")
   private Long studentNumber;
}

Heres the DDL for the table you will need to support sequence number generation for Students, given the example above:
create table identifier_table (
  id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  seq_name VARCHAR(255) NOT NULL,
  seq_count INT NOT NULL DEFAULT 0
);

And you would initially populate it with:
insert into identifier_table (seq_name, seq_count) VALUES ('student_seq', 0);

Of course, the simpler solution would be to declare your student identifier's as String, then you could just do the following, much easier setup:
public class Student extends Person {
    @Basic
    @NotNull
    @Column(name = "studentId")
    private String studentIdentifier;
}

And before saving each record, set the student ID with the UUID class:
aStudent.setStudentIdentifier(UUID.randomUUID().toString());

Hope this helps.

A: I think you can only have one GenerateValue currently.  If you want two, you either need to not use inheritance, i.e. Person has a 1-1 to StudentInfo, or you could assign the other id in an event or from your app.  There is an API on the EclipseLink Session to get a new generated id.


text:
Q: Should i use 'conda init' before opening jupyter notebook? I recently installed anaconda3 in ubuntu on default location. I didn't want base env to run every time i open terminal, so i used conda config --set auto_activate_base False.
To open jupyter notebook, i need to use source /home/<path to anaconda3>/anaconda3/bin/activate. Now, anaconda documentation specifically says to use conda init after it.
https://docs.anaconda.com/anaconda/install/linux/
But without using the conda init command i can directly open jupyter notebook (or anaconda). Should i use conda init or bypass it?


text:
Q: Magento, Get Ratings as a number in php I am trying to change my template to reflect the schema.org html
The only problem I have had so far is the reviews average which should be a number from 0 to 5.
there is a function called getratingssummary, but its used inside the style attribute of a div, I think it does not return a number
so far I have this
<?php if ($this->getReviewsCount()): ?>

        <?php if ($this->getRatingSummary()):?>

                <div class="rating" style="width:<?php echo $this->getRatingSummary() ?>%"><meta itemprop="ratingValue" content="5"/>

                <?php echo $this->getReviewsCount() ?>

        <?php endif;?>

            <a href="<?php echo $this->getReviewsUrl() ?>"><?php echo $this->__('%d Review(s)', $this->getReviewsCount()) ?>

A: To get the numeric star rating as opposed to the percentage open your desired review helper which could be either;
app/design/frontend/default/YOURTHEME/template/review/helper/summary_short.phtml

or
app/design/frontend/default/YOURTHEME/template/review/helper/summary.phtml

And use this code to get your number;
<?php
$ratingPercent = $this->getRatingSummary();
echo ($ratingPercent * 5)/100;
?>

A: The getRatingSummary function does return a numeric value, it just happens to be a percentage. If you have a look at the way it's called in the style attribute of the rating div you will see (if you replace the function call with an X)...it's definitely bringing back a percentage.

I would echo the $this->getRatingSummary() function call and see what you are getting back, then you can work on the maths to turn it into a 0-5 value.

A: You can try this, but you have to make it work to show a number instead of percentage:
<?php
$storeId = Mage::app()->getStore()->getId();
$summaryData = Mage::getModel('review/review_summary')->setStoreId($storeId)  ->load($_product->getId());
?>

// Rating Percentage showing of a product

<?php echo $summaryData['rating_summary']; ?>%


text:
Q: Как узнать является ли тип перечислением? Можно ли как-нибудь проверить, является ли тип перечислением, т.е. enum или enum class?

A: Начиная с C++11 — да. Это можно сделать с помощью шаблонного класса std::is_enum в заголовочном файле type_traits.

A: #include <iostream>
#include <type_traits>

class A {};
enum E {};
enum class Ec : int {};

int main()
{
    std::cout << std::boolalpha;
    std::cout << std::is_enum<A>::value << '\n';
    std::cout << std::is_enum<E>::value << '\n';
    std::cout << std::is_enum<Ec>::value << '\n';
    std::cout << std::is_enum<int>::value << '\n';
}

Ну, или
std::cout << std::is_enum<A>() << '\n';
std::cout << std::is_enum<E>() << '\n';
std::cout << std::is_enum<Ec>() << '\n';
std::cout << std::is_enum<int>() << '\n';


text:
Q: HTML / CSS / JS --> Syntax Error: Animated SignUp Form I followed advice from this site on how to embed
the code that i found on how to recreate the
Animated Sign In Form … shown here:
https://youtu.be/5uANWpkuPww
I was hoping to modify it, so that one face of the
animated circle contained text inviting people to
subscribe to my mailing list … with the clickable
link causing the circle to rotate, allowing people
to then enter their name and email address.
In any case, I got the code from:
https://github.com/DaftCreation/Animated-Sign-In---Sign-Up-Form
and tried it out on w3schools.com
Here is the result:
https://www.w3schools.com/code/tryit.asp?filename=G15FD7XT1JF6
If anybody will be kind enough to get it to work,
please save it on w3schools.com … and post the link / URL
here on stackoverflow.com
I am guessing that the guy that created it, may have left out
a character or two, when he cut and pasted it, which has
resulting in the code not working correctly ... and be sure to
let me know what was wrong with it, so that i can learn from this.
Thanks  : )

A: Your code is fine - the only real problem with is that you didn't wrap your jQuery in between <script></script> tags. Use the link below and you can see it working.
https://www.w3schools.com/code/tryit.asp?filename=G15LTVZCBB4R
Also you need to make sure your jQuery link is valid (just copy and paste the one from my code - it is via Google CDN).


text:
Q: C# AutoMapper with Entity Framework - Works with List but not single nullable instance I have a very wierd error that I can't get my head around. I'm using AutoMapper 6 with AutoMapper.Collection and AutoMapper.Collection.EntityFramework.
https://github.com/AutoMapper/AutoMapper.Collection
As you can see from the screenshot below, every component is updated apart from Image that is null for updatedContact. If I however do an explicit mapping for only updatedImage it works. It also works to update a collection of images without a problem. Has anyone experienced this? Other single properties works as well but for some reason Image is causing trouble.
//Works
var updatedArticle = Mapper.Map<ArticleViewModel, Article>(articleVm, articleOriginal);
//Every component is updated a part from Image.
var updatedContact = Mapper.Map<ContactViewModel, Contact>(contactVm, contactOriginal);
//Works
var updatedImage = Mapper.Map<ImageViewModel, Image>(contactVm.Image);
//Works
var newContact = Mapper.Map<ContactViewModel, Contact>(contactVm);

Mapping:
cfg.CreateMap<ArticleViewModel, Article>(MemberList.Source)
    .EqualityComparison((src, dst) => src.Id == dst.Id);

cfg.CreateMap<ImageViewModel, Image>(MemberList.Source)
    .EqualityComparison((src, dst) => src.Id == dst.Id)
    .ForSourceMember(x => x.IsDeleted, opt => opt.Ignore())
    .ForMember(dest => dest.ImageBytes, opt => opt.MapFrom(src => Encoding.ASCII.GetBytes(src.Image)));

cfg.CreateMap<ContactViewModel, Contact>(MemberList.Source)
.EqualityComparison((src, dst) => src.Id == dst.Id)
.ForSourceMember(x => x.IsDeleted, opt => opt.Ignore())
.ForSourceMember(x => x.FullName, opt => opt.Ignore());

Files:
public class ArticleViewModel
{
    public int Id { get; set; }
    ...
    public List<ImageViewModel> Images { get; set; }
}

public class Article : IEntity<int>
{
    public int Id { get; set; }
    ...
    public virtual ICollection<Image> Images { get; set; }
}

public class ContactViewModel
{
    public int Id { get; set; }
    ...
    public ImageViewModel Image { get; set; }
}

public class Contact: IEntity<int>
{
    [Key]
    public int Id { get; set; }

    ...

    public int? ImageId { get; set; }

    public Image Image { get; set; }

}

public class ImageViewModel
{
    public int Id { get; set; }

    public string Image { get; set; }

    public string ImageType { get; set; }

    public bool IsDeleted { get; set; }
}

public class Image : IEntity<int>
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public DateTime Created { get; set; }

    public DateTime Updated { get; set; }

    public byte[] ImageBytes { get; set; }

    public string ImageType { get; set; }

    public int? ArticleId { get; set; }

    public virtual Article Article { get; set; }
}

A: Finally solved it, I had forgot to mark Image as virtual in Contact. After doing that everything started working out of the box.
public virtual Image Image { get; set; }

A: I think you need to tell your contact mapper in the config to explicitly use the mapping for the image vm. There might be one or two typos as I'm doing this from memory but it should be similar to:
.ForMember(x => x.Image, opt => opt.MapFrom(contact => Mapper.Map<ImageViewModel, Image>(contact.ImageVm);))


text:
Q: filter array values with angular In an angular json response as shown when stringified
console.log("point data "+JSON.stringify(res,data.data));

my json response is of this format
"Monday : meeting invite"
...
"Notice : Come to hall"

I am trying to iterate over the above list in view
$rootScope.allData = res.data.data;

{{allData}} //prints Monday : meeting invite

how to do this upon iterating is a challenge

  Today:   {{allData}} // to print "Monday"
  Task:   {{allData}} //to print meeting invite

this is because the : represents a new data

A: On the data binding you can do split(':')

Today:   {{allData.split(':')[0]}} // to print "Monday"
Task:   {{allData.split(':')[1].trim()}}} //to print meeting invite

The trim() is optional here.
This is not something I would do though. This gets the job done but what I would prefer is create/map the allData a new array of object having two properties. The heading and the task. Then access them while iterating.
// mappedData is mapped from allData

Today:   {{data.Heading}} // to print "Monday"
Task:   {{data.Task}}} //to print meeting invite

Update: As per user10445503 My code does need track by. Adding it to my code.

A: Elegant way with array functions
$rootScope.allData = res.data.data.map(function(dataItem) {
    const dataItemParts = dataItem.split(':').map(function(part){
        return part.trim();
    });

    return {
        head: dataItemParts[0],
        content: dataItemParts[1]
    }
})

And then

  Today:   {{myData.head}} // to print "Monday"
  Task:   {{myData.content}} //to print meeting invite

For removing repeatable values with js you can use

  Today:   {{myData.head}} // to print "Monday"
  Task:   {{myData.content}} //to print meeting invite


text:
Q: getnameinfo() from ifaddrs.h gives junk values in C I want to retrieve ip address of the current wireless interface I use. For that I use getnameinfo() function from ifaddrs.h library. My problem is that this function return junk values rather than the actual ip address.
Here is the function I use:
void getWIFromSystem(WI **WIHead) {
  struct ifaddrs *ifaddr, *ifa;
  char host[NI_MAXHOST];

  if (getifaddrs(&ifaddr) == -1) {
    perror("getifaddrs");
    exit(-1);
  }

  /* Walk through linked list, maintaining head pointer so we
     can free list later */
  for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
    if (ifa->ifa_addr == NULL || ifa->ifa_addr->sa_family != AF_PACKET) {
      continue;
    }

    if (check_wireless(ifa->ifa_name)) { / /we want only wireless interfaces
      //getWIAdress(ifa->ifa_name, host);
      getnameinfo(ifa->ifa_addr, (ifa->ifa_addr->sa_family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6), host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
      addWI(&WIHead, ifa->ifa_name, host);
    }
  }

  freeifaddrs(ifaddr);
}

I manage to solve the problem with another function I created but I can't understand why I get junk values using the getnameinfo()
My other function that solves the problem:
void getWIAdress(char *name, char *host) {
   int fd;
   struct ifreq ifr;

   fd = socket(AF_INET, SOCK_DGRAM, 0);

   /* I want to get an IPv4 IP address */
   ifr.ifr_addr.sa_family = AF_INET;

   /* I want IP address attached to specified name */
   strncpy(ifr.ifr_name, name, IFNAMSIZ-1);

   ioctl(fd, SIOCGIFADDR, &ifr);

   close(fd);

   /* copy result */
   strcpy(host, inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr));
}

Screenshot of the junk values:

A: The problem was in this condition:
if (ifa->ifa_addr == NULL || ifa->ifa_addr->sa_family != AF_PACKET)

We have to change AF_PACKET with AF_INET. This will also allow us to bypass virtual interfaces generated by airmon-ng from aircrack-ng package.
With the above fix we also don't have to check for AF_INET in getnameinfo() as we stick to IPv4 adresses.
getnameinfo(ifa->ifa_addr,sizeof(struct sockaddr_in), host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);


text:
Q: creating multiple new mutate columns in dplyr iteratively - latitudes and longitudes I have a list of latitudes and longitudes (each row contains a labeling number, 2 points, which form a line between them), and I am trying to find the distance from one of the endpoints in each row to the line created by every other row in the list. I am using the geosphere(dist2gc) package and dplyr. I am trying to do it through looping (because I cannot figure out how to get lapply to do it), and I want to create a new column with the distances for each comparison (so if I start with 10 rows, I will compare 10 times 10 and have 10 new columns with the distances to the lines in each row). The output if I start with a 10x8 data.frame would be a 10x18 data.frame.
The temporary column name is not working. Please help!
Can anyone help me come up with the way to make variable naming work, or other approaches to do this?
dist <- function(df){
 idx <- seq(1, nrow(df)) # create index values
 namelist <- df[,2] # extract name list for new columns
  for (i in idx){
   templon <- df[i,3] # pull comparison value point for lat and lon
   templat <- df[i,4]
   tempcoln <- namelist[i]
   df <- mutate(df, !! tempcoln := dist2gc(cbind(Longitude1, Latitude1),
     cbind(Longitude2, Latitude2), cbind(templon, templat), r=radius,
     sign=FALSE))
  }
  return(df)
}


text:
Q: How to handle the case when input to reduce is hash rather than array of hashes I have an incoming input which is sometimes an array of hashes and sometimes its just an individual hash.
hsh = {"property"=>[{"name"=>"first_name", "value"=>"Joe"}, {"name"=>"last_name", "value"=>"Doe"}]}

or
hsh = {"property"=>{"name"=>"Foo", "value"=>"Bar"}}

From this input I am trying to generate a hash with name as key and value and as value, something like this:
hsh['property'].reduce(HashWithIndifferentAccess.new) do |scan, kv_pair|
  scan.merge kv_pair['name'] => kv_pair['value']
end

Giving:
{"first_name"=>"Joe", "last_name"=>"Doe"}

This works well when hsh['property'] is an array of hashes but fails with the following error:
TypeError: no implicit conversion of String into Integer

when it's just an hash.
How do I handle the reduce on hsh['property'] so it handles the case when input to it is hash rather than array of hashes?

A: It's easy to ensure something being an array. You don't need if-else. Just wrap it in a new array, then flatten that array 1 level down. I have to admit that this is not very performant, but I don't care if what I originally want to do is O(n) or higher (like mapping, reducing, sorting, whatever that requires traversing the array at least once). I won't go this way if what I originally want to do is O(log(n)) or lower (like binary search).
[hsh['property']].flatten(1).reduce(HashWithIndifferentAccess.new) do |scan, kv_pair|
  scan.merge kv_pair['name'] => kv_pair['value']
end

A: The first thing to fix is to get rid of merge which creates an intermediate Hash each time through the loop. That's a lot of garbage to collect. The second thing is to use the simpler each_with_index method that doesn't require chaining. This way you can just add data:
hsh['property'].each_with_object(HashWithIndifferentAccess.new) do |kv_pair, scan|
  scan[kv_pair['name']] = kv_pair['value']
end

This will work so long as property has a series of Hash objects in an array. If you have just one you'll need to special case that:
case hsh['property']
when Hash
  HashWithIndifferentAccess.new(
    hsh['property']['name'] => hsh['property']['value']
  )
when Array
  hsh['property'].each_with_object(HashWithIndifferentAccess.new) do |kv_pair, scan|
    scan[kv_pair['name']] = kv_pair['value']
  end
else
  # Uh-oh, you've got to handle this case of something random.
end

A: I'd convert the incoming parameter to an array of a single hash, then proceed:
def foo(aoh)
  aoh = [aoh] unless Array === aoh

  aoh # return it so we can see it's been changed

  # do stuff with the AoH
end

foo({a:1}) # => [{:a=>1}]
foo([{a:1},{b:2}]) # => [{:a=>1}, {:b=>2}]

Once it's an array of a single hash, or multiple hashes, you can iterate over the contents of the array with the same code.
If you are responsible for generating the single hash or an array of hashes, you should always generate the same type of object, an array of hashes, which makes it easier for you to deal with it. If you don't, then convert it to the same type of object and move on.

A: As you are using rails, there is a dedicated method for ensuring something is an array - Array#wrap. Also note that your use of #reduce is considered unindiomatic and you should use #each_with_object instead.
Here is a possible solution:
Array.wrap(hsh['property']).map { |kv| [kv['name'], kv['value']] }.to_h

If you are using ruby 2.3.0+, you can even take advantage of the cool new Hash#to_proc:
Array.wrap(hsh['property']).map { |kv| ['name', 'value'].map(&kv) }.to_h

If you insist, you can add the #with_indifferent_access at the end.


text:
Q: Powershell script to count files in a single folder and output count to a log file if the files exceed a set number 'I need this to loop every 20 seconds for about 14 hours a day.  This is what I have so far, but I am having some issues with the loop and output.'

        $timeout = New-TimeSpan -Hours 14
        $sw = [diagnostics.stopwatch]::StartNew()
        $count = (Get-ChildItem -Path 'D:\folder' | Measure-Object).count

        <# Loop condition check every 20 seconds until timeout #>
        While ($sw.elapsed -lt $timeout){
        If ($count -gt 30)
        {
        "$([datetime]::Now) $count" | Out-File C:\temp\file_count.log -Append
        }
        start-sleep -Seconds 20
        }

A: I think your issue is that your count of filer is only done once, outside your while loop.
Move the $Count =  right under the while statement, and I think your issue is solved


text:
Q: How to put stuff in the margin every first line with the listings package? I am writting a book and I use the listings package to type some matlab code. I would like to highlight every code block with an arrow or whatever hanging in the margin at the first line. Moreover The code should be indented.
More specifically, I would like to define a listings environment, say 'matlabcode', so that the latex code
  \documentclass{article}
\usepackage{listings}
\usepackage{lipsum}

\lstnewenvironment{matlabcode}{}{}

\begin{document}
\lipsum[1]
\begin{matlabcode}
>> plot(sin(1:10))
more matlab code
more matlab code
\end{matlabcode}
\end{document}

gave something like

where the arrow might be a latex symbol, a pgf/tikZ picture, etc.

A: You can alayws use tikz, and if you allow for an optional parameter to the matlabcode environment you can change the style as desired on  a per use basis:

Code:
\documentclass{article}
\usepackage{tikz}
\usepackage{listings}
\usepackage{lipsum}

\newcommand{\Arrow}[1][]{\tikz [overlay, line width=3pt, red, ->,#1] \draw (0,0) -- (1,0);}%

\lstnewenvironment{matlabcode}[1][]{%
    \smash{\raisebox{-3.5ex}{\Arrow[xshift = -1.2cm,#1]}}%
}{}

\begin{document}
\lipsum[1]
\begin{matlabcode}
>> plot(sin(1:10))
more matlab code
more matlab code
\end{matlabcode}

\begin{matlabcode}[blue, line width=4pt, -latex]
>> plot(sin(1:10))
more matlab code
more matlab code
\end{matlabcode}
\end{document}


text:
Q: sending bitmaps over tcp in c# iam trying to send an image continously but somehow it is not working. the problem is,that sometimes when the receiver tries to read the size into the string it reads some unknown 6 bytes. I dont know where they come from because i thougth that the networkstream is empty when all the bytes are read.
/// <summary>
/// This is the class that captures the screen and sends it
/// </summary>
public class TCPClient
{
    TcpClient me;
    bool lauf = true;
    NetworkStream ns;
    Thread mainThread;
    int ind = 0;

    public TCPClient()
    {
        mainThread = new Thread(new ThreadStart(sendThread));
        mainThread.Start();
    }

    public void sendThread()
    {
        try
        {
            me = new TcpClient("127.0.0.1",16500);
            ns = me.GetStream();
            while (lauf)
            {
                MemoryStream tempMS = this.getScreen();
                byte[] package = tempMS.ToArray();
                String tempS = "" + package.Length;
                byte[] tempBS = System.Text.Encoding.UTF8.GetBytes(tempS);
                ns.Write(tempBS, 0, tempBS.Length);
                ns.Write(package, 0, package.Length);
                Console.WriteLine("Paket gesendet " + package.Length);
                //package = null;
                Console.WriteLine("Memoryuse: " + Convert.ToDouble(((Process.GetCurrentProcess().WorkingSet64))/1024)/1024);
                Thread.Sleep(1000);
                //Die ms müssen für die Steuerung evtl runtergeregelt werden,da sonst eine komfortable steuerung nicht möglich ist
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            Console.ReadKey();
            mainThread.Abort();
            ns.Close();
            me.Close();
        }
    }

    public MemoryStream getScreen()
    {
        Bitmap bitmap = new Bitmap(SystemInformation.VirtualScreen.Width, SystemInformation.VirtualScreen.Height);

        using (Graphics graphics = Graphics.FromImage(bitmap))
        {
            graphics.CopyFromScreen(0,0,0,0,bitmap.Size);
            Cursors.Default.Draw(graphics,new Rectangle(Cursor.Position,Cursor.Current.Size));
            graphics.Dispose();
        }

        MemoryStream memoryStream = new System.IO.MemoryStream();
        bitmap.Save(memoryStream,System.Drawing.Imaging.ImageFormat.Png);

        bitmap.Dispose();
        //memoryStream.Flush();
        memoryStream.Position = 0;
        return memoryStream;
    }

    public void setLauf(bool pLauf)
    {
        lauf = pLauf;
    }
}

public class TcpReceiver
{
    private TcpClient me;
    private MainForm MF;
    private bool lauf = true;
    private Thread recieveThread;

    public TcpReceiver(MainForm tMF)
    {
        MF = tMF;
        recieveThread = new Thread(new ThreadStart(recieveImage));
        recieveThread.Start();
    }

    public void recieveImage()
    {
        try
        {
            TcpListener tempListener = new TcpListener(IPAddress.Any,16500);
            tempListener.Start();
            me = tempListener.AcceptTcpClient();
            //MF.newClient(me.Client.AddressFamily.ToString());
            NetworkStream ns = me.GetStream();

            while(lauf)
            {
                if (ns.DataAvailable)
                {
                    byte[] tempSA = new byte[6];
                    ns.Read(tempSA, 0, tempSA.Length);
                    String tempS = System.Text.Encoding.UTF8.GetString(tempSA);
                    int size = Int32.Parse(tempS);
                    byte[] tempBA = new byte[size];
                    ns.Read(tempBA, 0, tempBA.Length);

                    MemoryStream tempMS = new MemoryStream(tempBA);
                    Bitmap tempBitmap = new Bitmap(tempMS);
                    MF.showData(tempBitmap);

                    Thread.Sleep(100);
                }
            }
        }
        catch(Exception e)
        {

        }
    }

    public void setLauf(bool tLauf)
    {
        lauf = tLauf;
    }
}


text:
Q: $cordovaInAppBrowser.open works with _blank on iOs and _self on Android I have built an ionic app.
On android, I have been using the following code:
$cordovaInAppBrowser.open(url, '_self', options)
            .then(function (event) {
                // success
                console.log('success --> ' + event);
            })
            .catch(function (event) {
                // error
                console.log('error --> ' + event);

            });

Further on I have:
$rootScope.$on('$cordovaInAppBrowser:loadstart', function (e, event) { ..}

I found that for Android, the above loadStart event is fired, however on iOS I had to change the '_self' string to '_blank' for it to work (i.e. the loadstart event then fires).
Any reason why this is happening?
I now have to detect if I am on an iOS device and pass the correct string (_blank or _self).


text:
Q: Android camera intent in a fragment i have a problem with my first app!
My app is an navigation drawer. It has 2 fragmets where i show diferentes this.
- user fragment where i show user's info
- action screen where the user can use the camera and take a photo.
In user fragment i dont have any problem, but in camera fragment i have many problems!
I did a fragment where i have a button and an imageview (camera_image.xml)
And, CameraImage.java in the java directory.
Then, a put the code:
CameraImagen.java:
public class CameraImage extends Fragment {

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 1888;
Button button2;
ImageView imageView2;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    final View rootView = inflater.inflate(R.layout.camera_image,
            container, false);

    button2 = (Button) rootView.findViewById(R.id.button);
    imageView2 = (ImageView) rootView.findViewById(R.id.imageview);

    button2.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(intent,
                    CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);

        }
    });

    return rootView;

}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
        if (resultCode == Activity.RESULT_OK) {

            Bitmap bmp = (Bitmap) data.getExtras().get("data");
            ByteArrayOutputStream stream = new ByteArrayOutputStream();

            bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
            byte[] byteArray = stream.toByteArray();

            // convert byte array to Bitmap

            Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0,
                    byteArray.length);

            imageView2.setImageBitmap(bitmap);

        }
    }
}
}

camera_image.xlm
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.diegoperez.myfirstapp.CameraImage">

<!-- TODO: Update blank fragment layout -->
<TextView android:layout_width="match_parent" android:layout_height="match_parent"
    android:text="@string/hello_blank_fragment" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New Button"
    android:id="@+id/button2"
    android:layout_gravity="center_horizontal|bottom" />

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/imageView2"
    android:layout_gravity="center" />

in Manifest.xlm, i add:
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

In the navigation drawer java class, i add:
CameraImage fragment = new CameraImage();
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();

In the camera_image.java i have this problem:

Then i tried to modify this .java and i wrote this:
public class CameraImage extends Fragment {

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 1888;
Button button2;
ImageView imageView2;

public CameraImage() {
    // Constructor vacío
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.camera_image, container, false);

    return rootView;
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
        if (resultCode == Activity.RESULT_OK) {

            Bitmap bmp = (Bitmap) data.getExtras().get("data");
            ByteArrayOutputStream stream = new ByteArrayOutputStream();

            bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
            byte[] byteArray = stream.toByteArray();

            // convert byte array to Bitmap

            Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0,
                    byteArray.length);

            imageView2.setImageBitmap(bitmap);

        }
    }
}

public void tomar_foto (View view){
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
}

the app runs, i can open the fragment with the button but when i push it, the app crash and close itseft.
I need help please...two days with this problems!
thanks a lot!

A: Have you imported :
import android.view.View;
or
import android.view.View.OnclickListener ?
Also try to change the onClickListener() for this one :
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent,
                CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);

}
});


text:
Q: Kendo-ui grid don't refreshed after creating or updating a row My kendo grid don't get refreshed after a edit or create a new row.I have called a angularJS service for CRUD operation.
Here's the controller
app.controller("roadInventoryCtrl", function ($scope, services) {
$scope.gridOptions = {
    columns: [
        {
            field: "RoadCode",
            title: "Road Code",
            width: "",
            attributes: { class: "ob-right" }
        },
        {
            field: "Remarks",
            filterable: false
        },
        {
            command: [
                {
                    name: "edit",
                    template: "",
                    text: " "

                },
                {
                    name: "destroy",
                    template: "",
                    text: " "
                }
            ],
        }
    ],

    editable: 'inline',
    toolbar: ["create"],
    pageable: true,

    dataSource: {
        pageSize: 25,
        transport: {
            read: function(e) {
                services.getRoadInventroy()
                    .then(function success(response) {
                        e.success(response.data);
                    }, function error(response) {
                        alert('something went wrong');
                        console.log(response);
                    });
            },
            update: function(e) {
                services.updateRoadInventory(e)
                    .then(function success(response) {
                        e.success(response.data);
                    }, function error(response) {
                        console.log(response);
                    });
            },

            destroy: function(e) {
                services.destroyRoadInventory()
                    .then(function success(response) {
                            e.success(response.data);
                        }, function error(response) {
                            console.log(response);
                        }
                    );

            },
            create: function(e) {
                services.createRoadInventory(e)
                    .then(function success(response) {
                            console.log(response);
                        },function error(response) {
                            console.log(response);
                        }
                    );
            }
        },
        schema: {
            model: {
                id: "RoadCode",
                fields: {
                    RoadCode: {
                        editable: false
                    }

                }
            }
        }
    },
    sortable: true,
    selectable: "row",

    filterable: {
        extra: false,
        operators: {
        string: {
            startswith: "Starts with",
            contains:"Contains"

         },
         number: {
         }
       }
    }

    }

});

And the service is
app.service('services', ['$http', function ($http) {
var result;
this.getRoadInventroy = function () {
    result = $http.get("/api/InventoryService").success(function (data) {
        result = (data);
    }).error(function () {
        alert("Not hiting the Api Controller");
    });

    return result;
};

this.createRoadInventory = function (e) {
    //alert(JSON.stringify(e));
    //alert(e.data);
    $http.post("/api/InventoryService",e.data).success(function () {
    }).error(function() {
        alert("Not Hitting the POST of API but hitting the services");
    });
};
this.destroyRoadInventory = function () {

};
this.updateRoadInventory = function (e) {
    $http.put("/api/InventoryService", e.data).success(function () {
    }).error(function (){
        alert("Not Hitting the put of API but hitting the services");
    });
};

}]);

I have post it on Kendo forum but don't get appropriate answer.

A: Just put the result in var and return it.
        this.updateRoadInventory = function(e) {
        update = $http.put(rootUrl + "InventoryService", e.data).success(function() {
        }).error(function() {
            alert("Not Hitting the put of API but hitting the services");
        });
        return update;
    };


text:
Q: How to unwrap list with access variables? I have a list with access variables
letters <- list(A = "a", B = "B")

# $A
# [1] "a"
#
# $B
# [1] "B"

and I would like to transform this into
letters <- list("a", "B")
# [[1]]
# [1] "a"
#
# [[2]]
# [1] "B"

How can i achieve this ? I've tried
unlist(letters)

but it didn't work.


text:
Q: Get gps provider setting mode How can I get the gps location method?
The image shows gps only is selected in the location setting. Is there any way I can get this setting in cn1?

Code in cn1:
Location locationn = LocationManager.getLocationManager().getCurrentLocation();

A: I'm not sure if this is what you are looking for but isGPSEnabled() is available in LocationManager. Notice it might throw a runtime exception on unsupported platforms.
You can use native interfaces if it's exposed to Android native but since it's Android specific it's not really a part of the API.
Notice the Location class provides getAccuracy() if that helps.


text:
Q: Create managed form Dynamics CRM I'm building managed solution and created a new form on account. This form is unmanaged and because of that this managed solution can't be deleted from end users crm. Is there a possibility to create managed form in dynamics crm?
I didn't find it in documentation and saw no property in form xml that differ my form from managed ones.
I'm using Dynamics CRM 2016 version.

A: When you are working on your solution in your dev environment, all components will be unmanaged.  When you export your solution you are given the option of exporting as managed or unmanaged; choosing managed will result in all components in your solution being managed.
You should distribute the appropriate version based on the need.  For example, to move to a new dev environment, you would import the unmanaged version; when distributing your solution to clients, use the managed version.
Any unmanaged component can be deleted from an environment, so if you are unable to delete your managed solution from an environment, it's probably because of something unrelated to the unmanaged form. If the error message you are getting specifically references the unmanaged form, you could be running into a platform bug (we've encountered quite a few when importing/upgrading/deleting managed solutions).


text:
Q: Cohomological dimension of closed $G$-invariant subspaces on homology manifolds with a group action Suppose  $G$  is a compact topological  group acting  on an $m$-homology  manifold $M$ over some  ring $R$  by homeomorphisms.
Assume  that  the  action  of  $G$ is effectively  finite on a closed $G$-invariant subspace $A$ such that $A$ does not  contain a  connected component of $M$.
(Recall  that  an  effectively  finite  action means that  the  quotient  group  of  $G$ by the  ineffective kernel $K$  is finite. In  the  case  I  am  interested,  one  can  assume $G/K \cong \mathbb{Z}/k$)
Does it follow  that $H^{m}(A/G,R)=0$?


text:
Q: What is wrong with the resized memoir page? I want to make a cover page (for an eBook-like format) with a background image, the size (and aspect ratio) of which is not known in advance. I would like to cover the page with the image (the best way, i.e either the max. width or max. height, but no white stripes), then put some texts in boxes on top of it. Below you find an MWE and its output.

*

*The wallpaper [Golden ratio] has some margin (both vertical and horizontal)

*The box (Red text) of width=\paperwidth at north, has a right side margin and a top margin

*The box [Green text] of width=\textwidth at south west, has no bottom margin, but has right margin

*The box [Gray text] of width=\paperwidth at east, is positioned at some foreign place.

*The box [Blue text] at west, seems to have a vertical position different from the vertical position of box [Gray text], positioned at east

*It looks like \paperwidth is not the width of the paper
What am I doing wrong?

 \documentclass{memoir}
\usepackage{mwe}
\usepackage{wallpaper}
\usepackage{tikz}
\usepackage{graphicx}
\setstocksize{4.8in}{3.6in}
\settrimmedsize{4.65in}{3.45in}{*}
\setlrmarginsandblock{0mm}{2mm}{*}
\setulmarginsandblock{7mm}{1mm}{*}
\setheaderspaces{*}{2mm}{*}
\setheadfoot{.7\baselineskip}{0\baselineskip}
\checkandfixthelayout[fixed]
\renewcommand{\maketitle}
{
    \CenterWallPaper{.98}{example-image-golden}
\tikz[remember picture,overlay]%
\node[fill=gray,font=\LARGE\bfseries,text=black,%
minimum width=\paperwidth,minimum height=2em,anchor=north]%
at (current page.east){Gray text};
\tikz[remember picture,overlay]%
\node[fill=blue!50!white,font=\LARGE\bfseries,text=black,%
minimum width=.5\paperwidth,minimum height=2em,anchor=west]%
at (current page.west){Blue text};
\tikz[remember picture,overlay]%
\node[fill=green!50!black,font=\LARGE\bfseries,text=black,%
minimum width=\textwidth,minimum height=2em,anchor=south west]%
at (current page.south west){Green text};
\tikz[remember picture,overlay]%
\node[fill=red!50!black,font=\LARGE\bfseries,text=black,%
minimum width=\paperwidth,minimum height=2em,anchor=north]%
at (current page.north){Red text};
}
\begin{document}
\maketitle
\end{document}


text:
Q: Get all taggable_friends picture with FBSDKGraphRequest in swift I am trying to get all my taggable_friends profil picture in swift. With my code, I can obtain my taggable_friends' name, but I don't know how I can get their profil picture... Any idea how? Thanks!!!
var fbRequest = FBSDKGraphRequest(graphPath:"/me/taggable_friends", parameters: nil);
                fbRequest.startWithCompletionHandler { (connection : FBSDKGraphRequestConnection!, result : AnyObject!, error : NSError!) -> Void in

                    if error == nil {

                        var resultdict = result as! NSDictionary
                        var data : NSArray = resultdict.objectForKey("data") as! NSArray

                        for i in 0..<data.count {
                            let valueDict : NSDictionary = data[i] as! NSDictionary
                            let id = valueDict.objectForKey("id") as! String
                            let name = valueDict.objectForKey("name") as! String
                            // let url = valueDict.objectForKey("url") as! String  -- is not working

I already saw this topic: How can I retrieve friend's picture through FBRequest in swift but I still don't undersand how to do it...

A: Not sure if this is the most effective way to do this, but the code works:
      func returnUserData()
{
    let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me/taggable_friends?", parameters: nil)
    graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in

        if ((error) != nil)
        {
            // Process error
            println("Error: \(error)")
        }
        else
        {
            println("fetched user: \(result)")

            var resultdict = result as! NSDictionary
            var data : NSArray = resultdict.objectForKey("data") as! NSArray

            for i in 0..<data.count {
                let valueDict : NSDictionary = data[i] as! NSDictionary
                let id = valueDict.objectForKey("id") as! String
                let name = valueDict.objectForKey("name") as! String
                let pictureDict = valueDict.objectForKey("picture") as! NSDictionary
                let pictureData = pictureDict.objectForKey("data") as! NSDictionary
                let pictureURL = pictureData.objectForKey("url") as! String
                println("Name: \(name) URL: \(pictureURL)")
            }

        }
    })
}

A: Have a look at

*

*https://developers.facebook.com/docs/graph-api/reference/user-taggable-friend/
The request should be something like this
graphPath:"/me/taggable_friends?fields=id,name,picture"


text:
Q: Check if group contains same value in Pandas I am curious if there is a pre-built function in Pandas to check if all members of a group (factors in a column) contain the same value in another column.
i.e. if my dataframe was similar to below it would return an empty list.
Col1    Col2
2        A
2        A
0        B
0        B

However, if my dataframe appeared as such (notice the 1 in Col1):
Col1    Col2
2        A
2        A
0        B
1        B

Then the output would be a list containing the object "B" since the group B has different values in Col1.

A: Use groupby nunique and index of unique values > 1
a = df.groupby('Col2').Col1.nunique() > 1
a[a].index.tolist()

Output:
['B']

A: Use DataFrame.duplicated for boolean mask and convert column Col2 to list:
a = df.loc[~df.duplicated(keep=False), 'Col2'].unique().tolist()
print (a)
[]

And for second data:
a = df.loc[~df.duplicated(keep=False), 'Col2'].unique().tolist()
print (a)
['B']

Alternative with DataFrame.drop_duplicates:
a = df.drop_duplicates(keep=False)['Col2'].unique().tolist()
print (a)
['B']


text:
Q: ASP.NET MVC 3.0 Update element content/html of the form using Partial action and jQuery ajax I have Partial A1 inside Partial A.
I need to render my Partial view A1 on button A1B click.
For that i have an partial view action with parameter type of model of Partial view A (because there is some dependencies on A)
public PartialViewResult A1Partial(A model)
{
    //Getting my deserialized model here successfully

    //doing changes in the model collections

    return PartialView("A1Partial", model);
}

I have onclick function to call my A1Partial partial action:
$(document).ready(function () {
    $("#A1B").click(function () {

        dataString = $("#myForm").serialize();

        $.ajax({
            type: "POST",
            url: "/Controller/A1Partial",
            data: dataString,
            dataType: "json",
            success: function (data) {
                            //not working here

                            $("#myDiv").html("");
                $("#myDiv").html(data);
            }

        });

        return false;
    });
});

My call from jQuery ajax working correctly and dataString getting deserialized in controller without any issues.
But i am didn't get anything in $("#myDiv").append(data); looks like the html didn't came through.
What changes i need to made to make it work?

A: You indicate that you expect a JSON response type:
dataType: "json"

And yet you try to use it as if it was HTML:
$('#myDiv').append(data);

So remove this dataType: 'json' from the AJAX request and in the success callback the data variable will represent the HTML returned by the A1Partial.

A: You have to render the partial view on the server and then send the HTML result via Json like this:
public static class Renders
{
    public static string RenderPartialView(this Controller controller, string viewName, object model)
    {
        if (string.IsNullOrEmpty(viewName))
            viewName = controller.ControllerContext.RouteData.GetRequiredString("action");

        controller.ViewData.Model = model;
        using (var sw = new StringWriter())
        {
            ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
            var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
            viewResult.View.Render(viewContext, sw);

            return sw.GetStringBuilder().ToString();
        }
    }
}

In the controller:
public JsonResult A1Partial(A model)
{
    //Getting my deserialized model here successfully

    //doing changes in the model collections

    return Json(new
    {
        Html = this.RenderPartialView("A1Partial", model)
    }, JsonRequestBehavior.AllowGet);
}

Then in the JQuery code:
$("#myDiv").html(data.Html);


text:
Q: Why is the set of diagonal matrices not an ideal? Saw this fact in my lecture notes, but can't quite seem to work out why this is the case. Its clearly a subgroup of $M_n(\Re)$ and it seems that when multiplied by any element of $M_n(\Re)$ a diagonal matrix will result in a diagonal matrix. Definitely missing something insanely simple and trivial here but cant quite work it out.

A: What you're missing is that the product of a diagonal matrix with an arbitrary matrix is almost never a diagonal matrix. For instance, suppose that your diagonal matrix is the identity matrix and that the other matrix is any non-diagonal matrix.

A: Actually, when you  left-multiply an $n\times n$ matrix  by the diagonal matrix $D=\operatorname{diag}(a_1, a_2,\dots,a_n)$, for each $i=1,\dots, n$, you multiply  row $i$ of the matrix by $a_i$, and when you right-mutiply it by $D$, it's column $i$ you multiply  by $a_i$.


text:
Q: How to create Alignment Object using alignment API I have a local alignment.rdf file and using alignment API library here I want to create Alignment object and convert it to .owl file.
My code is here:
AlignmentParser aparser = new AlignmentParser(0);
Alignment result = aparser.parse( new File( "Ontologies/alcomo-alignment.rdf" ).toURI() );
File merged1 = new File( "Ontologies/final_alignment.owl");
PrintWriter writer1 = new PrintWriter ( new FileWriter( merged1, false ), true );
AlignmentVisitor renderer1 = new OWLAxiomsRendererVisitor(writer1);
result.render(renderer1);
writer1.flush();
writer1.close();

but I face with this error:
OWLAxiomsRenderer: cannot render simple alignment. Need an ObjectAlignment

A: Replace:
result.render(renderer1);

by
ObjectAlignment oresult = ObjectAlignment.toObjectAlignment(result);
oresult.render(renderer1);

Discussed in: http://alignapi.gforge.inria.fr/builtin.html
Note that for this purpose, the URI of the ontologies in the initial file must be dereferenceable.


text:
Q: JQuery bind() only tiggered once I have the following jquery script that is attached to button elements. At the moment, I'm only testing with one button but the idea is that clicking on any button will read the id of the button that is then used as part of the URL to call back to the web server. The button I'm testing with is on the main page i.e. visible as you arrive on the site. However even the main page (and the button itself) is loaded via an AJAX call! Also the button is part of the #content element that the script itself empties as shown below.
The behaviour I'm seeing:
- If I stay on the main page and click on the button, it works. Then if I navigate back, it doesn't work any more.

*

*If I arrive on the site and navigate away from the main page and go back, the button won't work again.

The pattern seems to be that the script won't run if the button is ever taken out of the DOM.
$(document).ready(function(){
    $("button").bind('click', function(){
          var route = element.attr("id");
          $.ajax(
          {
            type: "GET",
            url: '/' + route,
            dataType: "html",
            async: true,
            success: function(data)
            {
                $( "#content" ).empty();
                $( "#content" ).append( data );
            }
           });
    });
});

I'm new to JQuery and AJAX and even though I'm sure it's a trivial issue I haven't been able to find the answer online.
I'm using Chrome and JQuery 2.1.1.
Many thanks
Update: also tried with $('body button').on('click'... as suggested below but getting the same behaviour.

A: You add the handlers to the DOM element, meaning your $.bind() is run once on whatever elements are present against it's selector. Once you remove an element, it's event handlers get removed too.
If you want to continue handling that event, re-apply the event handler when you re-add those elements, or use $.on() through a parent using the second selector option (as long as the parent is not also removed). This is called event delegation. (The precursor to $.on() was called $.delegate(), but was changed for syntactical reasons.)
$(document).on('click', 'button', func...)

Make sure and use the second argument. Also don't apply handlers to body, it is in general a bad idea; use document if you must, or preferentially a common parent closer in the DOM to your element (so you don't have unnecessary event management going on).


text:
Q: Getting a "No parameterless constructor defined" error, not sure why For some reason one particular AJAX call of mine is getting a "No parameterless constructor defined" error. Here's the code:
CallAndReplace(JSON.stringify(model), url, $("#panel"));

function CallAndReplace(data, url, replace) {
    $.ajax({
        url: url,
        type: "post",
        contentType: "application/json; charset=utf-8",
        data: data,
        success: function (result) {
            replace.html(result);
        },
        error: function (x, e) {
            if (x.status == 0) {
                alert('You are offline!!\n Please Check Your Network.');
            } else if (x.status == 404) {
                alert('Requested URL not found.');
            } else if (x.status == 500) {
                alert('Internal Server Error.');
            } else if (e == 'parsererror') {
                alert('Error.\nParsing JSON Request failed.');
            } else if (e == 'timeout') {
                alert('Request Time out.');
            } else {
                alert('Unknow Error.\n' + x.responseText);
            }
        }
    });
}

'model' is a viewmodel in my MVC-3 view that I've converted into a Javascript object. 'url' is the url generated via the '@Url.Action("Action", "Controller")' method. And $("#panel") is the div area that gets replaced by a partial view returned by the controller action.
When I try to debug the project, it never gets to the controller action. When I created a dummy controller action with no parameters, it reaches there in debug mode. But I'm obviously sending data. I can see the data being posted in Firebug (although it's not structured for some reason) but apparently it's not being sent over and I don't know why.
I use CallAndReplace 20 other times in my code for other uses and it has never given me this problem. I am completely at a loss as to why.
Edit: Here's the viewmodel class that I'm sending to the view:
public class AwardsEdit
{
    public List<AwardsViewModel> Awards { get; set; }
    public int TitleId { get; set; }

    public List<Tuple<int, string>> Participants { get; set; }
    public List<Award1> AllAwards { get; set; }
    public List<Tuple<int, string>> AllAwardCompanies { get; set; }
}

And the controller action I'm trying to call:
public PartialViewResult SaveAwards(AwardsEdit award)
    {
        if (ModelState.IsValid)
        {
            bool updated = _translator.UpdateAward(award);
            if (updated)
            {
                return PartialView("Details", _translator.GetAwards(award.TitleId));
            }
            //else error
            ModelState.AddModelError("", "Award data was not saved.");
        }
        //on error, load meta data
        var data = _translator.GetAwards(award.TitleId, true);

        award.Participants = data.Participants;
        award.AllAwards = data.AllAwards;
        award.AllAwardCompanies = data.AllAwardCompanies;

        return ViewAwards(award.TitleId);
    }

The controller itself doesn't have a parameterless constructor method and I am using dependency injection, but I have other AJAX calls that call various actions in that controller and they work fine. I don't know why this one isn't working.

A: The error is probably referring to the type of one of your action's parameters (not the Controller, as others have suggested).
MVC cannot populate the parameter if it cannot first be constructed.
For example, you can get the same error like this:
public class ParameterConstructor
{
    public ParameterConstructor(string parameter){
    }
}

public class MyController : Controller {
    public ActionResult Test(ParameterConstructor model) {
        return "This action will not be reached";
    }
}

So you need to make sure that your model type has a parameterless constructor.
Update
In response to your updated code, it is true that your ViewModel constructor is parameterless.
However, you have a list of Tuple<int, string>.  The documentation says that Tuple does not have a parameterless constructor.   That's the problem -- Tuple is designed to be read-only.  Perhaps you could use a KeyValuePair<> instead?

A: If you want to pass JSON to your server, you have to pass it as the value of a parameter.  Just setting the "data" property on the AJAX call won't work.
You could use:
    data: { theJson: data },

then your server would see a parameter "theJSON" and could decode the value of that to get your data structure back.

A: .stringify is the reason it is not structured.  That call will take your data, add a [ to the front,  a ] to the back, and then create a comma delineated string of the data you sent.  Perhaps your controller expects an object or model and is instead getting a string.

A: I would verify that the Controller referenced in your @Url.Action("Action", "Controller") actually has a parameterless constructor.  Or it could be that you do not expect there to be an parameterless constructor in which case you must make sure that your IoC Container is properly configured to inject the necessary dependency.
It could also be the ViewModel itself in which case you should ensure that a parameterless (default) constructor exists on the ViewModel type.
Example:
public class Example
{
    // this is a parameterless constructor
    public Example()
    {
        // ...
    }
}

A: public class MyController : Controller
{
    // make sure constructor has default parameterless constructor
    public MyController() {}
}

A: That error message isn't the greatest -- it sends people to one of the more likely causes of your controller class not being instantiated. But it really should read "Controller construction and initialization failed. One likey cause is that there is not a parameterless constructor but you might have screwed it up some other way. Inner exception was . . ."
Best bet to catch it would be to run your code in debug mode, Visual Studio should pop you over to the exception when it occurs.

A: Since you're using Dependency Injection you'll need to dig in to your code to figure out why the dependency injector isn't creating an instance of the controller with the paramteres it requires.


text:
Q: macos wakes up from sleep very slowly when internet connection is also slow I have the latest macos (BigSur or Catalina I think) on a new Macbook Air.
When I have poor wifi reception (e.g. I go to garden and I'm too far from the rooter) or if the internet connection is slow then when I open the lid of the mac I see the screen later than normally and the keyboard and mouse are unresponsive for a minute - sometimes even mac notices that and asks if I would like to connect a bluetooth keyboard.
Everything is normal when I'm on a normal internet connection.
SO basically, WTF? I heard that Apple introduced some software that validates hashes of running programs before they are allowed to run, and it does it over the internet. So it sounds like this is the issue.
Any solutions to that (besides speeding up the connection)?
EDIT: OK, now I know, this is called notarization and not only I have such issues: https://sigpipe.macromates.com/2020/macos-catalina-slow-by-design/
Are there any workarounds?