How to implement map function of Mongodb cursor in node.js (node-mondodb-native)

Question: I am trying to implement following MongoDB query in NodeJS
db.tvseries.find({}).map(function(doc){
    var userHasSubscribed = false;

    doc.followers && doc.followers.forEach(function(follower) {
            if(follower.$id == "abc") {
                userHasSubscribed = true;
            }
        });

    var followers = doc.followers && doc.followers.map(function(follower) {
            var followerObj;
            db[follower.$ref].find({
                    "_id" : follower.$id
                }).map(function(userObj) {
                        followerObj = userObj;
                    });
             return followerObj;
        });

    return {
            "id": doc.name,
            "userHasSubscribed": userHasSubscribed,
            "followers": followers || []
        };
})

Following is the db
users collection
{
     "id": ObjectId("abc"),
     "name": "abc_name"
},
{
     "id": ObjectId("def"),
     "name": "def_name"
},
{
     "id": ObjectId("ijk"),
     "name": "ijk_name"
}

tvseries collection
{
     "id": ObjectId("123"),
     "name": "123_name",
     "followers": [
        {
            "$ref": "users",
            "$id": ObjectId("abc"),
        },
        {
            "$ref": "users",
            "$id": ObjectId("def"),
        }
     ]
},
{
     "id": ObjectId("456"),
     "name": "456_name",
     "followers": [
         {
            "$ref": "users",
            "$id": ObjectId("ijk"),
        },
     ]
},
{
     "id": ObjectId("789"),
     "name": "789_name"
}

I am not able to figure out how to execute the above MongoDB query in NodeJS with the help of node-mongodb-native plugin.
I tried the below code but then I get TypeError: undefined is not a function at .map
var collection = db.collection('users');
collection.find({}).map(function(doc) {
   console.log(doc);
});

How to execute .map function in NodeJS?
Thanks in advance
Answer: I struggled with this for some time. I found that by adding .toArray() after the map function works.
You could even skip map and only add .toArray() to get all the documents fields.
  const accounts = await _db
    .collection('accounts')
    .find()
    .map(v => v._id) // leaving this out gets you all the fields
    .toArray();

  console.log(accounts); // [{_id: xxx}, {_id: xxx} ...]

Please take note that in order for map to work the function used must return something - your example only console.logs without returning a value.

The forEach solution works but I really wanted map to work.
Answer: I know that I'm pretty late but I've arrived here by searching on Google about the same problem. Finally, I wasn't able to use map function to do it, but using forEach did the trick.
An example using ES6 and StandardJS.
  let ids = []
  let PublicationId = ObjectID(id)
  feeds_collection
    .find({PublicationId})
    .project({ _id: 1 })
    .forEach((feed) => {
      ids.push(feed._id)
    }, () => done(ids))

Answer: To echo @bamse's anwer, I got it working with .toArray(). Here is an async example:
async function getWordArray (query) {
  const client = await MongoClient.connect(url)
  const collection = client.db('personal').collection('wordBank')
  const data = await collection.find(query).map(doc => doc.word).toArray()
  return data
}

Then I use it in my Express route like this:
app.get('/search/:fragment', asyncMiddleware(async (req, res, next) => {
  const result = await getWordArray({word: 'boat'})
  res.json(result)
}))

Finally, if you need a guide to async/await middleware in NodeJS, here is a guide: https://medium.com/@Abazhenov/using-async-await-in-express-with-node-8-b8af872c0016
Answer: map returns a cursor, toArray returns a Promise that will execute a cursor and return it's results. That may be an array of the original query find, limit etc. or a promise of an array of those result piped through a function.
This is typically useful when you want to take the documents of the cursor and process that (maybe fetch something else) while the cursor is still fetching documents, as opposed to waiting until they have all been fetched to node memory
Consider the example
let foos = await db.collection("foos")
    .find()
    .project({
        barId: 1
    })
    .toArray() // returns a Promise<{barId: ObjectId}[]>

// we now have all foos into memory, time to get bars
let bars = await Promise.all(foos.map(doc => db
    .collection("bars")
    .findOne({
        _id: doc.barId
    })))

this is roughly equivalent to
bars = await db.collection("foos")
    .find()
    .project({
        barId: 1
    })
    .toArray() // returns a Promise<{barId: ObjectId}[]>
    .then(docs => docs
        .map(doc => db
            .collection("bars")
            .findOne({
                _id: doc.barId
            })))

using map you can perform the operation asynchrounsly and (hopefully) more efficiently
bars = await db.collection("foos")
    .find()
    .project({
        barId: 1
    })
    .map(doc => db
        .collection("bars")
        .findOne({
            _id: doc.barId
        }))
    .toArray()
    .then(barPromises => Promise.all(barPromises)) // Promise<Bar[]>

The main point is that map is simply a function to be applied to the results fetched by the cursor. That function won't get executed until you turn it into a Promise, using either forEach or more sensibly, map


parsing json key-value in snowflake with key having a dots in it

Question: {
  "deviceLocale": "en_US",
  "deviceSerialNumber": "xxxxxxxxxx",
  "eventSource": "abc",
  "ext.user.browser": "Mobile Safari",
  "ext.user.browser.version": "1.0.4",
  "ext.user.device.family": "iPhone",
  "ext.user.os": "iOS",
  "ext.user.os.version": "1.3.0",
  "Timestamp": 158007896874 }

This is the sample json that I have..
Parsing in snowflake
```
select distinct
eve_id,
json_payload:ext.useragent.device.family::varchar as type,
json_payload:ext.useragent.os::varchar as osname,
json_payload:ext.useragent.os.version::varchar as os
from XYZ table, lateral flatten (input => json_payload)
```

But all these three fields are giving NULL values and I see the data in the json format. So I guess parsing is not right.  I know in snowflake while parsing if we use a dot or : then it refers to the nested key. But in my case I have a simple json with no nested keys.
Any idea?
Answer: firstly you can put the name in double quotes, like so:
SELECT parse_json('{
        "deviceLocale": "en_US",
        "deviceSerialNumber": "xxxxxxxxxx",
        "eventSource": "abc",
        "ext.user.browser": "Mobile Safari",
        "ext.user.browser.version": "1.0.4",
        "ext.user.device.family": "iPhone",
        "ext.user.os": "iOS",
        "ext.user.os.version": "1.3.0",
        "Timestamp": 158007896874 }') AS json_payload,
    json_payload:"ext.user.device.family"::varchar as type,
    json_payload:"ext.user.os"::varchar as osname,
    json_payload:"ext.user.os.version"::varchar as os;

gives:
JSON_PAYLOAD    TYPE    OSNAME  OS
{    "Timestamp": 158007896874,    "deviceLocale": "en_US",    "deviceSerialNumber": "xxxxxxxxxx",    "eventSource": "abc",    "ext.user.browser": "Mobile Safari",    "ext.user.browser.version": "1.0.4",    "ext.user.device.family": "iPhone",    "ext.user.os": "iOS",    "ext.user.os.version": "1.3.0"  }    iPhone  iOS 1.3.0

OR you can use the [''] format like json_payload['ext.user.os.version']::varchar as os which allow the avoidance of double quotes (in case you want to avoid that).
In you access SQL you have json_payload:ext.useragent.device.family::varchar but the useragent section is only user in your JSON. So that will give you trouble.
Also in your example you are using a LATERAL FLATTEN, but asking how to access the flattened members of the object you are flattening. So the flatten is not needed. But if you are want to flatting then you will get a row per top level item, at which point you would be want to filter the key.. but I suspect this is not what your trying to do. But if you are is a good idea to alias the flatten to help show the intention.
WITH jp AS (
    SELECT parse_json('{
      "deviceLocale": "en_US",
      "deviceSerialNumber": "xxxxxxxxxx",
      "eventSource": "abc",
      "ext.user.browser": "Mobile Safari",
      "ext.user.browser.version": "1.0.4",
      "ext.user.device.family": "iPhone",
      "ext.user.os": "iOS",
      "ext.user.os.version": "1.3.0",
      "Timestamp": 158007896874 }') AS json_payload
)
SELECT
    f.key,
    f.path,
    f.value
FROM jp, LATERAL FLATTEN (input => json_payload) f;

gives:
KEY PATH    VALUE
Timestamp   Timestamp   158007896874
deviceLocale    deviceLocale    "en_US"
deviceSerialNumber  deviceSerialNumber  "xxxxxxxxxx"
eventSource eventSource "abc"
ext.user.browser    ['ext.user.browser']    "Mobile Safari"
ext.user.browser.version    ['ext.user.browser.version']    "1.0.4"
ext.user.device.family  ['ext.user.device.family']  "iPhone"
ext.user.os ['ext.user.os'] "iOS"
ext.user.os.version ['ext.user.os.version'] "1.3.0"


Was there ever a time that you Spent Quest Points for Hints on Different Quests in Runescape?

Question: I specifically remember a time where there was this website you can go into and you were allowed to spend Quest points to receive hints to different quests you are currently on. Is this true, If so, what was the website/context, or is my old mind playing tricks on me?
Answer: What you're thinking of was QuestHelp, a system that helped players who were stuck during quests. The currency itself was not quest points, but another type of points where you get 4 a day:

Each player had 4 QuestHelp points, which were reset after 24 hours.
Using these points, players could unlock:

Hints - cost a point each. Unlocked by clicking "Reveal Hint" on the
parchment
Spoilers - cost two points each. Unlocked by clicking
"Reveal Spoiler" on the parchment.
Answer: While I don't personally remember there being such a thing for OSRS, there does appear to be a news post from back in 2018 (for RuneScape 3) regarding spending quest points. Specifically, a Quest Point Shop.
https://secure.runescape.com/m=news/quest-point-shop

Greetings!
So, you're all sitting on loads and loads of quest points, right? Or
perhaps you've not delved too deep down the questing rabbit hole
because, why bother, as you can't do anything with those points
anyway? Whichever is true for you, we have good news – Quest Point
Shop is here to reward questers for their heroic deeds!
WHAT IS IT? As the name might suggest, Quest Point Shop is… a shop.
More specifically, a shop in which you can spend quest points. Quest
points + shop = Quest Point Shop. We hope you're keeping up. You'll be
able to find it south west of the Varrock Lodestone.
In the shop players will find May. She's a tinkerer, so please do
excuse any mess you find around her wagon. May used to be an
adventurer herself, and is determined to help other adventurers
succeed in their pursuits. Well done her!
In Quest Point Shop there is one general reward track and then a
number of additional reward tracks that players can choose to progress
along, should they so desire. The former is automatic, but the latter
depends on how the player chooses to allocate their points.
WHAT CAN YOU GET? Quest Point Shop unlocks occur in 25 quest point
intervals, and players will be able to reset their unlocks once a
week.

I also found a reference to May's Quest Caravan, here:
https://www.runehq.com/special/mays-quest-caravan

Located next to the Champions' Guild, just South West of the Varrock
lodestone, is May's Quest Caravan. Here you can use your quest points
to obtain special offers and rewards for completing a certain number
of quests. You will also find the Quest Noticeboard which informs you
who has completed what quest most recently.
First and foremost, you will need to complete 1 or more quest to begin
taking advantage of what May has to offer.

Perhaps this is what you remembered?


My outdoor lights on whole day and night. I can't find any switches for them

Question: My outdoor wall lights always work. I can't find any switches for them, and I already tried every switch in the house. When I use one of switches near porch switch, nothing happens. I only noticed lights turned off when handymen came to repair pool things, and he turned off electricity which regards to pool. Where do you think may located switch for these outdoor lights outside of my garage?
Comment: Possible they had a day/night sensor that stop working, but not likely.  Would turn off breakers till they go off and see what else doesn't work.  Maybe whoever had them put in did not think about having a switch, just the breaker, would be weird.
Comment: Is it not bad enough to find a switch that does nothing, now we have to worry about hidden WiFi switches.
Comment: It's possible that the previous owner had a home automation system and installed these lights to be switched digitally and didn't include a physical switch. There may be an blank wall plate somewhere that contains a WiFi (or other wireless protocol) enabled switch that is used to turn them on/off. (Yes, some are UL listed for installation in a junction box.) It may be set to turn on when power is restored and you simply have no way of turning them off.
Comment: Alternately, why don't you just fix the broken day/night sensor or the broken motion sensor?  Better day/night sensors are made to fail "on", for the simple reason that the exact same units are used on municipal street lights, and city maintenance people mostly work during the day.  Although they make a variant designed to fail "off".
Comment: Rental places need to have an electrician to do most work, renters/landlords only allowed to do simple replacements, replace light bulbs, maybe switches/outlets, anything else need the electrician.
Comment: Thank you for your tips, guys! Unfortunately, I suck at all of this electric stuff area. I have only one switch that doesn't do anything, and it near the front door. Maybe this one that I need to repair? We also have a security system, and there are a lot of different buttons. Also, there is something looks like wi-fi router and one white box attached to the wall, and it doesn't have any buttons. Sorry for this poor description, I rent this house, and I moved only recently:)
Comment: Yes, I understand. I thought maybe there is a hidden switch in the house, so I will not need to call electrician.
Comment: Can you find a circuit breaker in your breaker panel that turns them off?
Comment: **Just get a new fixture** with a dusk till dawn. *That* you can do, presuming you know how to kill the power. Adding a timer or a switch is not novice level. First **make sure the senor is not covered** by a little plastic cap (this comes with the light to defeat the sensor, for if you do want it always on).
Comment: Do you need the lights at night? Assuming bulbs (as opposed to integrated leds), you could just unscrew the bulbs a bit to turn them off.
Comment: @Harper-ReinstateMonica But also better for a street light to fail on and waste a little energy than to fail off and have an unsafe street.
Answer: One way to find the culprit is to check ALL switches and junction boxes on the pertinent circuit.
If you are new and cautious about DIY electrical work, get an experienced DIY friend to do this with you. Working with open boxes on live circuits is dangerous. If you are not the home owner you need to contact the landlord.

Switch off all circuits at the panel.
Switch them on one at a time and determine which circuit applies to those lights.
With only that circuit on, and others off, determine the switches and junction boxes wired to it. For this, use a "proximity" voltage tester (not expensive), and open each box. Mark every such light, switch and receptacle with a piece of (painter's) tape.
In all switch boxes for this circuit, near the lights, check so see if any wire that possibly continues from the box to the outdoor lights is wired "permanently on". They may originally have been wired through a switch that is later circumvented.

If so, you are likely able to interrupt the wire to the lights and confirm that the lights are fed by it. Before unwiring the feed, the circuit must be switched off at the panel by the breaker, and any loose wires must then capped off before switching the breaker on again. If the lights now stay off you likely found your feed.

Check that all earlier marked outlets of this circuit (lights, receptacles) still have power, after interrupting the sub-circuit for the problematic outdoor lights. If the feed leaving the box only serves your lights, you may be able to rewire it so that the lights outside go through the switch.

Report back with your findings if step 4 is not conclusive.
Comment: in paragraph 2 you reccomend breaking the law
Comment: @Jasen changed "for you" to "with you"


Ubuntu equivalent of CentOS success / failure

Question: A lot of services in CentOS look like this (except green and red, respectively):
$ sudo service blah start
Starting blah:           [  OK  ]
$ sudo service notrunning stop
Stopping notrunning:     [FAILED]

This happens because the /etc/init.d scripts use utility scripts in /etc/rc.d/init.d/functions called success and failure. Here's a snippet from /etc/init.d/sshd in CentOS:
echo -n $"Starting $prog: "
$SSHD $OPTIONS && success || failure

My question is: is there a ubuntu equivalent? I could copy the scripts over, but they're more complicated than you'd think, and why reinvent the wheel if I don't have to?
Answer: I think the functions you are looking for are sourced from /lib/lsb/init-functions, and named log_success_msg and log_failure_msg:
$ . /lib/lsb/init-functions
$ log_success_msg foo
 * foo
$ log_failure_msg foo
 * foo

In this output, the first * is grey, the second is red (error case). Not extremely colorful, just enoug to get the point across...

From /lib/lsb/init-functions:
[ ... ]

log_success_msg () {
    if [ -n "${1:-}" ]; then
        log_begin_msg $@
    fi
    log_end_msg 0
}

log_failure_msg () {
    if [ -n "${1:-}" ]; then
        log_begin_msg $@ "..."
    fi
    log_end_msg 1 || true
}

[ ... ]

Answer: You could use the functions provided by the lsb-base package in /lib/lsb/init-functions. I have seen init.d scripts sourcing that file and then using the functions within, such as log_end_msg:
$ (. /lib/lsb/init-functions; log_end_msg 1)
   ...fail!
$ (. /lib/lsb/init-functions; log_end_msg 0)
   ...done.

For example, a snippet from /etc/init.d/ssh (case for start):
if start-stop-daemon --start --quiet --oknodo --pidfile /var/run/sshd.pid --exec /usr/sbin/sshd -- $SSHD_OPTS; then
    log_end_msg 0 || true
else
    log_end_msg 1 || true
fi


user recognizes command but root doesn't

Question: I installed arm-linux-g++ and added its directory to PATH and it recognizes the command. But when I try it with sudo it says command not found. I even tried adding its directory to bashrc--root but still nothing changed.
How can I fix it?
Answer: sudo specifically ignores your PATH variable and uses its own. Compare echo "$PATH" with sudo sh -c 'echo "$PATH"'. Either put the command in one of the paths sudo trusts, or supply the full path to that particular command.
Comment: you're right it's not in sudo PATH. How can i add it to one of those paths you mentioned?
Comment: @soroosh.strife for instance `sudo cp /path/to/the/command /usr/local/bin/`.
Comment: @geirha Wouldn't `ln -s` be better (as any updates to the command woundn't be reflected if you copy it) , or even fixing the path for sudo?


With Xubuntu 21.10 on 2008 MacBook, why does keyboard only function as a 10-key pad?

Question: Just installed Xubuntu 20.10 on my 2008 MacBook (4,1). Most keys don't function, but one group behaves like a 10-key pad. Selected standard English keyboard layout during install. Tried several other keyboard layouts. None worked. Can't type terminal commands or connect to wifi without alpha characters. Since keyboard seems stuck in a "numlock on" mode, I thought of checking Bios/EFI for a way to disable numlock, but powering up with CMD-S won't bring up EFI since the Xubuntu install.
Comment: My solution: replaced Xubuntu with Ubuntu Mate 20.04.3 LTS. It worked beautifully right from the start. Leaving the question up because I'm still curious, and maybe replies will help somebody.
Answer: You can disable the numlock from the terminal using numlockx off.
This will allow to turn off the numlock.
You can do this using the virtual keyboard (onboard) and the terminal emulator. It's in Menu > Accessories > Onboard


Angular card flips back without calling function

Question: I am using Angular for my front end and wanted to use a card flip animation on cards. On clicking the card, the card should flip and reveal a form. On clicking submit on this form the form should flip back. I have also added a clear button in the form which should clear out the form but not flip the card back. For some reason in my implementation, clicking clear is flipping the form. Here is the code for the card.componenet.ts
import { Component, OnInit } from '@angular/core';
import {
  trigger,
  state,
  style,
  transition,
  animate,
} from '@angular/animations';

@Component({
  selector: 'app-card',
  templateUrl: './card.component.html',
  styleUrls: ['./card.component.css'],
  animations: [
    trigger('flipState', [
      state(
        'active',
        style({
          transform: 'rotateY(179deg)',
        })
      ),
      state(
        'inactive',
        style({
          transform: 'rotateY(0)',
        })
      ),
      transition('active => inactive', animate('500ms ease-out')),
      transition('inactive => active', animate('500ms ease-in')),
    ]),
  ],
})
export class CardComponent implements OnInit {
  constructor() {}

  ngOnInit() {}

  flip: string = 'inactive';

  toggleFlip() {
    this.flip = 'active';
  }

  toggleFlipBack() {
    this.flip = 'inactive';
  }
}

Here is the html for this component, as you will notice I havent added any function to the Clear button as of now, but it still flips back

Front

      <form (submit)="toggleFlipBack()" [@flipState]="">
        First name:

        <input type="text" id="fname" name="fname" value="John" />

        Last name:

        <input type="text" id="lname" name="lname" value="Doe" />

        <button>Clear</button>
        <input
          type="submit"
          (click)="toggleFlipBack()"
          [@flipState]=""
          value="Submit"
        />
      </form>

I also created a stackblitz for this case, just in case someone wants to play around with it.
card flip stackblitz
Can someone please tell me why the clear button behaves this way, without any function attached to it?
Answer: Use type="button". By default it is type="submit". Updated StackBlitz.
Answer: You run into the default behavior of the button element. Button element become a default submit when nested inside a form.
You can prevent this behavior by adding the type attribute with the value button like here:
<button type="button">Clear</button>


What happened to my face?


Auto Increment c# in Excel

Question: I have here a line of code increment number but every I register a patient the sampleNum didn't increment. Please help me with this.

Please click the image. I already have a line of code for increment a patient number. But every time I register a patient the sampleNum did not increment. My point here is every time I register a patient the PatientNumber will increment by 1. Then as you can see in my excel 2 RP00 means my code didn't increment.
Comment: please don't post code as pictures. always paste it into your post. As for your question: your increment variable is help locally so it is initialized with `0` each time you call this method. you need to declare it as a static variable outside of this method.
Comment: The only thing I can see that would reasonably increment a number, is commented out.. `ToString("00001")` might not be what you expect; your number will be formatted to 4 zeroes wide and then have a 1 added on the end, so every number it generates will end in 1
Answer: Here is a simple program that will ask you for the number of patients to register and print out their formatted patient numbers. I trust that studying it will prove helpful to you completing your homework mission
public class Program
{
    public static void Main()
    {
        Console.WriteLine("How many?");
        int howMany = int.Parse(Console.ReadLine());

        int patNum = 0;
        while(howMany > 0){
          patNum++;
          RegisterPatient(x);
          howMany--;
        }
    }

    public static void RegisterPatient(int patientNumber){
        string pn = patientNumber.ToString("RP0000");
        Console.WriteLine("Now registering patient "+pn);
    }
}

Auto Increment c# in Excel


Is there an easier way to view replays?

Question: I am trying to do some replay viewing practices.  Unfortunately, the WC3 replay viewing doesn't offer user friendly controls. I was wondering if there is any application or plugin to improve the replay viewing.
For example, I want to be able to scroll the replay to certain parts I need, rather than waiting to get there by increasing the playback speed to x8.
Answer: No there is no tool to enable you to jump/scroll directly to a point.
However, you can speed up the replay speed more than the standard x8 using Replay Seeker.
WARNING: It can still be buggy.

Is there an easier way to view replays?


Responsive nav sidebar with company logo and information

Question: Currently, our team's browser app looks like this:

up to this point, we built our app to target desktop. However, because we're moving to Android, it is imperative that we can also effectively target mobile devices. Upon trying to emulate that, through the Developer Console, the screen looks like this:

The nav side bar and the company info are both gone! Furthermore, if we place a menu button next to our company logo, it may create confusing UX, as the end-user could easily fat-finger the menu button and end up hitting our logo instead. What would you advise we do, with respect to this?
Comment: Heads up that you should sanitize that screenshot since I now know the real names of two of your colleagues/clients/etc.
Comment: Why do you think *user* needs your company logo?
Comment: As of right now, our logo is a quick way back to the home page, similar to how the StackExchange logo on this (and every other!) question on here provides a link "back" to stackexchange.com
Answer: 2 months ago I had similar problem, which now is implementing.
For now the solution I see:
Logo should be transformed into sygnet and place in left-top corner

Categorization & nesting list elements in several levels:

Using dropdown list in menu (like Material Design)
Answer: Two ideas:

Leave your logo at top left corner and put your menu hamburger to the top right corner. You can put your user profile there also. I did exactly that in one project.
Let your logo be your menu. Since the user has nowhere to click on a toolbar, they will click on logo eventually. As this will work for them, they'll accustom to do that every time. The idea here is following: your mobile user probably needs menu much more than to go to Homepage Dashboard. You will have special item "Dashboard" in menu (and it looks like you already have it anyway).

Also let me note you have a lot of menu items on the sidebar. Maybe your users don't all of them, at least in mobile. Not all of them look interesting for me as a user (sorry for that).


stuck into building jar with external jar dependency

Question: I'm trying to build a executable jar only using the terminal with the following directory structure:
project-folder
|---lib
|   |---commons-io-2.6.jar
|---src
|   |---App.java
|   |---App.class
|   |---App$1.class
|   |---App$2.class
|---manifest.mf
|---App.jar

How you can see I have already created the App.jar with the command:
jar cmf manifest.mf App.jar src/*.class

But when I try to execute the App.jar file with
java -jar App.jar

I get the error message:

Caused by: java.lang.NoClassDefFoundError: App (wrong name: src/App)

Here is my manifest.mf:
Class-Path: lib/commons-io-2.6.jar
Main-Class: src/App

Can't see where the fault is and still searching for hours..
Thanks in advance!
Answer: the compiler is trying to tell you that it has a package srcApp;. You need to run it from the package root on.
Comment: So u mean I should use: `jar cmf ../manifest.mf ../App.jar *.class ../lib/commons-io-2.6.jar` and execute it from src folder?
Comment: Or can I also leave `../lib/commons-io-2.6.jar` out cause I have it already in manifest file (Class-Path)?


LazyVGrid crashes

Question: I have a problem in an app on App Store that crashes and I cannot find the reason. I reduced the problem in a sample project and can repeat the crash with the following code:
struct ContentView: View {
    var items: [Int] = Array(0...40)
    var body: some View {
        ScrollView {
            LazyVGrid(columns: columns, spacing: 16) {
                ForEach(items, id: \.self) { item in
                    Rectangle()
                        .foregroundColor(.blue)
                        .frame(height: 135)
                }
            }
        }
    }

    var columns: [GridItem] {
        [GridItem(.flexible(), spacing: 16), GridItem(.flexible(), spacing: 16)]
    }
}

When I run it on my device, I get a crash after doing the following:

scroll to the bottom
rotate the device
scroll to the top

What is going on? Is there something that I have missed, or is this actually a bug in LazyVGrid? The steps to reproduce this seem so simple, that I have a hard time believing that it has been missed by Apple, hence the question here...
I tried this on 4 different devices (2 iPads, 2 iPhones) and an iPad simulator, all running iOS 17.1 or 17.1.1. It failed every time on one of the iPads and one of the iPhones (and not on simulator), so it is not necessarily repeatable for everybody.
The crashing line in the code is just the main app entry point, and the message is something like "EXC_BREAKPOINT 0x00000001a582e454", so nothing helpful there...
Answer: Seems this is a long term issue, discussed in the developer forums:
https://developer.apple.com/forums/thread/718741
I can reproduce this in Xcode Version 15.1 beta 3 (15C5059c) deployed to iPhone 14 Pro Running 17.1.1. I noticed it only happens after a rotation where animation looks glitchy with the rectangles overlapping one another. Launch in portrait, scroll down, rotate to landscape then back to portrait (overlapping animation occurs), scroll to top, crash.
It even happens with Apple's example code in the docs for LazyVGrid.
I noticed it doesn't crash when there is only one column.
Unrelated but it's not a good idea to use id: \.self because self is not a valid id and it can crash in a similar way, it can be made safer like this:
private let items: [Int] = Array(0...40) // private prevents changes being possible

or even better:
ForEach(0..<41) { item in // static range is now impossible to change

Comment: Agreed. Although self is often misused in situations where it isn't unique, it should work here.
Comment: Thanks a lot for looking into this. Cannot believe that Apple has not fixed this yet when it's such an old issue. As one of the comments in the developer forum writes: "Please care more about SwiftUI" . It looks like I have to create a SwiftUI wrapper around UICollectionView instead then
Comment: No, that was not the reason. It still crashes.
BTW: I believe that \.self is allowed - it refers to the Int in the array. Paul Hudson has explained it here: https://www.hackingwithswift.com/books/ios-swiftui/why-does-self-work-for-foreach
Answer: In my case at least, disabling the animation of the LazyVGrid works. This has only been confirmed in the simulator so far but it consistently crashes in the simulator without this.
LazyVGrid {
// Insert code...
}
.transaction { transaction in
    transaction.animation = nil
}

I got the suggestion from here: https://www.avanderlee.com/swiftui/disable-animations-transactions/ While it does not say it will fix the crash, I took a chance on it and it seems to work.
Comment: transaction - didn't help
Comment: for such uncorrected years! errors Apple must pay compensation for damages.
I can't imagine Toyota releasing a car for which:
- go back
- rotated 90 degrees
- go forward
bam and the car fell apart

LazyVGrid crashes


Flash Player in Google Chrome does not work on Ubuntu Live CD

Question: I use Ubuntu 16.04.1 LTE Live CD.
I tried to install Google Chrome using terminal:
sudo dpkg -i ~/Downloads/google-chrome-stable_current_amd64.deb

It got some problems while installing, but solved it using:
sudo apt-get -f install

And after that I run the Google chrome installation again.
It worked, and I am able to start Google Chrome.
Then, it always happens that Ubuntu ask me to set a new password for "keyring". I ignored that, and Ubuntu said it has found an internal problem.
After all these things, I tried to run Flash Player on Google Chrome, but it said: download failed.
In the past, it did not happened. It only started happening this week.
I tried sudo apt-get install flashplugin-installer but it said Unable to locate package flashplugin-installer.
I tried deleting ~/.config/google-chrome/PepperFlash but it also didn't work.
What should I do? I just want to run flash.
Comment: Google Chrome comes with Flash built-in; you don't need to install anything but Google Chrome to use Flash in Google Chrome.
Answer: You're installing wrong package. Chrome uses it's own flash. It's called PepperFlash.
Do not delete ~/.config/google-chrome/PepperFlash
Or install PepperFlash by editing gksudo gedit /etc/apt/sources.list and adding this lines:
deb http://archive.canonical.com/ubuntu your_ubuntu_version multiverse
deb-src http://archive.canonical.com/ubuntu your_ubuntu_version multiverse

Do not forget to apt-get update && apt-get upgrade
and install package apt-get install pepperflashplugin-nonfree
Comment: I cannot do `gksudo gedit /etc/apt/sources.list`
Comment: When I use  `apt-get install pepperflashplugin-nonfree`, it said Unable to locate package pepperflashplugin-nonfree.
Comment: Then you did something wrong, pepperflashplugin-nonfree is located in http://packages.ubuntu.com/xenial/pepperflashplugin-nonfree


Parseval equality with $\int |f|^{1}$

Question: The famous Parseval equality states that
\[
\int|f|^{2} = \int |F|^2,
\]
where $f$ and $F$ are related to one another by
\[
\int f e^{-2 \pi i r y } dr = F(y).
\]
My question is, whether there is any result for
\[
\int |f|
\]
given its Fourier transform.
Comment: If I remember correctly, if $f \in L^2$, then the $L^2$ norm of $f$ is equal to its Fourier transform norm: http://math.mit.edu/~jerison/103/handouts/fourierint1.13.pdf. For your case of $e^{2 \pi I r y}$, the constant is 1
Comment: If $f \in L^{2}$, then can we say anything about $\int |f|$? (not the mean square)
Comment: Not necessarily, there are many $f \in L^2$ that are not in $L^1$. Let $f = \frac{1}{x} \chi_{[1,\infty)}$ for one example
Comment: How about for those belonging to both spaces?
Comment: You don't even have inequalities of the type $\int |f| \leq C (\int |F|^{2} )^{1/2}$ or the reverse of this inequality.
Comment: I don't think there is any.
Comment: Okay. Thanks for many comments.
Answer: There is a general result called the Babenko–Beckner inequality:
$$\left(\sqrt{q}\int |F|^q\right)^{\frac{1}{q}} \leq \left(\sqrt{p}\int |f|^p\right)^{\frac{1}{p}}$$
where $\frac{1}{p}+\frac{1}{q}=1$.
The equality is only reached in the case $p=2=q$.
In the limit where $p=1$, you might get something like:
$$\max F \leq \int |f|$$
or you most probably remains with the disappointing $$0 \leq \int |f|$$
(I should check whether we can commute the order of the limit $q\longrightarrow \infty$ and the limit of the Riemann sum.)

Parseval equality with $\int |f|^{1}$


Installed Gnome but I don't want gnome 3

Question:
Possible Duplicate:
How to revert to GNOME Classic?

I installed gnome because I liked the old gnome, but I installed Gnome 3, and even when I go into gnome classic, I can't right click the top and bottom bars and customize them like I used to do in Ver 11 (or 10... I'm not exactly sure... but it wasn't 12) of Ubuntu. Anyway to revert back?
I'm in 12.04
Answer: You could always try Cinnamon or Mate desktop environments.
Comment: Mate (gnome 2 fork), not cinnamon (gnome 3 fork).
Answer: You are in GNOME Classic session which uses compiz for effects. Compiz disabled those options. To add the icons do the following

Login to "Gnome-Classic (No effect)" session
Press and Hold the Alt
While holding Alt key, right click on the top panel
Select "Add to panel"
Choose "Application launcher"
Click on the "Forward" button at the bottom.
Select the desired application icon from the list. You can add a complete category such as "Sound & Video" to the panel!
Click "Add" button or double click the Application entry.

You're done. Now login again to Gnome-Classic (with effect) session. It should now include the icons in top panel.
Comment: I answered the question because, I think he wanted to customize the top and bottom panel which can't be done with "Gnome-Classic" session which uses compiz.
Comment: I hold the alt key and right click, don't required the super key. anyway glad to know it helped.
Comment: I marked this as the answer, but I went in and actually tried it and it didn't work. Right clicking doesn't give me the option.
Comment: @EGHDK See the updated answer
Comment: I'll mark you as the correct answer, but for me all I had to do was hold the alt and super key while right clicking. Then I was able to do everything as I expected.


Normalizing data

Question: I need to update the managerid field with the related employeeid.
CREATE TABLE Employee(
EmployeeID Int Primary Key Identity,
Name Varchar(50),
ManagerID INT default 0,
ManagerName Varchar(50) default ''
)
INSERT INTO Employee(Name,ManagerName) VALUES('Dilbert','Boss')
INSERT INTO Employee(Name,ManagerName) VALUES('Boss','Dogbert')
INSERT INTO Employee(Name) VALUES('Dogbert')
SELECT * FROM Employee
GO
-- This is the update stmt I need help with
UPDATE Employee
SET ManagerID=EmpID
WHERE ManagerName = Name

Answer: You can join on the Employee table to find a manager's id:
UPDATE emp
SET ManagerID = boss.EmployeeID
FROM Employee emp
INNER JOIN Employee boss
    ON boss.Name = emp.ManagerName

Be aware that storing both the manager's name and the manager's id in an employee row violates 3rd Normal Form.
Comment: Thanks Andomar! I was trying to update employee instead of update emp.  Thank you very much!
Comment: I will remove ManagerName after I get ManagerID populated.

Normalizing data


More content in gcm notification meteor

Question: I am working with GCM notification in my Meteor app. The code goes as follows
    var gcm = Meteor.npmRequire('node-gcm');
var message = new gcm.Message({
    collapseKey:new Date().getTime().toString(),
    delayWhileIdle: false,
    timeToLive: 2419200,
    data: {
        "title": "some Title",
        "message":"some Message"
    }
});

message.addData('msgcnt','3');
message.addData("notId", parseInt(Math.random() * 25));
var sender = new gcm.Sender('XXXXX');
var registrationIds = [];
registrationIds.push('XXXX');
sender.send(message, registrationIds, 5, function (err, result) {
    if(err) {
    }
    else   {
        console.log(message);
    }
});

The above code gives me a notification with title in bold and beneath the title, I have single line of message. But I do not want the title, instead I want to accommodate more lines of messages in my notification.
Like when I get a notification, I should just see about few lines of messages with no headers. How should I do it in GCM?
Comment: This is handled client-side, so your question is not related to node.js or javascript. It is all down to how you display the data from the notification in your Android app.
Comment: Ok. Can u please guide me how that is to be done. I would be really grateful. Thanks.
Comment: You *might* be looking for something like this (but I am not sure from your question): https://developer.android.com/training/wearables/notifications/stacks.html
Comment: I agree with Niels in that this is handled on the client-side. Your node server will only be able to send the info needed, like what text to display, but it is up to your Android app to place this text in a notification that will get displayed on the phone's screen.
Answer: You will need to implement Big View styles, which help generate notifications with a lot of text. In particular, you will need to call setStyle on your notification builder as follows:
.setStyle(new NotificationCompat.BigTextStyle()
            .bigText(msg))

This needs to be implemented in your client code, which is on Android.
Comment: But I really wonder how can I do that in meteor. As in Meteor, we have both client and server side code in Javascript. And I am using some meteor packages to send notification.
Comment: Oh I see what you mean. Unfortunately, client side JavaScript still runs on a web page. GCM is meant to send messages from a server to an Android client app. I assume this is what you intended, to reach an Android app. If not, check out GCM for Chrome extensions.
Comment: Just to add, I see that meteor has now added Phonegap support. Is that what you intend to use?
Comment: yes, I have already used that and I am successful in sending notification too. But my notifications contains a header and a single line message. Instead I want to remove the header and add more of messages.

More content in gcm notification meteor


Show that $\sqrt{x}$ is continuous using sequences

Question:
Show that $f(x)=\sqrt{x}$ is continuous on $[0,\infty)$ using the sequence definition.

The sequence definition is referring to $f$ being continuous in a point $x$ if for all sequences $(x_n)_n$ with $x_n\to x$ it holds that $\lim_{n\to\infty}f(x_n)=f(x)$.
In this case $f$ is continuous for all $(0,\infty)$ because we can pick any non-negative sequence $(x_n)_n$ with $x_n\to x\geq 0$ then
$$\lim_{n\to\infty}|\sqrt{x_n}-\sqrt{x}|=\lim_{n\to\infty}\frac{|x_n-x|}{\sqrt{x_n}+\sqrt{x}} \overset{(*)}{\leq}\lim_{n\to\infty}\frac{|x_n-x|}{\sqrt{x}}=0.$$
For $x=0$ we can pick any $(x_n)_n$ with $x_n\to 0$ thus $(\sqrt{x_n})_n\to 0$ as well, hence $f$ is continuous on $[0,\infty)$.
I am curious if the estimation marked with $(*)$ is really necessary and if yes, why so? It felt logical to do so, yet I can't explain the reasoning to do so.
Answer: You can circumvent that estimation with
$$|\sqrt{x_n}-\sqrt{x}|^2 = |\sqrt{x_n}-\sqrt{x}||\sqrt{x_n}-\sqrt{x}|\leqslant |\sqrt{x_n}-\sqrt{x}||\sqrt{x_n}+\sqrt{x}|=|x_n - x|.$$
Hence, for any $\epsilon >0$ there exists $N \in\mathbb{N}$ such that if $n > N$ we have $|x_n - x| < \epsilon^2$ and
$$0 \leqslant |\sqrt{x_n}-\sqrt{x}| \leqslant |x_n-x|^{1/2} < \epsilon$$
Answer: I don't think it's really necessary, but it's a valid estimation, it is not too rough (i.e. the argument still works after doing the estimation), and (perhaps most importantly) it becomes a lot easier to evaluate the limit in the end (using, for instance, the squeeze theorem). Therefore I would personally deem it a good step to make.


React first time - structure, moving between pages and variables

Question: so I started with react few days ago and have first problem.
I've build site structure using react-router and sample looks like this:
const app = document.getElementById('app');
ReactDOM.render(
    <Router history={hashHistory}>
        <Route path="/" component={Layout}>
            <IndexRoute component={MainPage}></IndexRoute>
            <Route path="/creator" component={MainCreator}>
                <Route path="select" component={Step1}></Route>
                <Route path="customize" component={Step2}></Route>
            </Route>
        </Route>
    </Router>,
app);

In Layout I'm rendering some site parts (which works fine, so I'll skip this code):
render() {
    return (

            <Menu />
            {this.props.children}

    );
}

I move through pages by using Link, like:
<Link to="creator/select">Creator - step1</Link>

Moving forward, my MainCreator is another component, parent for subpages in it, right now it's simple as:
render() {
    return (

        {this.props.children}

    );
}

And my problem is concerned with the flow of the application and how to solve this. In Step1 of the Creator user have to choose document type that will be created (like "pdf" or "html"). Right now there are sample  tags, but it can be anything. So after users clicks it, I have to remember selected value and load (can be after clicking submit button) Step2 component with proper view.
I tried to use this.state, but read I should use this.props instead, because state is/should be private in particular component. But I don't know how to construct this relation between Creator main page and two childs/steps (there will be 5 steps in Creator finally).
For me it should act like keeping this variable in Creator component, but be able to modify and read it's current state from any of Creator child.
Answer: In your maincreator component use a state which save record of user's choice. Pass this state as prop to step2 component.
Also pass a function as a prop to step1 component.
This function will just set the value of state acording to user's choice.
In your maincreator component define a state and a method and pass to the children component like this:
    constructor(props){
      this.state={ userResponse: null}
    }
    changeResponse = (res) => {
       this.setState({userResponse: res})
    }
    .....
    render() {
       const children = React.Children.map(this.props.children,
              (child) => React.cloneElement(child,{userResponse:this.state.userResponse, changeResponse: this.changeResponse})
          );
       return (

        {children}

    );
}

Comment: Please clarify. I don't know how can i pass this state through this statement:
{this.props.children}
and only to one child - Step2 and similar - function to Step1.


unable to use autofilter to show dates before 2014 excel c#

Question: I am trying to use 'AutoFilter' to show all the cells that are before 2014. But I don't know how to do that. I was able to show only "01/01/2014" because my code chose in the 'AutoFilter' equals and I want is before.
This is my code:
range1 = xlWorkSheet.get_Range("A1:" + GetExcelColumnName(Globals.cl) + "1", Type.Missing);
range1.AutoFilter(cHireDate, "01/01/2014");

I tried to find on the web but I was unable to find something similar.
Thanks a lot for your help.
Answer: Just use a Less Than:
range1.AutoFilter(cHireDate, "<01/01/2014");

Comment: Thanks That do the trick :) (i didn't know that you can do < inside the string)
Comment: Yes - the excel interop uses very similar syntax to the Excel and excel vba functions. You can verify some of these types of things by recording macros in excel!


How to find the spectrum?

Question: Let the Hilbert space $H=l_2$ over the complex field.
How to find the point spectrum $\sigma_p(A)$ of $A$
$Ax=(x_1,ix_2,-x_3,-ix_4,x_5,....)$
Any help is very appreciated. thanks :)
Answer: By definition of eigenvalues if $Ax=\lambda x$ then $x_1=\lambda x_1$, $ix_2=\lambda x_2$, $-x_3=\lambda x_3$, $-ix_4=\lambda x_1$, $\dots$. If not all $x_i$ are zero the only solutions are: $\lambda=1$ and $x_1,x_5,\dots$ are non-zero;  $\lambda=i$ and $x_2,x_6,\dots$ are non-zero; $\lambda=-1$ and $x_3,x_7,\dots$ are non-zero; and $\lambda=-i$ and $x_4,x_8,\dots$ are non-zero. So $\sigma_p(A)=\{1,i,-1,-i\}$.
Answer: For $x=(x_{1},x_{2},x_{3},\cdots)$, define
$$
\begin{align}
    P_{1}x & =(x_{1},0,0,0,x_{5},0,0,0,x_{9},\cdots)\\
    P_{2}x & =(0,x_{2},0,0,0,x_{6},0,0,0,x_{10},\cdots)\\
    P_{3}x & =(0,0,x_{3},0,0,0,x_{7},0,0,0,x_{11},\cdots)\\
    P_{4}x & =(0,0,0,x_{4},0,0,0,x_{8},0,0,0,x_{12},\cdots).
\end{align}
$$
The $P_{n}$ are mutually disjoint, orthogonal projections that sum to $I$. And $AP_{n}=i^{n-1}P_{n}$ for $n=1,2,3,4$, which proves $\{1,i,-1,-i\}\subseteq\sigma_{P}(A)$. Clearly $A=\sum_{n=0}^{3}i^{n-1}P_{n}$ (this is a spectral decomposition.) Let $d(\lambda)=\mbox{dist}(\lambda,\{1,i,-1,-i\})$. Then
$$
\begin{align}
    \|(A-\lambda I)x\|^{2}
   & =\|\sum_{n=0}^{3}i^{n-1}P_{n}x-\lambda\sum_{n=0}^{3}P_{n}x\|^{2} \\
   & = \sum_{n=0}^{3}|i^{n-1}-\lambda|^{2}\|P_{n}x\|^{2}\ge d(\lambda)^{2}\sum_{n=0}^{3}\|P_{n}x\|^{2} = d(\lambda)^{2}\|x\|^{2}.
\end{align}
$$
So $(A-\lambda I)x=0$ and $x\ne 0$ together imply $d(\lambda)=0$, which finishes the proof that $\sigma_{P}=\{1,i,-1,-i\}$.
Answer: I think just intuitively that it is a diagonal matrix (infinite of course) so the spectrum ought to be $\{1,-1,i,-i\}$ Essentially it is just the same four dimensional action repeated infinitely many times.

How to find the spectrum?


Expand RAID array

Question: I'm pretty new to RAID, so please forgive my silly question.
I have an Ubuntu Server 12.04 x64 installed on a pc having 4 hdds.
During RAID setup I selected RAID10 and (my ignorance) choose 2 active hdds and 2 spare hdds. I'm pretty sure it's not the optimal configuration and probably I should have selected 4 active hdds.
Running cat /proc/mdstat I get
md1 : active raid10 sdb2[1] sdd2[3](S) sdc2[2](S) sda2[0]
      948736 blocks super 1.2 2 near-copies [2/2] [UU]

md0 : active raid10 sdb1[1] sdd1[3](S) sdc1[2](S) sda1[0]
      311619072 blocks super 1.2 2 near-copies [2/2] [UU]

unused devices: <none>

Is there a way I can convert spare disks to active disks?
I tried using mdadm --grow /dev/md1 --raid-devices=4, but got this answer
mdadm: RAID10 can only be changed to RAID0

Answer: You cannot grow a RAID1+0 (it's not supported by mdadm).
From mdadm manpage:

Grow (or shrink) an array, or otherwise reshape it in some way.
  Currently supported growth options including changing the active size
  of component devices and changing the number of active devices in
  Linear and RAID levels 0/1/4/5/6, changing the RAID level between 0,
  1, 5, and 6, and between 0 and 10, changing the chunk size and layout
  for RAID 0,4,5,6, as well as adding or removing a write-intent bitmap.
Comment: So I cannot do anything else than keep current situation or restart from beginning, correct? :(
Comment: on very recent kernels (>3.0) you may be able to convert raid10 to raid0, but it's a risky business. Maybe someone can chime in on this.

Expand RAID array


How to modify a list of data.frame and then output the data.frame

Question: I want to create a second column in each of a list of data.frames that is just a duplicate of the first column, and then output those data.frames:
store the data frames:
> FileList <- list(DF1, DF2)

Add another column to each data frame:
> ModifiedDataFrames <- lapply(1:length(FileList), function (x) {FileList[[x]]$Column2 == FileList[[x]]$Column1})

but ModifiedDataFrames[[1]] just returns a list which contains what I assume is the content from DF1$Column1
What am I missing here?
Comment: Your function should return the updated data.frame. When you do an assignment, just the right hand term is returned, not the data.frame. You can add `return(FileList[[x]])` to your function. It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions.
Comment: @MrFlick oh ok because you need to specify what sapply should return, otherwise it just return the standard out from the run of the function. so in this case it was just returning ``FileList[[x]]$Column1``
Answer: There are a few problems with your code. First, you are using the equivalence operator == for assignment and second you are not returning the correct element from your function. Here is a possible solution:
df1 <- data.frame(Column1 = c(1:3))
df2 <- data.frame(Column1 = c(4:6))
FileList <- list(df1, df2)
ModifiedDataFrames <- lapply(FileList, function(x) {
  x$Column2 <- x$Column1
  return(x)
})

> ModifiedDataFrames
[[1]]
  Column1 Column2
1       1       1
2       2       2
3       3       3

[[2]]
  Column1 Column2
1       4       4
2       5       5

Comment: yea, the equivalence operator wasn't going to work, I was just getting frustrated and was trying random things. specifying the return element was what I was missing. Thanks sorry.


What goes into replacing a package unit (HVAC)?

Question: I have an A/C, Heater package unit on the roof of my condo in Southern California. My unit works but my neighbor's unit just  kicked the bucket and it is being replaced.
The estimates she got varied from $7k to $12k. She picked the $7k unit, 3 ton. Our package units (condo built in 1986) are Rheem 2.5 ton, gas for heater and electricity for the A/C. I have a 40A breaker for it inside my condo. I know we need a crane to do the work (the unit are two stories, garage on bottom, condo on top) so that adds to the installation cost. Besides the electrical and gas connection there is a water drain (PVC) that need to be removed/connected to the old/new unit.
I see some package units from Goodman are about $3k shipped. Other brands are about the same price. Assuming the crane is about $500. Where is the rest of the expense? Does it really cost $2k - $3k to connect the electricity, gas and water drain?
I know my numbers are not exact ... taxes are unavoidable...lol. BTW no rebates being used. I'm wondering because I'm thinking of replacing my unit myself. I can do the electrical, gas and pvc without a problem. I can contract a crane but maybe I'm missing something? Does the weight of the unit keeps it in place or is it screwed on?
Oh the price does not include any modification to the base where the old unit is placed.
UPDATE: Added a picture of my unit
Comment: What are you basing your crane estimate of $500 on?  I've never rented a crane, but that sounds low to me...
Comment: How tall or number of stories? I have put units on roofs using high lift forklifts. I think they can if to 45' but -5 because you hang the unit by chains.
Comment: @Ed Beal: 20 ft (from the ground to the roof)
Comment: @Nate S.: I remember asking crane operators that have been here before doing the install. I'm thinking outdated info by now though.
Comment: Do you have the equipment and knowledge to charge the freon?
Comment: @Mattman944 are package units charged at the factory or on site?
Comment: @PlatinumGoose - sorry, missed the *package* part, they are usually charged at the factory.
Answer: I would look into renting a "reach forklift", or boom lift forklift, suitable for rough terrain.  They have names like Gehl, SkyTrak, JLG & Genie. The last one I rented was $250/day with a delivery charge of $75.00. A crane requires a certified crane operator which goes for $100/hr in my state with a minimum rate; that's for just the operator.  So the forklift saves big time. (They go up to 40+feet, depending on model.)
As far as the charge for connections, that is off topic, but I can say on a condo it would require a licensed electrician at a minimum in my state,
possibly adding the required 120v receptacle as well, as I don't see that.
Possible changes in mounting, power, gas, drains all add time.
With commercial properties, like condos, we usually have to meet current code when there is a change (your neighbor going from 2.5 ton to 3 is a change).
So as far as cost, there may be multiple trades required in your state and some other changes we don't know about. So the cost may sound steep to me, but I did not bid the job and don't know all your local requirements.
The more requirements, the higher the cost.
Comment: I'm quickly getting to the conclusion that this is *not* a DIY project for me. Thanks.
Comment: A smart person will know when they are over their head but investigating may help you decide.
Answer: The last time I got a quote for crane service, which was not very recent, it was a couple hundred fee to show up and another hundred or two per hour on the site. I can see it taking more than a single hour to get the old unit free and down to the ground and the new unit settled into its final resting place the last time. Your crane estimate might be a little low.
Don't forget labor: a crew of two for most of a day at close to $100/hr rings up $1600 or so.
There'll be another hundred or two in materials as well. Gas pipe will have to be re-routed, duct size or shape will have to be modified, and so on. The meter keeps running on the crane as well while some of these matters get sorted out.
Comment: From older install that I've seen the crane doesn't stay here more than 30mins at the most. The new unit is here ready though. I imagine the old is ready to be removed as well. Yeah...cranes are not cheap.


Branch name in SonarQube iOS project scanning using Fastlane

Question: I am using Fastlane Action sonar to scan my iOS projects. But I can't pass sonar.branch.name in the action. I checked the code on github but didn't found any support for branch name there. So is there an alternate solution to this?
Final solution is to ditch fastlane is write a script to execute sonar scan.
Comment: If this is a common enough use case you could also just create an issue for fastlane or - even better - create a Pull Request adding the feature yourself. (Ruby is pretty "simple" to get if you know any other modern language, and the fastlane repo is happy to accept contributions and help you get them merged.)
Answer: I've added this functionality in fastlane and now it's possible via branch_name property.
Released in version 2.121.0
https://github.com/fastlane/fastlane/releases/tag/2.121.0


What type of tape is used to seal vapor barrier seams?

Question: If I was installing vapor barrier in Canada, I'd use Tuck® Contractors Sheathing Tape.  However, after a trip to the local Home Depot (USA), I came up empty in my search for Tuck Tape.
I did find Tyvek® Tape, which is used to seal the seams of Tyvek® HomeWrap®.
Can Tyvek tape be used as a stand in for Tuck tape, or are there more appropriate products available?
Comment: here I was thinking that duct tape was the goto tape for everything
Comment: Looks like canadian tire sells Tuck tape
Answer: I too, was in search of Tuck Tape at Home Depot / Lowe's and couldn't find it. When I asked a salesman about it, they didn't understand what I was looking for.
When I said I wanted to seal the edges of vapor barrier, they told me to use the Tyvek tape, the same one you found.
Duct tape won't cut it; it's too porous. We used the Tyvek and it's worked well so far.
Don't use it on hard wood floors as painter's tape; it'll rip the polyurethane right off of the floor (lesson learned).

It is the opinion of the Canadian Construction Materials Centre (CCMC) that "Tuck® 205-02 Contractor's
  Sheathing Tape / DuPontTM Tyvek® Tape", when used as a sheathing tape in accordance with the conditions and limitations stated in Section 3 of this Report, complies with the National Building Code 2005:
PDF
Comment: Yes, actually, I can. Answer modified.
Comment: Avtually The statement from the CCMC refers to exterior sheathing NOT interiror vapor barrier. The poster was asking about interior vapor barrier.
Comment: for the record I was making a joke
Comment: @ratchetfreak for sure; but too many people think duct tape solves everything. There's tape for duct work (which isn't duct tape), plastics, drywall, etc... Could you imagine someone using duct tape for taping seams on drywall? That would be funny.
Comment: Can you provide any data to back up the HD associates claims that this is the proper product to use?
Answer: I love how people take this vapor barrier stuff to the edge of infinity.
I remember when I took my contractor license test... 18 inch overlap doesn't even require sealing with tape.  If your concrete, or subfloor, or really any space is putting out enough moisture vapor to get past a simple overlap of poly then you have a much more serious problem than the correct tape.
Almost all of the "stucco tape" and "sheathing tape" I found is for temporary hanging of plastic.  The Intertape brand has one that says it's specifically for sealing vapor barriers so that's what I used.  But to be honest... I felt like duct tape works better.  I found some duct tapes that were rated to bond 20 yrs.  That Intertape bonded well, but not as sticky and nasty as duct tape.  I called on manufacturer of "sheathing tape" they said bond is only good for 2 years MAX.
The very best thing to do is call the manufacturer tech line for the wood/laminate or other covering and MAKE SURE you are talking to a tech guy and NOT a rep/sales rep.  Ask for the nerdy guy, he has all the legitimate answers.
I've installed LOTS of different products and many of the instructions for those different products give conflicting advice.  Your investment is safe if you follow the instructions for YOUR product.
PS.. one of the manufacturers specifically says to seal the seams with good ole duct tape.  :-)


How to share code in serverless with Python properly?

Question: I'm trying to find the best approach for robust serverless development with Python. The project is divided into multiple services using the serverless framework and versioned in a monorepo. Here's the structure I'd like to have:

service_1/

serverless.yml
handler.py

service_2/

serverless.yml
handler.py

shared

module_a.py
module_b.py

module_a and module_b comprise shared logic, which should be available for both services. So far I've found 2 approaches: wrap shared code in an installable package and inject it to services via pip or provide shared code as a layer. Both solutions have flaws, most importantly it's impossible to rapidly develop the app because any change requires pip.
I've noticed this problem is solved in Node.js and there are many unanswered questions about Python.
There is the plugin - serverless-package-common, which seems to tackle this issue, however, it doesn't look like a go-first approach.
I appreciate any form of help.
Comment: I am not familiar with Node.js. How exactly is the problem solved there? Can you link some of the unanswered questions? Maybe they contain helpful information despite not having an accepted answer.
Comment: Well, I should have been more specific about the unanswered questions - I meant questions like the one I'm asking on my mind. In Node.js shared code might be resolved like in [this post](https://theburningmonk.com/2019/06/aws-lambda-how-to-share-code-between-functions-in-a-monorepo/).
Answer: Maybe you can consider to use Lambda layer. You can find a quick guide here: link.
Let me give you a simple example. This example has two serverless projects - library which has shared code and service which has service codes.

library - This project should have below file structure. You have serverless.yml in the root of this project and another folder which will be export as a module. python will be linked and let lambda find your module when you use lambda with python.

./
└ serverless.yml
└ common/
    └ python/
        └ Common.py

serverless.yml - As you can see, folder common is explicitly declared here to be exported. Beware that layer name Common is re-used in resources and serverless framework will automatically match this with resource reference.
service: library
  provider:
    name: aws
    runtime: python3.7
    stage: dev
    region: ap-northeast-1
  layers:
    Common:
      path: common
  resources:
    Outputs:
      CommonLayerExport:
        Value:
          Ref: CommonLambdaLayer
        Export:
          Name: CommonLambdaLayer

common/python/Common.py (printException is an example of shared function which will be used in another project)
import sys
import traceback
import os

def printException(exception, writer=None):
    if writer is None:
      writer = print
    top = traceback.extract_tb(sys.exc_info()[2])[-1]
    writer(", ".join([type(exception).__name__, str(sys.exc_info()[1]), os.path.basename(top[0]), str(top[1])]))

service
serverless.yml - As you can see, layers should be included per each functions and you can refer to a specific layer with CloudFormation reference.

service: layer-test
  provider:
    name: aws
    region: ap-northeast-1
    runtime: python3.7
    stage: dev
  functions:
    exceptionExample:
      handler: handler.func
      layers:
        - ${cf:library-dev.CommonLayerExport}
      events:
        - http:
            path: exceptionExample
            method: get

handler.py - Now we can easily import shared module from shared layer.
import json
import Common

def func(event, context):
    try:
        1/0 # just to raise an exception and test the shared function
    except Exception as e:
        Common.printException(e)

    response = {
        "statusCode": 200,
    }
    return response

One thing you should be careful is that as lambda layer does not pack imported modules, you should import modules which is used by your layer in your services as well.
Comment: @UnbrandedManchester thanks for your comment, I just edited my answer and hope this helps.
Comment: Your answer seems helpful but please don't share links that may one day disappear. Instead share the info needed to answer the question in your answer.
Comment: @msc Would you mind having a look at https://stackoverflow.com/questions/63107494/sharing-python-code-as-a-lambda-layer-using-the-serverless-framework ? It is a follow up question to your answer.. thank you


OSGi Runtime cannot be loaded: In eclipse

Question: I am trying to create new Image Discription for my prdix machine and I am getting following error in Eclipse.

OSGi Runtime cannot be loaded: Directory:
  /home/shubham/.eclipse....v20161214/runtime does not contain a valid
  product installation

I am getting following error in eclipse as shown in Error Image when I click over Predix Machine Icon. It is giving runtime can not be loaded.
There is no such user Shubham in my system and Home folder does not contain shubham folder. I am using;
 - CentOS7
 - eclipse neon 4.6.2
 - Predix Machine 16.4.0
 - java1.8
Comment: In order for the community to help you it would be a good idea to review http://stackoverflow.com/help/how-to-ask and add a few more details about what you are trying to accomplish and what you already have or have not tried.  For instance, what version of Eclipse?  What did you select as your image description?  Are you following a specific tutorial that has more context?
Comment: There doesn't seem to be a question here.
Comment: I have edited my question, please see again and help me.
Answer: I found the solution for this. I was using old eclipse workspace which was copied form different system, that is why it was using old settings and was searching for folder which is not there.


How to permanently draw things in OpenGL's Immediate mode?

Question: I am having a small problem in essentially creating a path tracer.
In my project, I have an object which constantly moves around quite organically through an update function done in the while loop. I use immediate mode and represent the player as a square, I would like to make it so that every update the object is drawn in its current position, but also for it to draw it's previous position(s), so etching dots towards the path the object is going. I'm pretty sure we can do this by drawing the position as normal but not clearing everything up after this instance in the while loop, but I have no knowledge on how to do this.
Edit: For those who want the code, do understand that this code, in particular, is not adherent to the question and that I made a ton of generalizations (such as the particle(s) being referred to an object) so that the general gist of the question is understandable:
<code>#include "PerlinNoise.hpp"
#include "Particle.hpp"

#include <iostream>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <cmath>
#include <vector>

using namespace siv;

float map(float oValue, float oMin, float oMax, float nMin, float nMax)
{
  float oRange = (oMax - oMin);
  float nRange = (nMax - nMin);
  return(((oValue - oMin) * nRange)/oRange) + nMin;
}

void drawRectangle(float x, float y, float xr, float yr, float R, float G, float B)
{
  glBegin(GL_QUADS);
  glColor3f(R,G,B);
  glVertex2f(x,y);
  glVertex2f(x+xr,y);
  glVertex2f(x+xr,y+yr);
  glVertex2f(x,y+yr);
  glEnd();
}

void drawLine(float x, float y, float xr, float yr, float rotation)
{
  float radius = sqrt(xr*xr + yr*yr);
  float a0 = asin(yr/radius);
  float tangle = a0+rotation;
  //std::cout<<tangle*180/M_PI<<std::endl;
  glBegin(GL_LINES);
  glColor3f(.1,.1,.1);
  glVertex2f(x,y);
  glVertex2f(x + sin(tangle)*radius,y + cos(tangle)*radius);
  glEnd();
}

int main()
{
  float inc = 0.1;
  int scl   = 20;
  int cols,rows;

  Particle particles[100000];

  //V2D flowfield[cols*rows];

  GLFWwindow* window;
  if (!glfwInit())
    return 1;
  int width  = 800;
  int height = 800;
  window = glfwCreateWindow(width, height, "Window", NULL, NULL);
  cols = floor(width/scl);
  rows = floor(height/scl);
  V2D flowfield[cols*rows];
  float zoff = 0;
  if (!window) {
    glfwTerminate();
    return 1;
  }
  glfwMakeContextCurrent(window);
  if(glewInit()!=GLEW_OK)
    std::cout<<"Error"<<std::endl;
  glEnable(GL_DEPTH_TEST);
  glMatrixMode(GL_PROJECTION);
  glfwGetFramebufferSize(window, &width, &height);
  glOrtho(0, width*(width/height), height, 0, -2, 2);
  PerlinNoise png = PerlinNoise(1);
  while(!glfwWindowShouldClose(window)) {
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
    glClearColor(0.11, 0.14, 0.17, 1);
    float yoff = 0;
    for(int y = 0; y < rows; y++)
    {
      float xoff = 0;
      for(int x = 0; x < cols; x++)
      {
        double noise = map(png.noise((double)xoff, (double)yoff, (double)zoff),-1,1,0,1);
        double angle = noise * 8 *M_PI;
        //std::cout<<angle/(2*M_PI)<<std::endl;
        int index = x + y * cols;
        V2D v = V2D(cos(angle), sin(angle));
        v.normalize();
        v = V2D(v.x*5,v.y*5);
        flowfield[index] = v;
        //drawLine(x*scl, y*scl, scl, 0, atan2(v.x, v.y));
        //drawRectangle(x*scl,y*scl,scl,scl,noise,noise,noise);

        xoff += inc;
      }
      yoff += inc;
      zoff += 0.0001;
    }
    for(int i = 0; i < 100000; i++)
    {
      particles[i].follow(flowfield);
      particles[i].update();
      particles[i].show();
    }
    glfwSwapBuffers(window);
    glfwPollEvents();
  }
  glfwTerminate();
}
</code>
Comment: Show your current draw loop?
Comment: @Botje Are u sure it is a very big chunk of code, and a lot of things I said were generalizations so that the question was understandable.
Comment: Presumably you already tried not calling `glClear` every frame, so you will need to show a minimal example we can comment on.
Comment: @Botje It has been edited to include the code.
Comment: Simply remove `GL_COLOR_BUFFER_BIT` from your glClear call?
Comment: @Botje This does indeed work, however the program glitches sometimes(the pixels shift quite vigorously), is this normal?
Comment: That is probably caused by double buffering. [Ask GLFW to switch to single buffering](https://github.com/glfw/glfw/issues/415), or do your drawing in a headless framebuffer (that you never clear) and on every frame overwrite the main framebuffer with the contents of the headless framebuffer. The first option is probably less work, at the expense of slower drawing.
Comment: @Botje Thanks for the info I will mark this as Solved.
Answer: When drawing directly to a window (be it double buffered or not doesn't make a difference) you must not make any assumptions about its contents being persistent between drawing. Heck, strictly speaking the contents may become damaged mid draw, before things even finished up; of course in practice this isn't very likely to happen and given modern compositing graphics systems it's practically eliminated.
Your application screams for drawing to an intermediary framebuffer object. FBOs are guaranteed to retain their contents no matter what happens; also you can add further drawing to the backing buffer of an FBO at any time.
The official OpenGL wiki describes FBOs at https://www.khronos.org/opengl/wiki/Framebuffer_Object
Also ages ago I wrote a simple codesample (using a lot of outdated, legacy OpenGL); drawing is legacy, but the FBO parts are done today as it was 10 years ago: https://github.com/datenwolf/codesamples/blob/master/samples/OpenGL/minimalfbo/minimalfbo.c (I implemented it using render to texture; a render to renderbuffer and buffer blit to main framebuffer would work for you, too).


A way to pass milions of items in python to C program many times in rapid succesion

Question: I've wrote a python script that need to pass millions of items to a C program and receive its output many times in a short period (pass from 1 up to 10 millions of vertices data (integer index and 2 float coords) rapidly 500 times, and each time the python script call the C program, i need to store the returned values in variables). I already implemented a way reading and writing text and or binary files, but it's slow and not smart(why write files to hdd while you don't need to store the data after the python script terminates?). I tried to use pipes, but for large data they gave me errors...
So, by now i think the best way can be using the ability of ctypes to load functions in .dll
Since i've never created a dll, i would like to know how to set it up (i know many ide have a template for this, but my wxdev-c++ crashes when i try to open it. Right now i'm downloading Code::Blocks )
Can you tell me if the solution i'm starting to implement is right, or if there is a better solution?
The 2 functions i need to call in python are these
void find_vertex(vertex *list, int len, vertex* lower, vertex* highter)
{
    int i;
    *lower=list[0];
    *highter=list[1];
    for(i=0;i<len;i++)
    {
        if ((list[i].x<=lower->x) && (list[i].y<=lower->y))
            *lower=list[i];
        else
        {
            if ((list[i].x>=highter->x) && (list[i].y>=highter->y))
                *highter=list[i];
        }
    }
}

and
vertex *square_list_of_vertex(vertex *list,int len,vertex start, float size)
{
    int i=0,a=0;
    unsigned int *num;
    num=(int*)malloc(sizeof(unsigned int)*len);
    if (num==NULL)
    {
        printf("Can't allocate the memory");
        return 0;
    }
    //controlls which points are in the right position and adds their index from the main list in another list
    for(i=0;i<len;i++)
    {
        if ((list[i].x-start.x)<size && (list[i].y-start.y<size))
        {
            if (list[i].y-start.y>-size/100)
            {
                num[a]=i;
                a++;//len of the list to return
            }
        }
    }

    //create the list with the right vertices
    vertex *retlist;
    retlist=(vertex*)malloc(sizeof(vertex)*(a+1));
    if (retlist==NULL)
    {
        printf("Can't allocate the memory");
        return 0;
    }
    //the first index is used only as an info container
    vertex infos;
    infos.index=a+1;
    retlist[0]=infos;

    //set the value for the return pointer
    for(i=1;i<=a;i++)
    {
        retlist[i]=list[num[i-1]];
    }

    return retlist;
}

EDIT:
forgot to post the type defintion of vertex
typedef struct{
    int index;
    float x,y;
} vertex;

EDIT2:
I'll redistribute the code, so i prefer not to use external modules in python and external programs in C. Alsa i want try to keep the code cross platform. The script is an addon for a 3D app, so the less it uses external "stuff" the better it is.
Comment: The C data type `float` has only 4 bytes.  The Python type `float` corresponds to the C type `double` and has 8 bytes.
Comment: "for large data they gave me errors"?  Please be specific.  What errors?  Pipes can handle an large volume of data, limited only by OS memory.
Comment: Even assuming only 1 million items per vertix and optimal memory layout, you'd need about 5.6 GB (not GiB) if Google's calculator doesn't betray me. You propably *can't* store this RAM unless you have some supercomputer at your command.
Comment: @delnan: 1 million vertices is only 16 MB in C, and 104 MB in Python.
Comment: @S. Lott http://stackoverflow.com/questions/4979421/subprocess-popen-invalid-argument-broken-pipe-while-comunicating-to-c-program/4987203#4987203 Keeps giving error 32 pipe broken
@delnan 1'188'100 vertices saved in a binary file are 13,5 MB (14.257.200 byte)(it's just a struct.Struct('iff') for each vertex). So maybe the google calculator failed ;)
(i read the size of the file after saving them to file with a script and looking at the properties of the file)
Comment: @Rosh @OP: Aren't you having 500 of those? Calculator would about agree with this (11 MB).
Comment: int = 4, float = 8, so 20 bytes per struct. Then 20*one million=20 million byte that divided by 2^20 are around 15 MB
Comment: "Keeps giving error 32 pipe broken"?  Why aren't you debugging that?  Why are you asking this question when you have code that has a simple error?
Comment: S.Lott The python script is executed inside another program, and it uses an api of that program that uses data of objects in that program. It isn't run inside another process, but inside the process of the program. I don't really know how to debug it(and i never debugged code) By now i solved the pipe problem, but since i'm still learning, i would like to learn even calling a shared library function, so i can do it in future if i need and i can give choices to who will use my script ;)
Comment: Don't print to `stdout` on errors if you use `stdout` to communicate with an external program that expects formatted input. You could use `perror("malloc");` instead.
Answer: Using ctypes or Cython to wrap your C functions is definitely the way to go.  That way, you won't even need to copy the data between the C and Python code -- both the C and the Python part run within the same process and access the same data.  Let's stick with ctypes, since this is what you suggested.  Additionally, using NumPy will make this a lot more comfortable.
I infer your vertex type looks like this:
typedef struct
{
    int index;
    float x, y;
} vertex;

To have these vertices in a NumPy array, you can define a record "dtype" for it:
vertex_dtype = [('index', 'i'), ('x', 'f'), ('y', 'f')]

Also define this type as a ctypes structure:
class Vertex(ctypes.Structure):
    _fields_ = [("index", ctypes.c_int),
                ("x", ctypes.c_float),
                ("y", ctypes.c_float)]

Now, the ctypes prototype for your function find_vertex() would look like this:
from numpy.ctypeslib import ndpointer
lib = ctypes.CDLL(...)
lib.find_vertex.argtypes = [ndpointer(dtype=vertex_dtype, flags="C_CONTIGUOUS"),
                            ctypes.c_int,
                            ctypes.POINTER(Vertex),
                            ctypes.POINTER(Vertex)]
lib.find_vertex.restypes = None

To call this function, create a NumPy array of vertices
vertices = numpy.empty(1000, dtype=vertex_dtype)

and two structures for the return values
lower = Vertex()
higher = Vertex()

and finally call your function:
lib.find_vertex(vertices, len(vertices), lower, higher)

NumPy and ctypes will take care of passing the pointer to the beginning of the data of vertices to your C function -- no copying required.
Probably, you will have to read a bit of documentation on ctypes and NumPy, but I hope this answer helps you to get started with it.
Comment: Yes, i already used the cytpe structure while trying to use popen function.
Since with ctypes we can call functions, create arrays and pointes, why should i use NumPy(that is an external module and then need to be installed on every machine that wants to run the code)? If possible i prefer to use only standard modules..
Comment: @Makers_F: It *is* possible to do it without NumPy.  Handling and memory management of `ctypes` arrays is very error-prone though, and it is very hard to debug.  Furthermore, with NumPy you can efficiently do many things in Python which otherwise would have to be done in C.  Pretty much anyone handling large uniform arrays in Python uses NumPy, and I do consider it quite "standard".
Answer: It seems like what you really want is to turn your C program into a Python module. Here is a tutorial that will get you started.
Answer: If you want to pass data between two programs, and you already have the code to use a file, why not just use a RAMdisk? For Windows, you can use something like http://www.ltr-data.se/opencode.html/#ImDisk to create the RAMdisk and you can use the commands listed here for Linux. For smallish amounts of data (anything that will fit in RAM without requiring to be constantly paged out), this should outperform disk-based operations by a couple of orders of magnitude.
Comment: Yes, it was one of my first thoughts. I edited my first answer, look at it :)
In addition, in my case i don't need the 2 programs to "communicate", but more simply the python program have to call the C program passing him some data, and after it finished read the returned value. The os.system or subprocess.call would be the best thing if they only can handle big quantities of data..
I know in linux there are built in commands to create ramdisks, the problem then is windows, and i want not to use external programs..
Answer: I think I would use a library like sysv ipc for this job and simply map the data to a shared memory segment.
Comment: Another thing i thought about. If there is a way to use it without external programs i can definitely go with this!
Comment: @Makers_F Yes , IPC means interprocess communication, it is designed for sharing data between processes.
Answer: If you can, make the Python program buffer the data that it is sending so that it does not send every vertex one by one. Save them up until there are 100 or 500 or 1000 and that way you will make fewer calls. Do some timing tests to determine optimal buffer size.
Answer: Iterating over millions of items is the worst possible operation you could do in Python... If at all possible write this portion of the program in C or C++, it will be 100's of times faster and use 100's of times less memory...
I love python, but it's not a best solution for this type of operation.
Comment: Yeah, i'm totally with you, and if i only can i would. The problems are:
1) the script works as an addon of a program with a python api that interfaces with the C data of the program. I can get the address in memory stored by the program (it is written in C)of the data i want to use(the vertex), but even if i pass it to my C program i wouldn't be able to access it because of the memory space limitation. In addition, even if the program is open source, i don't know enough his structure to know how to handle the data, so i discarded this way..
Answer: Here's a variant that uses Cython to write an extension module for CPython.
C declarations to be used in Cython:
# file: cvertex.pxd
cdef extern from "vertex.h":
    ctypedef struct vertex:
        int index
        float x,y
    void find_vertex(vertex *list, int len, vertex* lower, vertex* highter)

Where vertex.h is:
typedef struct{
    int index;
    float x,y;
} vertex;

void find_vertex(vertex *list, int len, vertex* lower, vertex* highter);

Cython implementation to be used in Python:
# file: pyvertex.pyx
cimport numpy
cimport cvertex # use declarations from cvertex.pxd

def find_vertex(numpy.ndarray[cvertex.vertex,ndim=1,mode="c"] vertices):
    if len(vertices) < 2:
        raise ValueError('provide at least 2 vertices')

    cdef cvertex.vertex lower, highter
    cvertex.find_vertex(<cvertex.vertex*>vertices.data, len(vertices),
                        &lower, &highter)
    return lower, highter # implicitly convert to dicts

To compile the extension, run:
$ python setup.py build_ext -i

Where setup.py is:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext

setup(
    cmdclass = {'build_ext': build_ext},
    ext_modules = [Extension("vertex", ["pyvertex.pyx", "vertex.c"])]
)

Now the extension can be used from Python:
import numpy
import vertex # import the extension

n = 10000000
vertex_list = numpy.zeros(n, dtype=[('index', 'i'), ('x', 'f'), ('y', 'f')])
i = n//2
vertex_list[i] = i, 1, 1
v1, v2 = vertex.find_vertex(vertex_list)
print(v2['index'])
print(v1, v2)

Output

5000000
{'y': 0.0, 'index': 0, 'x': 0.0} {'y': 1.0, 'index': 5000000, 'x': 1.0}


is this a simple monad example?

Question: This is my attempt to grok monadic functions after watching this.
h uses bind to compose together two arbitrary functions f and g. What is the unit operator in this case?
;; f :: int -> [str]
;; g :: str -> [keyword]
;; bind :: [str] -> (str -> [keyword]) -> [keyword]
;; h :: int -> [keyword]

(defn f [v]
  (map str (range v)))

(defn g [s]
  (map keyword (repeat 4 s)))

(defn bind [l f]
  (flatten
   (map f l)))

(f 8)   ;; :: (0 1 2 3 4 5 6 7)
(g "s") ;; :: (:s :s :s :s)

(defn h [v]
  (bind (f v) g))

(h 9)
;; :: (:0 :0 :0 :0 :1 :1 :1 :1 :2 :2 :2 :2 :3 :3 :3 :3 :4 :4 :4 :4 :5 :5 :5 :5)

Ah, thanks for the comments; I see where I was confused.
I was familiar with these functions and how to compose them using bind:
f0 :: a -> M a
g0 :: a -> M a

but not with these functions:
f1 :: a -> M b
g1 :: b -> M c

but essentially, the bind operator is the same for both cases if M is the same. In my case, M is the list monad so f1 and g1 can be combined the same way as f0 and g0.
Comment: I've changed the type comments a bit; are they still okay?
Answer: This is a list monad, and so the unit operator is x ↦ [x], i.e.
(defn return [x] [x])

(Called return after the Haskell function of the same name & purpose.)
One can see that this is the unit operator by checking it satisfies the monad laws:
(bind (return a) f) => (bind [a] f)
      => (flatten (map f [a])) => (flatten [f a]) => f a  ;; f returns a vector

And similarly for (bind x return).
Answer: Are you trying to implement the list monad?  If so, then it would be:
(defn unit [x]
  [x])

This is based on the Haskell implementation:
instance  Monad []  where
    m >>= k             = foldr ((++) . k) [] m
    return x            = [x]

is this a simple monad example?


Django REST Framework error with accepted_renderer

Question: I'm pretty noob with DFR so I'm learning by following the tutorial.
Until now all is fine, but in the last part, here, I have to add a schema to the API and I follow the instructions, so install coreapi and add
from rest_framework.schemas import get_schema_view

schema_view = get_schema_view(title='Pastebin API')

urlpatterns = [
    path('schema/', schema_view),
    ...
]

in tutorial/urls.py, so my complete tutorial/urls.py is:
from django.conf.urls import url
from django.contrib import admin
from django.urls import path, include

from rest_framework.schemas import get_schema_view

schema_view = get_schema_view(title='Pastebin API')

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    path('', include('snippets.urls')),
    path('api-auth/', include('rest_framework.urls')),
    path('schema/', schema_view),
]

But if I visit /schema/ from browser at http://127.0.0.1:8000/schema/, I get:
AttributeError at /schema/

'Request' object has no attribute 'accepted_renderer'

I do not understand how to fix this error since I followed the tutorial's instructions.
My conf is:
coreapi             2.3.3
coreschema          0.0.4
Django              2.1.3
djangorestframework 3.9.0

If needed you can see the tutorial's code here and here is the get_schema_view documentation.
Comment: I found a solution here: https://github.com/encode/django-rest-framework/issues/6331 using DRF 3.8.0 instead of 3.9.0
Answer: There are two solutions:
install pyyaml:
pip install pyyaml

OR
Revert DRF:
pip install djangorestframework==3.8.0

Answer: The tutorial makes a request to that endpoint from the command-line using HTTPie, not the browser which would require a renderer to be specified. If you want this to work from the browser, specify a renderer as the documentation describes
Comment: The tutorial say: If you visit the /schema/ endpoint in a browser you should now see corejson representation become available as an option.
Comment: No it doesn't, I've looked at the docs for `get_schema_view` in the tutorial and your link, it states `Once the view has been added, you'll be able to make API requests to retrieve the auto-generated schema definition.`

Followed by a request using HTTPie.
Comment: Yes I know and I've already tried with httpie and get the same error. Moreover I have tested all the other endpoints (from previous part of the tutorial) both from the browser and from the command line and only this does not work. Please note that requests can come from both the browser and the command line.


syntax error, unexpected 'public' (T_PUBLIC)

Question: I am getting an error which is shouting at me that appears to be a syntax error?
I am really not sure where I am going wrong?

public function upload() {
  // getting all of the post data
  $file = array('image' => Input::file('image'));
  // setting up rules
  $rules = array('image' => 'required',); //mimes:jpeg,bmp,png and for max size max:10000
  // doing the validation, passing post data, rules and the messages
  $validator = Validator::make($file, $rules);
  if ($validator->fails()) {
    // send back to the page with the input data and errors
    return Redirect::to('upload')->withInput()->withErrors($validator);
  }
  else {
    // checking file is valid.
    if (Input::file('image')->isValid()) {
      $destinationPath = 'uploads'; // upload path
      $extension = Input::file('image')->getClientOriginalExtension(); // getting image extension
      $fileName = rand(11111,99999).'.'.$extension; // renameing image
      Input::file('image')->move($destinationPath, $fileName); // uploading file to given path
      // sending back with message
      Session::flash('success', 'Upload successfully');
      return Redirect::to('upload');
    }
    else {
      // sending back with error message.
      Session::flash('error', 'uploaded file is not valid');
      return Redirect::to('upload');
    }
  }
}

Comment: which line cause problem ?
Answer: If you're not inside a class, just use function upload(), not public function upload().
If you're inside a class, the error lies before the code you've provided.
Answer: You need a context of class to use access identifiers.
Your code should be:
class MyClass {
    public function upload() {
      // getting all of the post data
      $file = array('image' => Input::file('image'));
      // setting up rules
      $rules = array('image' => 'required',); //mimes:jpeg,bmp,png and for max size max:10000
      // doing the validation, passing post data, rules and the messages
      $validator = Validator::make($file, $rules);
      if ($validator->fails()) {
        // send back to the page with the input data and errors
        return Redirect::to('upload')->withInput()->withErrors($validator);
      }
      else {
        // checking file is valid.
        if (Input::file('image')->isValid()) {
          $destinationPath = 'uploads'; // upload path
          $extension = Input::file('image')->getClientOriginalExtension(); // getting image extension
          $fileName = rand(11111,99999).'.'.$extension; // renameing image
          Input::file('image')->move($destinationPath, $fileName); // uploading file to given path
          // sending back with message
          Session::flash('success', 'Upload successfully');
          return Redirect::to('upload');
        }
        else {
          // sending back with error message.
          Session::flash('error', 'uploaded file is not valid');
          return Redirect::to('upload');
        }
      }
    }
}