text:
Q: return control to the transport I'm trying to simulate a situation where data is received by a server periodically. In my set up, I run one process that sets up the server and another process that sets up a bunch of clients (suffices to think of a single client). I have set up some of the code by putting together bits and pieces mostly from here. The server/clients communicate by sending messages using transport.write. First, the server tells the clients to start (this works fine AFAIK). The clients report back to the server as they make progress. What has me confused is that I only get these intermittent messages at the very end when the client is done. This could be a problem with buffer flush and I tried (unsuccessfully) things like This. Also, each message is pretty large and I tried sending the same message multiple times so the buffer would get cleared.
I suspect what I am seeing is a problem with returning the control to the transport but I can't figure out how to do away with it.
Any help with this or any other issues that jump up to you is much appreciated.
Server:
from twisted.internet import reactor, protocol

import time
import serverSideAnalysis
import pdb
#import bson, json, msgpack
import _pickle as pickle  # I expect the users to authenticate and not
                          # do anything malicious.

PORT = 9000
NUM = 1
local_scratch="/local/scratch"

class Hub(protocol.Protocol):
  def __init__(self,factory, clients, nclients):
    self.clients = clients
    self.nclients = nclients
    self.factory = factory
    self.dispatcher = serverSideAnalysis.ServerTalker(NUM, self,
          local_scratch)

  def connectionMade(self):
    print("connected to user" , (self))
    if len(self.clients) < self.nclients:
      self.factory.clients.append(self)
    else:
      self.factory.clients[self.nclients] = self
    if len(self.clients) == NUM:
      val = input("Looks like everyone is here, shall we start? (Y/N)")
      while (val.upper() != "Y"):
        time.sleep(20)
        val = input("Looks like everyone is here, shall we start??? (Y/N)")
      message = pickle.dumps({"TASK": "INIT", "SUBTASK":"STORE"})
      self.message(message) # This reaches the client as I had expected

  def message(self, command):
    for c in self.factory.clients:
      c.transport.write(command)

  def connectionLost(self, reason):
    self.factory.clients.remove(self)
    self.nclients -= 1

  def dataReceived(self, data):
    if len(self.clients) == NUM:
      self.dispatcher.dispatch(data)

class PauseTransport(protocol.Protocol):
  def makeConnection(self, transport):
    transport.pauseProducing()

class HubFactory(protocol.Factory):
  def __init__(self, num):
    self.clients = set([])
    self.nclients = 0
    self.totConnections = num

  def buildProtocol(self, addr):
    print(self.nclients)
    if self.nclients < self.totConnections:
      self.nclients += 1
      return Hub(self, self.clients, self.nclients)
    protocol = PauseTransport()
    protocol.factory = self
    return protocol

factory = HubFactory(NUM)
reactor.listenTCP(PORT, factory)
factory.clients = []
reactor.run()

Client:
from twisted.internet import reactor, protocol
import time
import clientSideAnalysis
import sys

HOST = 'localhost'
PORT = 9000
local_scratch="/local/scratch"

class MyClient(protocol.Protocol):

  def connectionMade(self):
    print("connected!")
    self.factory.clients.append(self)
    print ("clients are ", self.factory.clients)

    self.cdispatcher = clientSideAnalysis.ServerTalker(analysis_file_name, local_scratch, self)

  def clientConnectionLost(self, reason):
    #TODO send warning
    self.factory.clients.remove(self)

  def dataReceived(self, data): #This is the problematic part I think
    self.cdispatcher.dispatch(data)
    print("1 sent")
    time.sleep(10)
    self.cdispatcher.dispatch(data)
    print("2 sent")
    time.sleep(10)
    self.cdispatcher.dispatch(data)
    time.sleep(10)

  def message(self, data):
    self.transport.write(data)

class MyClientFactory(protocol.ClientFactory):
  protocol = MyClient

if __name__=="__main__":
  analysis_file_name = sys.argv[1]

  factory = MyClientFactory()
  reactor.connectTCP(HOST, PORT, factory)
  factory.clients = []
  reactor.run()

The last bit of relevant information about what the dispatchers do.
In both cases, they load the message that has arrived (a dictionary) and do a few computations based on the content. Every once in a while, they use the message method to communicate with thier current values.
Finally, I'm using python 3.6. and twisted 18.9.0

A: The way you return control to the reactor from a Protocol.dataReceived method is you return from that method.  For example:
def dataReceived(self, data):
    self.cdispatcher.dispatch(data)
    print("1 sent")

If you want more work to happen after this, you have some options.  If you want the work to happen after some amount of time has passed, use reactor.callLater.  If you want the work to happen after it is dispatched to another thread, use twisted.internet.threads.deferToThread.  If you want the work to happen in response to some other event (for example, data being received), put it in the callback that handles that event (for example, dataReceived).


text:
Q: Create a GEOSGeometry from a FeatureCollection in GeoDango Is it possible create a GEOSGeometry from a FeatureCollection(GeoJSON)?
For instance: GEOSGeometry(json.dumps(fc)) where:
fc = { "type": "FeatureCollection",
"features": [
  { "type": "Feature",
    "geometry": {"type": "Point", "coordinates": [102.0, 0.5]},
    "properties": {"prop0": "value0"}
    },
  { "type": "Feature",
    "geometry": {
      "type": "LineString",
      "coordinates": [
        [102.0, 0.0], [103.0, 1.0], [104.0, 0.0], [105.0, 1.0]
        ]
      },
    "properties": {
      "prop0": "value0",
      "prop1": 0.0
      }
    },
  { "type": "Feature",
     "geometry": {
       "type": "Polygon",
       "coordinates": [
         [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0],
           [100.0, 1.0], [100.0, 0.0] ]
         ]
     },
     "properties": {
       "prop0": "value0",
       "prop1": {"this": "that"}
       }
     }
   ]
 }

A: Something like this will do what you want:
import ast
from django.contrib.gis.geos import GeometryCollection, GEOSGeometry

def make_geometrycollection_from_featurecollection(feature_collection):
    geoms = []
    features = ast.literal_eval(feature_collection)
    for feature in features['features']:
        feature_geom = feature['geometry']
        geoms.append(GEOSGeometry(feature_geom))
    return GeometryCollection(tuple(geoms))

redpajama_set_name: RedPajamaStackExchange


text:
Q: Storing a one to many relationship in Node.js using Mongoose I have a very simple one to many relationship where a User has a list of Alerts. For this, I've defined the following schemas:
var userSchema = new Schema({
    email: String,
    alerts: [{type: Schema.Types.ObjectId, ref: 'Alert'}]
});
var User = mongoose.model('User', userSchema);

var alertSchema = new Schema({
    _creator: {type: Schema.Types.ObjectId, ref: 'User'},
    value: String,
});
var Alert = mongoose.model('Alert', alertSchema);

Now, I'm trying to create a function which creates a new Alert and adds it to an existing User from the database. I have the following code (removing error-handling so the code is shorter):
function createAlertForUser(userId, value) {
    User.findOne({_id: userId}, function (error, user) {

        var alert = new Alert({
            _creator: userId,
            value: value
        });

        alert.save(function (error, alert) {

            // push it to the user
            user.alerts.push(alert);
            user.save(function(error) {
                console.log("saved");
            });
        });
    });
}

However, when I check the database, I seem to be saving null values to the User's list of alerts. Any ideas what I'm missing?

A: You try to push a whole Alert object to an array of ObjectId.
Try this instead:
user.alerts.push(alert.id);

or
user.alerts.push(alert._id);

both are correct.


text:
Q: Need help in displaying all the columns, there is missing data I am trying to sort a txt file through 3rd column in c#. I can see 4 rows beneath my columns but the text file contains a lot more rows. I also need to get one more functionality working and that is removing duplicate data from the display. {If data in the first and second column is the same as another row then remove one instance from the display. data is case sensitive i.e. broc is not the same as BRoc}. Help appreciated. My code is as follows. Please note that the txt file is a TSV and not a CSV.
     using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;
namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            var records = (from l in File.ReadAllLines(@"d:\data\542112107\Desktop\project 1\Project1\Project1\bin\Debug\instance_test.txt")
                           let pieces = l.Split('\t')
                           select new { Col1 = pieces[0], Col2 = pieces[1], Col3 = pieces[2], Col4 = pieces[3] })

                .Skip(1)

                .Distinct()
                .OrderBy(c => c.Col3);

            for (int i = 0; i < 99; i++)
            {

            } foreach (var r in records)
            { Console.WriteLine("{0}, {1}, {2},{3}", r.Col1, r.Col2, r.Col3, r.Col4); }

            Console.WriteLine();
            Console.WriteLine("Done");
            Console.ReadLine();
        }
    }
}

Here is the sample input:(\n is new line)
Heading 1   Heading 2     Heading3    Heading 4

ascvad3124        adfdasfData            asasffasf       adsfasfasdf
asf123134Data      dasfasdfdasfData        Dasfasfata      asdfasdfadsf
123123fData       asdfdasfsData        asdfasdfasdf          sadvsdfdaf

A: So the first issue is that you're not ordering on the third column's value; you're ordering on the second letter of the third column's value.  Change c.Col3[1] to just c.Col3 when ordering to actually order on the third column.
Another issue is that you're grouping on the concatenation of all of the fields; this isn't particularly safe.  Here "ab", "c", "d", "e" will be considered equal to "a", "bc", "d", "e".  You can just call Distinct instead of GroupBy.  Anonymous objects properly override Equals an GetHashCode to be based on the underlying properties, not the reference, so this will work just fine.
Next, You can use ReadLines instead of ReadAllLines to lazily read in the lines, instead of eagerly loading in all of the lines when you are only going to go and process the data lazily anyway.


text:
Q: Random ultrametric trees I've implemented a program on python which generates random binary trees. So now I'd like to assign to each internal node of the tree a distance to make it ultrametric. Then, the distance between the root and any leaves must be the same. If a node is a leaf then the distance is null. Here is a node :
class Node() :
    def __init__(self, G = None , D = None) :
        self.id = ""
        self.distG = 0
        self.distD = 0
        self.G = G
        self.D = D
        self.parent = None

My idea is to set the distance h at the beginning and to decrease it as an internal node is found but its working only on the left side.
def lgBrancheRand(self, h) :
    self.distD = h
    self.distG = h
    hrandomD = round(np.random.uniform(0,h),3)
    hrandomG = round(np.random.uniform(0,h),3)
    if self.D.D is not None :
        self.D.distD = hrandomD
        self.distD = round(h-hrandomD,3)
        lgBrancheRand(self.D,hrandomD)
    if self.G.G is not None :
        self.G.distG = hrandomG
        self.distG = round(h-hrandomG,3)
        lgBrancheRand(self.G,hrandomG)

A: In summary, you would create random matrices and apply UPGMA to each.
More complete answer below
Simply use the UPGMA algorithm. This is a clustering algorithm used to resolve a pairwise matrix.
You take the total genetic distance between two pairs of "taxa" (technically OTUs) and divide it by two. You assign the closest members of the pairwise matrix as the first 'node'. Reformat the matrix so these two pairs are combined into a single group ('removed') and find the next 'nearest neighbor' ad infinitum. I suspect R 'ape' will have a ultrametric algorhithm which will save you from programming. I see that you are using Python, so BioPython MIGHT have this (big MIGHT), personally I would pipe this through a precompiled C program and collect the results via paup that sort of thing. I'm not going to write code, because I prefer Perl and get flamed if any Perl code appears in a Python question (the Empire has established).
Anyway you will find this algorhithm produces a perfect ultrametric tree. Purests do not like ultrametric trees derived throught this sort of algorithm. However, in your calculation it could be useful because you could find the phylogeny from real data , which is most "clock-like" against the null distribution you are producing. In this context it would be cool.

You might prefer to raise the question on bioinformatics stackexchange.


text:
Q: Android Room Migration Strategy Is there any way to instruct Room to simply delete the database and recreate it if the schema has changed? Similar to the migration strategy seen in Entity framework commonly used in the early development of a app.
As I'm in the early stages of development of the app and schema changes will be frequent meaning writing migrations and changing version numbers would be a waste of my time.
Thanks

A: You can use fallbackToDestructiveMigration(). Usage pattern:
Room.databaseBuilder(...)
    .fallbackToDestructiveMigration()
    .build();

A: Add a Debug flag and delete the database before creating it. Something like Android Room - auto increment @database version number?
If you do not want it on every run then catch the Exception and then delete and create.
This should not be done on release builds though.


text:
Q: If every point of a topological space $X$ has a closed neighbourhood that is $T_2$ (as subspace), then $X$ is $T_2$. I have tried the problem in the following way-
Let $x,y$ be two distinct points in $X$ and let $x\in A$ and $y\in B$ where $A,B$ are closed neighbourhoods of $x,y$ respectively and $T_2$. Let $U_1$ and $U_2$ be open sets such that $x\in U_1\subset A$ and $y\in U_2\subset B$.
Case 1: If $y\notin A$, then take $V=A^c$ and $U=U_1$. Then $U\cap V=\emptyset $ and $y\in V$ and $x\in U$.
Case 2: If $x\notin B$ then take $U=B^c$, $V=V_1$. Then $U\cap V=\emptyset$ and $x\in U$, $y\in V$.
But I'm stuck with the case $x\in B$ and $y\in A$ i.e. $x,y\in A\cap B$.
Can anyone help me in this regard? Thanks for your help in advance.

A: In that last case: $A \cap B$ is Hausdorff, so there are open (in $A \cap B$) sets $O_1, O_2$ containing $x$ resp. $y$ that are disjoint.
So $O_i = (A \cap B ) \cap O'_i$, $O'_i$ open in $X$, $i=1,2$.
But then $U_1 \cap O'_1$ and $U_2 \cap O'_2$ disjoint open neighbourhoods of $x,y$ are as required.


text:
Q: Xcode Codesign error: timestamps differ My attempts at signing my application within XCode are failing with an error "Code signing failed: check that the identity you selected is valid".
Since my certificates all check out as valid I tried using the codesign utility in Terminal.
When I run it with these parameters:
codesign --force --deep  -s
I get this cryptic error:
timestamps differ by 230 seconds - check your system clock
I have research this error in the documentation and all over the web and found nothing.
Any ideas ?
Thank you.
Update - a few days later: I was able to dispense with this problem by getting fresh certificates and signing identity and doing a "Clean Build Folder" (hold the option key down when choosing Clean Build).

A: What works for me was to use "Set date and time automatically" in my date & Time Control panel. After doing this the timestamps error disappeared and I was able to codesign. Daniel

A: $sudo ntpdate -u time.apple.com

worked for me.

A: Sometimes the profiles may get messed up. In those cases I download them again. And (using the Finder) activate them by opening the profiles.
Nothing really spectacular happen, occasionally you may see the profiles flashing or being updated in Xcode.
After that it normally works.

A: We just had the same error in our automated build, which calls codesign
timestamps differ by XXX seconds - check your system clock

turns out it was caused by automatic XCode update, which did not have the EULA accepted. The fix was to login to the machine, run XCode.app and accept the T&Cs on startup.


text:
Q: Attempting to upload a pdf from a html form Here I'm trying to upload a PDF file from a html form. But the file is not being uploaded.
HTML file:
<form action="Upload.php" method="post" enctype="multipart/form-data">
    <input type="file" name="fileToUpload"  accept="application/pdf" id="fileToUpload">
    <input type="submit" value="Upload" name="submit">
</form>

Upload.php file:
move_uploaded_file ($_FILES['fileToUpload'] ['tmp_name'], "uploads/{$_FILES['fileToUpload'] ['name']}");

A: Check you have created "upload" folder in your root directory.

A: edit in your upload.php

move_uploaded_file ($_FILES['fileToUpload'] ['tmp_name'], "uploads/".$_FILES['fileToUpload'] ['name']);

also check permission to your upload folder to 777


text:
Q: Passing parameters to a saved query in MS Access Ok, I tried every possible situation from SO, and none of it did the job.
I have a problem calling a saved query which requires 4 parameters to be passed (talking about access database), and I have a simple code :
params = ()
sql_saldo = "{CALL KUP_BalansKupDosp(204701,0,#3/5/2020#,0)}"
saldo = cursor.execute(sql_saldo)
for row in saldo.fetchall():
    print(row)

This works!
But since I need those parameters to be dynamic, when I try :
params = ('204701','0,#3/5/2020#','0')
sql_saldo = "{CALL KUP_BalansKupDosp(?,?,?,?)}"
saldo = cursor.execute(sql_saldo, params)
for row in saldo.fetchall():
    print(row)

I get an error Data type mismatch in criteria expression
This is original parameter definition
PARAMETERS InKupID Long, InSekID Long, InDatum DateTime, InToler Currency = 1;
So it takes, string, string, datetime, and int i suppose.
So when I try with :
today_row = date.today()
today = today_row.strftime("%d/%m/%Y")
params = (204701,0,today,0)
sql_saldo = "{CALL KUP_BalansKupDosp(?,?,?,?)}"
saldo = cursor.execute(sql_saldo, params)
for row in saldo.fetchall():
    print(row)

I also get the same error, i even tried with every possible combo and I just cant figure it out.
PS. My connection is working great since I have 10 more queries besides this one.
Someone had a similar problem?

A: I manage to solve it with this :
params = (204701, 0, today, 0)
sql_saldo = "{CALL KUP_BalansKupDosp(%s,%s,%s,%s)}" % params
saldo = cursor.execute(sql_saldo)
for row in saldo.fetchall():
    print(row)

A:
This is original parameter definition PARAMETERS InKupID Long, InSekID Long, InDatum DateTime, InToler Currency = 1; So it takes, string, string, datetime, and int i suppose.

No. In Access DDL, Long is "Long Integer" and Currency is a numeric value similar to Decimal(18, 4).
To avoid the SQL injection vulnerabilities present in the other answer, we need to use a parameterized query and pass the appropriate types.
params = (204701, 0, datetime.datetime(2020, 3, 5), Decimal("19.95"))
sql_saldo = "{CALL KUP_BalansKupDosp(?,?,?,?)}"
cursor.execute(sql_saldo, params)
for row in cursor.fetchall():
    print(row)


text:
Q: How to make an array of matrix (of varying sizes) I'm trying to get to grips with matlab, so this question is more about syntax than anything else.
I want to create a vector (1xn) of matrices. The matrices are all possibly of different dimensions eg. matrix 1 = 4 x 5, matrix 2 = 5 x 6 etc.
I tried using a for loop, but I had the following error:
Subscripted assignment dimension mismatch.

A: You can store an array of matrices of different sizes as a cell array of matrices. Often you'll want to create these cell arrays dynamically using the arrayfun function which will do this for you if you set the UniformOutput option to 0.
Example:
cols = [4 5 6];
rows = [1 2 3];
A = arrayfun(@(i) zeros(rows(i),cols(i)),1:3,'UniformOutput',0);
A{:}

Outputs:
ans =

     0     0     0     0

ans =

     0     0     0     0     0
     0     0     0     0     0

ans =

     0     0     0     0     0     0
     0     0     0     0     0     0
     0     0     0     0     0     0


text:
Q: A question about earth ground and current loop
If the live wire in above illustration touches to the metal case, a high short circuit current will flow to the earth through the safety earth wire and the fuse will trip.
Now imagine a 9V battery staying on a wooden table. If now its plus terminal is tied to the earth through a wire almost no current will flow.
Above two points shows that it is not the case that the earth is a reservoir that sucks all electrons, but simply current needs a loop to flow.
In the battery case it is obvious that there is no loop because the negative terminal is floating.
But what is the loop in the first AC case? Is that the AC generator star connection? Can you draw this loop to illustrate better?

A: Any mains wiring installation requires a safety earthing system, or grounding electrode system - typically to grounding rods or a steel water pipe.
Then, the transformer's output is grounded:  One conductor is picked to be "neutral", or a hypothetical point in the middle is picked using transformer tricks, and that is pegged to the grounding electrode to create an artificial relationship with ground.  Of course this is also tied to those green ground wires in the wiring.
Why?  To give a return path for fault currernt, and to keep the system voltages from "floating" or "rattling" at arbitrary random potentials.  For instance if the 2400V supply transformer had a weak primary-secondary fault, it might "pull up" the secondary outputs up to 2400V, so now your voltages are 2280V, 2400V, and 2520V.  Trouble is, your stuff is not insulated for 2520V.
In residential, the neighborhood poletop transformer has a ground rod and a neutral-ground bond.  Each house's main service panel also has a grounding electrode and its own neutral-ground bond. They must all be in sync, or you will create current loops through your lawn, and make your meter spin.  But if you own your own transformer, you can ground any way you want.
Imagine you have a supply transformer with secondary taps at 0V, 120V, 123V, and 240V.   You connect 0V to pole L1, 120V to neutral, 123V to ground, and 240V to pole L2.   At this point you would have common North American split-phase power, with L1 and L2 both 120V from neutral.  But with a twist: neutral would be biased 3V away from ground.  That's weird, but it still serves all the purposes of grounding: it keeps neutral near ground, gives a path for fault current, and assures sane voltages on all the conductors.

Why does your hot-ground fault complete a circuit? Because we added that neutral-ground bond so it would do that.
If you prefer, you could run an isolated system where hot and neutral have no relationship with ground, it is unbonded.   In that case, your first ground fault becomes your ground bond.  I have had this happen with a panel fed from an onsite transformer that unknowingly did not have a neutral-ground bond.  An L1-ground fault biased the entire system 120V from where it should've been, with L2 now 240V from ground and neutral 120V from ground.   I found this out when I deenergized a circuit on L2 and flashed its hot to ground just to make sure it was off; rather than get a blinding arc flash, I got a tiny fizzle and the circuit lit back up!  Not good, though.
At this point, your second ground fault then starts tripping breakers.
An isolated system makes sense when you have engineering staff on premises regularly checking for ground faults.  They catch the first one before a second one occurs.

No one has ever claimed that earth draws all electrons to it.  A lot of people think electricity wants to "return to earth", that's only true for lightning and ESD.   Artificial electricity wants to return to source.

A: What is different is that for a battery there is not other connection to ground, this is not the case with the mains.
In the mains, the neutral connection is actually grounded as it enters your building, or at the transformer.
As such shorting the live wire to the case is really shorting the live wire to the neutral side of the transformer through the ground line creating a loop, and, as you have expressed, large current flows till the fuse of breaker trips.

simulate this circuit – Schematic created using CircuitLab
Which is why this is dangerous...

With an isolation transformer you isolate the power from ground and there is no return path.


text:
Q: Karma + Webpack testing Unexpected token '/' I'm trying to setup my tests for angular,
but I keep getting the following error:
PhantomJS 2.1.1 (Windows 8 0.0.0) ERROR
  SyntaxError: Unexpected token '/'
  at app/components/dropdown/dropdown.spec.ts:1

PhantomJS 2.1.1 (Windows 8 0.0.0) ERROR
  SyntaxError: Unexpected token '/'
  at app/components/dropdown/dropdown.spec.ts:1

but I don't know what might be wrong, these are my files:
karma.conf.js
var WebpackConfig = require('./webpack.config.js');

// Karma configuration
// Generated on Wed Dec 30 2015 11:13:38 GMT-0500 (EST)

module.exports = function (config) {
    config.set({

        // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: '.',

        files: [
            'app/**/*.spec.ts'
        ],

        // frameworks to use
        // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
        frameworks: ['mocha', 'chai'],

        // list of files to exclude
        exclude: [
            'node_modules'
        ],

        // test results reporter to use
        // possible values: 'dots', 'progress'
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        reporters: ['progress', 'dots'],

        // web server port
        port: 9876,

        // enable / disable colors in the output (reporters and logs)
        colors: true,

        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: true,

        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        browsers: ['PhantomJS'],

        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
        singleRun: false,

        // Concurrency level
        // how many browser should be started simultaneous
        concurrency: Infinity,

        preprocessors: {
            'app/**/*.spec.ts': ['webpack']
        },

        webpack: WebpackConfig,

        webpackMiddleware: {
            noInfo: true
        },

        plugins: [
            require('karma-mocha'),
            require('karma-chai'),
            require('karma-phantomjs-launcher'),
            require('karma-webpack')
        ]
    });
};

webpack.config.js
var Loaders = require('./webpack/loaders');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
    entry: {
        'bundle': 'app/core/bootstrap.ts'
    },
    output: {
        path: 'public',
        library: '[name]',
        filename: '[name].js'
    },
    resolve: {
        root: __dirname,
        extensions: ['', '.ts', '.js', '.json']
    },
    resolveLoader: {
        modulesDirectories: ['node_modules']
    },
    devtool: 'source-map',
    plugins: [
        new HtmlWebpackPlugin({
            template: 'app/index.html',
            inject: 'body',
            hash: true
        })
    ],
    module: {
        loaders: Loaders
    }
};

there is only one test:
dropdown.spec.ts
import '../../core/tests.ts';
import {chai} from '../../core/tests.ts';

var expect = chai.expect;

describe('Unit tests for DropDown component', () => {

    describe('2 + 4', () => {

        it('should be 6', (done) => {
            expect(2 + 4).to.equal(6);
            done();
        });

        it('should not be 7', (done) => {
            expect(2 + 4).to.not.equals(7);
            done();
        });

        it('should be 10', (done) => {
            expect(6 + 4).to.equal(10);
            done();
        });
    });

});

tests.ts
require('../../node_modules/mocha/mocha.js');
export var chai = require('../../node_modules/chai/chai.js');

package.json
{
  "name": "proj",
  "version": "0.0.1-beta2",
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "angular-mocks": "^1.5.3",
    "autoprefixer": "^6.3.3",
    "bootstrap-loader": "^1.2.1",
    "browser-sync": "^2.17.5",
    "browser-sync-webpack-plugin": "^1.1.3",
    "chai": "^3.5.0",
    "constants": "0.0.2",
    "css-loader": "^0.25.0",
    "extract-text-webpack-plugin": "^1.0.1",
    "file-loader": "^0.9.0",
    "gulp": "^3.9.0",
    "gulp-connect": "^5.0.0",
    "gulp-ngdocs": "^0.3.0",
    "html-webpack-plugin": "^2.24.0",
    "html-webpack-template": "^5.4.1",
    "imports-loader": "^0.6.5",
    "karma": "^1.3.0",
    "karma-chai": "^0.1.0",
    "karma-chrome-launcher": "^2.0.0",
    "karma-cli": "^1.0.1",
    "karma-coverage": "^1.1.1",
    "karma-mocha": "^1.1.1",
    "karma-phantomjs-launcher": "^1.0.2",
    "karma-sourcemap-loader": "^0.3.7",
    "karma-webpack": "^1.8.0",
    "mocha": "^3.1.2",
    "ng-annotate-webpack-plugin": "^0.1.2",
    "node-sass": "^3.4.2",
    "phantomjs": "^2.1.7",
    "postcss-loader": "^1.0.0",
    "protractor": "^4.0.9",
    "raw-loader": "^0.5.1",
    "resolve-url-loader": "^1.4.3",
    "rimraf": "^2.5.0",
    "sass-loader": "^4.0.2",
    "style-loader": "^0.13.0",
    "ts-loader": "^0.9.5",
    "tslint": "^3.2.1",
    "tslint-loader": "^2.1.0",
    "typescript": "1.8.10",
    "url-loader": "^0.5.7",
    "webpack": "^1.13.2",
    "webpack-config": "^6.2.0",
    "webpack-dev-server": "^1.14.0",
    "webpack-stream": "^3.1.0"
  },
  "dependencies": {
    "angular": "^1.5.8",
    "angular-ui-router": "^0.3.1",
    "socket.io-client": "^1.5.0"
  },
  "optionalDependencies": {
    "fsevents": "1.0.14"
  }
}

A: If you use parametr "library" in your webpack.config.js, your global variable is given a name consisting of the file path and file name. If you open console in the real browser, you can see:
enter image description here
Change your karma.config.js:

var WebpackConfig = require('./webpack.config.js');
WebpackConfig.output.library = false;


text:
Q: ManyToOne Lazy loading not working Spring boot I have make the rest api using Spring boot. It has two entities employee and department. Employee has department object so relation is ManyToOne. It is unidirectional. Department do not have the employees list. When I hit the employees GET method endpoint I am getting com.fasterxml.jackson.databind.exc.InvalidDefinitionException Exception. Please tell me how to solve it.
Employee Class:
@Entity
@Table(name = "employees")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String firstName;
private String lastName;
private Integer salary;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="department_id",referencedColumnName = "id",nullable = false)
private Department department;

Department Class:
@Entity
@Table(name = "departments")
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String name;

Employee Service:
@Service
public class EmployeeService {

private final EmployeeRepository employeeRepository;

@Autowired
public EmployeeService(EmployeeRepository employeeRepository) {
    this.employeeRepository = employeeRepository;
}

public List<Employee> getAllEmployees(){
    return employeeRepository.findAll();
}

public Employee getEmployeeById(Integer id){
    Optional<Employee> optionalEmployee = employeeRepository.findById(id);
    if(optionalEmployee.isEmpty()){
        throw new IllegalStateException("Department does not exists");
    }
    return optionalEmployee.get();
}

public Employee createEmployee(Employee employee){
    return employeeRepository.save(employee);
}

Employee Controller:
@RestController
@RequestMapping(path = "/employees")
public class EmployeeController {

private final EmployeeService employeeService;

@Autowired
public EmployeeController(EmployeeService employeeService) {
    this.employeeService = employeeService;
}

@GetMapping
public List<Employee> getAllDepartments(){
    return employeeService.getAllEmployees();
}
   @PostMapping
public Employee createEmployee(@RequestBody Employee employee){
    return employeeService.createEmployee(employee);
}}

A: You have to put @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) annotation in ManyToOne relationship mapping


text:
Q: Generating a random string using RandomNumberGenerator - Is it random enough? I'm generating random strings that ideally should be unique (I'm checking uniqueness as they are inserted into the DB), the strings are 12 characters long.
Here is my code
var alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var uniqueCode = new char[12];
for (var i = 0; i < codeLength; i++)
{
   uniqueCode[i] = alphabet[RandomNumberGenerator.GetInt32(alphabet.Length)];
}

If I'm using RandomNumberGenerator which is cryptographic do i need to worry about adding any other uniqueness? Masking, etc
Looking at the C# port of nanoId i can see there is some masking but is this really needed if RandomNumberGenerator is truly random ?
NanoId Masking Example
        internal static int Clz32(int x)
        {
            const int numIntBits = sizeof(int) * 8; //compile time constant
            //do the smearing
            x |= x >> 1;
            x |= x >> 2;
            x |= x >> 4;
            x |= x >> 8;
            x |= x >> 16;
            //count the ones
            x -= x >> 1 & 0x55555555;
            x = (x >> 2 & 0x33333333) + (x & 0x33333333);
            x = (x >> 4) + x & 0x0f0f0f0f;
            x += x >> 8;
            x += x >> 16;
            return numIntBits - (x & 0x0000003f); //subtract # of 1s from 32
        }

https://github.com/codeyu/nanoid-net/blob/master/src/Nanoid/Nanoid.cs


text:
Q: SVG textPath with linear gradient is damaged in Safari The textPath is damaged when I fill linear gradient.
How to fix it?
Thanks.
[[the broken image]]: https://i.stack.imgur.com/200t3.png

<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:svgjs="http://svgjs.dev/svgjs" width="1000" height="1000">
  <g font-size="42.5" font-weight="800">
<path d="M 400, 400
      m -100, 0
      a 100, 100 0 1,0 200, 0
      a 100, 100 0 1,0 -200, 0" fill="transparent" stroke="black" id="SvgjsPath1000"></path>
<circle r="4" cx="400" cy="400" fill="#000000"></circle>
<text stroke-width="10" svgjs:data="{"leading":"1.3"}">
  <textPath xlink:href="#SvgjsPath1000" fill="transparent" stroke="#ffffff" svgjs:data="{"leading":"1.3"}">
    <tspan alignment-baseline="middle">RRRRRRRRRRRRRRRRRRRRR</tspan>
  </textPath>
</text>
<text svgjs:data="{"leading":"1.3"}">
  <textPath xlink:href="#SvgjsPath1000" fill="url("#SvgjsLinearGradient1001")" svgjs:data="{"leading":"1.3"}">
    <tspan alignment-baseline="middle">RRRRRRRRRRRRRRRRRRRRR</tspan>
  </textPath>
</text>
  </g>
  <defs>
<linearGradient x1="0%" y1="0%" x2="100%" y2="0%" id="SvgjsLinearGradient1001">
  <stop offset="0" style="stop-color:#007cf0"></stop>
  <stop offset="1" style="stop-color:#ff0080"></stop>
</linearGradient>
  </defs>
</svg>

A: Apparently, a safari specific rendering bug when applying gradients to <textPath> elements.
I could also reproduce this issue with a simplified example (testing in iOS safari):

<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
  <defs>
    <linearGradient id="myGradient" gradientTransform="rotate(90)">
      <stop offset="5%" stop-color="gold" />
      <stop offset="95%" stop-color="red" />
    </linearGradient>
  </defs>
  <path
    id="MyPath"
    fill="none"
    stroke="red"
    d="M10,90 Q90,90 90,45 Q90,10 50,10 Q10,10 10,40 Q10,70 45,70 Q70,70 75,50" />
  <text>
    <textPath fill="url('#myGradient')" href="#MyPath">Quick brown fox jumps over the lazy dog.</textPath>
  </text>
</svg>

Workaround: create a <mask> containing the text path:

body {
  background: #ccc
}

svg {
  width: 50%;
  border: 1px solid #000
}
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:svgjs="http://svgjs.dev/svgjs" viewBox="250 250 300 300">
  <defs>
    <linearGradient x1="0%" y1="0%" x2="100%" y2="0%" id="SvgjsLinearGradient1001">
      <stop offset="0" style="stop-color:#007cf0"></stop>
      <stop offset="1" style="stop-color:#ff0080"></stop>
    </linearGradient>
    <mask id="mask" x="0" y="0" width="200%" height="200%">
      <rect fill="#000" x="0" y="0" width="200%" height="200%" />
      <text>
        <textPath class="textPath" font-size="42.5" font-weight="800" href="#SvgjsPath1000" dominant-baseline="middle" fill="#fff">
          RRRRRRRRRRRRRRRRRRRRR
        </textPath>
      </text>
    </mask>
  </defs>
  <g>
    <path d="M 300 400 a 100 100 0 1 0 200 0 a 100 100 0 1 0 -200 0 z" fill="transparent" stroke="black" id="SvgjsPath1000" />
    <circle r="4" cx="400" cy="400" fill="#000000" />
    <text>
      <textPath class="textPath" font-size="42.5" font-weight="800" href="#SvgjsPath1000" dominant-baseline="middle" fill="transparent" stroke="#fff" stroke-width="10">
        RRRRRRRRRRRRRRRRRRRRR
      </textPath>
    </text>
    <rect mask="url(#mask)" fill="url(#SvgjsLinearGradient1001)" x="0" y="0" width="200%" height="200%" />
  </g>
</svg>


text:
Q: Invalid win32 Application Visual Studio Application I created an application in Visual Studio using VB.Net and service-based database. But when I run it on another computer, it gives an eror:

Invalid Win32 Application

It runs fine on my own computer in which I created it.
Please hellp

A: Check whether .Net Framework is installed in the target computer because you should have the .net framework installed in the computer in which you want to run your application.


text:
Q: Can we mix Mongodb dynamic attributes to an ActiveRecord model? We are using a dynamic attributes plugin similar to this:
http://codaset.com/joelmoss/dynamic-attributes
Which allows us to store dynamic attributes in our rails model.  Those dynamic attributes are in a single database column.  We are facing performance issues because of this and I am wondering if MongoId, MongoMapper or other rails plugins will allow us to keep some attribute in ActiveRecord (keeping the  < ActiveRecord::Base) but store the dynamic attributes in mongodb.  We want to do this because we need to keep using MySQL for most of our existing system, but use MongoDB to store dynamic attributes about some models.
Basically this is what I am talking about:
http://www.railsinside.com/plugins/242-quickly-add-couchdb-to-existing-rails-models-with-stuffing.html
This plugin does the exact same thing using CouchDB.

A: I don't see any reason that MongoDB can't handle the same thing.
MongoMapper should implement the ActiveRecord pattern. However, Mongo also has some simple drivers for Ruby. All in all, the concept of storing dynamic attributes is a perfect use-case for MongoDB.
If you don't mind skipping "ActiveRecord" you can probably cook up your own using the basic Mongo drivers with very little work.
If you can't figure out the steps to do this, I would suggest pinging the groups (http://groups.google.com/mongodb-user/) and asking Kyle Banker directly (he's their ruby expert).


text:
Q: Connect to service bus using python SAS token I need to connect to azure service bus using SAS token(generate and connect).
I don't see anything for the python implementation.
This link provides the implementation for Eventhubs -
https://learn.microsoft.com/en-us/rest/api/eventhub/generate-sas-token#python
Not sure where I can find the python implementation for servicebus.

A: I have found a way where you can do it for the ServiceBusService Class.
After running "pip install azure.servicebus", I imported it as:
from azure.servicebus.control_client import ServiceBusService

The ServiceBusService constructor takes an argument called "authentication", which isn't specified by default.
If you got into the ServiceBusService init file, you can see how authentication is handled in more detail.
if authentication:
        self.authentication = authentication
    else:
        if not account_key:
            account_key = os.environ.get(AZURE_SERVICEBUS_ACCESS_KEY)
        if not issuer:
            issuer = os.environ.get(AZURE_SERVICEBUS_ISSUER)

        if shared_access_key_name and shared_access_key_value:
            self.authentication = ServiceBusSASAuthentication(
                shared_access_key_name,
                shared_access_key_value)
        elif account_key and issuer:
            self.authentication = ServiceBusWrapTokenAuthentication(
                account_key,
                issuer)

If you don't pass a custom authentication object, it will then try to use the ServiceBusSASAuthentication class, which is the default if you populate the shared_access_key_name and shared_access_key_value.
So if you jump into the ServiceBusSASAuthentication class, you'll notice something useful.
class ServiceBusSASAuthentication:
    def __init__(self, key_name, key_value):
        self.key_name = key_name
        self.key_value = key_value
        self.account_key = None
        self.issuer = None

    def sign_request(self, request, httpclient):
        request.headers.append(
            ('Authorization', self._get_authorization(request, httpclient)))

    def _get_authorization(self, request, httpclient):
        uri = httpclient.get_uri(request)
        uri = url_quote(uri, '').lower()
        expiry = str(self._get_expiry())

        to_sign = uri + '\n' + expiry
        signature = url_quote(_sign_string(self.key_value, to_sign, False), '')

        auth_format = 'SharedAccessSignature sig={0}&se={1}&skn={2}&sr={3}'  # <----awww, yeah
        auth = auth_format.format(signature, expiry, self.key_name, uri)

        return auth  # <--after inserting values into string, the SAS Token is just returned.

    def _get_expiry(self):  # pylint: disable=no-self-use
        '''Returns the UTC datetime, in seconds since Epoch, when this signed
        request expires (5 minutes from now).'''
        return int(round(time.time() + 300))

The sign_request function is the only function that will be directly referenced by the ServiceBusService class when it does authentication, but you'll notice that all its doing is adding an authentication header to a request that...IS IN THE FORMAT OF A SAS TOKEN.
So at this point I had all the information I needed to make my own authentication class. I made one that looked exactly like this.
class ServiceBusSASTokenAuthentication:
    def __init__(self, sas_token):
        self.sas_token = sas_token

    # this method is the one used by ServiceBusService for authentication, need to leave signature as is
    # even though we don't use httpClient like the original.
    def sign_request(self, request, httpclient):
        request.headers.append(
            ('Authorization', self._get_authorization())
        )

    def _get_authorization(self):
        return self.sas_token

I probably could get rid of the _get_auth function all together, but I haven't polished everything up yet.
So now if you call this class like so in the ServiceBusService constructor with a valid SAS Token, it should work.
            subscription_client = ServiceBusService(
                authentication=ServiceBusSASTokenAuthentication(sas_token=sas_token),
                service_namespace=service_namespace
            )

A: Once you create the Service Bus using Azure Portal, ServiceBusService object enables you to work with queues.
Follow this document for more information on creating the queue, sending message to queue, receiving message from a queue using python to programmatically access the Service Bus.


text:
Q: How to add custom claims to Azure AD authenticated user in ASP.Net Core application? We are building a ASP.net core Web API with Angular SPA client.  For Authentication we have implemented Azure AD with multi tenants.  For the Web API authentication/authorization we have followed this Microsoft sample.  This uses the Microsoft.Identity.Web MSAL library for authenticating the authorisation code that originated from the Angular SPA.  On the Azure AD application registration we manage the correct scope of the application, but we are not able to understand how claims are managed.
In previous applications I had run the authentication server IdentityServer4 as middleware in my application, allowing the authentication and issuing of claims in my application.  I was using UserManager to add or remove claims on the User.  Claims information was stored in the User tables of my database, and were then included in the issued cookie and available to the SPA and the Web API.
In the current application we are fully relying on Azure AD, and now I feel I am missing a piece of the puzzle to manage the user claims (and their inclusion on the cookie/token).  Question: How can I manage claims that are specific to our application while user management and authentication takes place on Azure AD rather than in my application?
To clarify: This Microsoft document mentions three ways of using application roles: Azure AD App roles, Azure AD Security Groups and Application Role manager.  It's the last one I feel is the correct functionality I need:

With this approach, application roles are not stored in Azure AD at all. Instead, the application stores the role assignments for each user in its own DB — for example, using the RoleManager class in ASP.NET Identity.

A small selection of the documentation I have reviewed but didn't give me the answers:

*

*This previously linked Microsoft document does mention using the RoleManager class in ASP.NET Identity, but does not explain how to implement this as integration with Azure AD such that the cookies/tokens include the roles (or roles converted to claims).

*I have read about using MS Graph schema extensions and including these in claims however, the article also states that any application with consent can read and write these extended properties.  Implying this is not a secure way to provide any claim to the application as the values could be touched from outside the application

*Documentation explaining how to verify user claims.

*Tailspin scenario, mentions using roles on the application rather than security groups.  But there is no indication or hint how this is included as claims in Azure AD.  And following this it's clear that it's not controlled in the application.

*This document and this explains about transforming claims or adding custom claims, but this is basis conditions on the user account rather than the application setting the claims.  These conditions would also need to be managed on the domain rather than in the application.

*Similar question?  But no answer.

A: After discussing with Microsoft Azure AD support, I conclude that this is not possible.

The below are the alternative approaches I have recognised.  Happy to hear about others that would be possible:
Following this article from Microsoft we can add roles with custom information, by using:

*

*Azure AD App Roles

*Azure AD Security Groups

*Or adding an Identity within the application, and then implementing RoleManager class.  This means the application database would hold an identity, somewhat defeating the purpose of Azure AD.

Other information can also be added to Microsoft Graph as described in this blog post by rasmustherkelsen.  However I don't think this appropriate for any security related items (such as permissions, or paid-for module licenses) as Microsoft explains in this article that:

extension properties are accessible by any consented application in an organization, not just for the application to which they are registered.

And so other applications could read and write to this properties if the tenant provides consent to this.
Edit: The Graph API has the ability to update the Application Roles.  This can be called by the application to securely update the Application Roles.
My research leads me to conclude that Azure AD cannot realistically be used by a multi tenant SaaS solution, as the sole identity provider. The application needs to provide some identity to manage additional claims, such as detailed application permissions and paid-for module access.

A: This document should be what you want.
You should add the app role into the manifest of Azure AD app which represents your Web API (here should be the service app TodoListService) by following the first example.
"appId": "8763f1c4-f988-489c-a51e-158e9ef97d6a",
"appRoles": [
    {
      "allowedMemberTypes": [
        "User"
      ],
      "displayName": "Writer",
      "id": "d1c2ade8-98f8-45fd-aa4a-6d06b947c66f",
      "isEnabled": true,
      "description": "Writers Have the ability to create tasks.",
      "value": "Writer"
    }
  ],
"availableToOtherTenants": false,

Then you need to assign users to this app role.
After the user sign in, you will get the app role in the token and you can verify it easily.
HttpContext.ValidateAppRole("Writer");

This app role is specific to your Web API application. When the user sign into other applications, app role Writer won't be available.

A: Don't have rep for comment but I am running into the same issue while trying to move authentication to MSAL.  If you run across the answer to using Role Manager please let me know.


text:
Q: Makefile/Cmake hide "conflicting types" error I am trying to compile a program in CLion and am getting the error "conflicting types" and "previous declaration of...".  This is because I have a function index() that is also in the string.h library.  I need this function to be named this for an assignment and am wondering if there is a way to hide this error with some cmake flag or something.

A: I found the issue and have fixed it. Within the project directory inside CLion, I navigated to cmake-build-debug/CMakeFiles/${ProjectName}.dir/flags.make. Inside that file, I changed the C_FLAGS = -O0 -std=gnu99 to C_FLAGS = -O0 -std=c11.
Additionally, I found that removing set(CMAKE_C_STANDARD 11) and replacing it with set(CMAKE_C_FLAGS "-std=c11") in the CMakeLists.txt resulted in the same outcome.


text:
Q: Can I post-process three.js on processing.js? Can I get the output of Three.js as a workable buffer on processing.js, so I can do some post-render processing with effects and overlays?

A: If you have access to the output in image form you can hand this over to your sketch by using something like this:
sketch:
addThreeJSImage(String datauri) {
  PImage img = loadImage(datauri);
  // trigger further code based on img
}

javascript (assuming sketch reference 'p'):
function doFunkyStuff(canvas) {
  imgdata = canvas.toDataURL('image/png');
  p.addThreeJSImage(imgdata);
}

This is assuming three.js gives you access to the canvas, of course, and the data it draws is "clean" (i.e. you didn't import any external images, because then cross-origin lockdown prevents you from reading the pixels; you'll only be able to write over them...)


text:
Q: WPF placement of Intellisense like PopUp below the selection start Hi I want to place a WPF Popup below the last character typed in a textbox just like we know it from intellisense in VS.
My actual Code looks like this is there a way to place it according the coordinates of the textboxex text?:
 <local:TextBoxAutoSuggestion Text="{Binding InputText, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
                                        x:Name="SearchPathTextBox"
                                        local:FocusExtension.IsFocused="{Binding IsFocusOnInputTextBox, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
                                        HorizontalAlignment="Stretch"
                                        Foreground="{DynamicResource Menu.Static.Foreground}"
                                        Background="Transparent"
                                        VerticalAlignment="Stretch"
                                        VerticalContentAlignment="Center"
                                        Height="45"
                                        Padding="5,0,30,0"
                                        Margin="0,0,0,0"
                                        CaretBrush="White"
                                        BindableSelectionStart="{Binding SelectionLengthInputText,Mode=TwoWay}">
          <i:Interaction.Triggers >
            <i:EventTrigger EventName="GotFocus">
              <i:InvokeCommandAction Command="{Binding TextBoxFocusedChangedCommand}" />
            </i:EventTrigger>
            <i:EventTrigger EventName="LostFocus">
              <i:InvokeCommandAction Command="{Binding TextBoxFocusedChangedCommand}" />
            </i:EventTrigger>
          </i:Interaction.Triggers>

          <local:TextBoxAutoSuggestion.InputBindings>
            <KeyBinding Command="{Binding EnterKeyPressedCommand}"
                        Key="Return" />
            <KeyBinding Command="{Binding TabKeyPressedCommandinTextBox}"
                        Key="Tab" />
            <KeyBinding Command="{Binding BackSpacePressedCommand}"
                        Key="Backspace" />
            <KeyBinding Command="{Binding SelectNextItemCommand}"
                        Key="Down" />
            <KeyBinding Command="{Binding SelectPreviousItemCommand}"
                        Key="Up" />

          </local:TextBoxAutoSuggestion.InputBindings>
        </local:TextBoxAutoSuggestion>
<Popup
             Width="300"
             Margin="0,0,0,0"
             StaysOpen="False"
             Visibility="{Binding IsPopUpOpened, Converter={StaticResource BooleanToVisibilityConverter}}"
             IsOpen="{Binding IsPopUpOpened, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
             PlacementTarget="{Binding ElementName=SearchPathTextBox}"
             Placement="Bottom"
             IsEnabled="{Binding IsPopUpEnabled, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
             >
      <ListBox Margin="0,0,0,0"
               Visibility="{Binding IsPopUpOpened, Converter={StaticResource BooleanToVisibilityConverter}}"
               ItemsSource="{Binding FilteredPossibleSegments}"
               Foreground="{DynamicResource Menu.Static.Foreground}"
               Background="Transparent"
               SelectedItem="{Binding SelectedSegment,Mode=TwoWay}"
               ScrollViewer.VerticalScrollBarVisibility="Disabled"
               Height="200"
                >
      </ListBox>
      </Popup>

The placement which I use right now is "Bottom".

A: I used horizontal offset property of the pop up and set it according the text length:
 <Popup
             Width="300"
             Margin="0,0,0,0"
             StaysOpen="False"
             Visibility="{Binding IsPopUpOpened, Converter={StaticResource BooleanToVisibilityConverter}}"
             IsOpen="{Binding IsPopUpOpened, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
             PlacementTarget="{Binding ElementName=SearchPathTextBox}"
             Placement="RelativePoint"
             IsEnabled="{Binding IsPopUpEnabled, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
             HorizontalOffset="{Binding HorizontalPopUpPosition, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
             VerticalOffset="50"

             >

I experimented with the horizontal and found the best with this you need to find the best option for your position in your window.
   HorizontalPopUpPosition =330+ InputText.Length*5;


text:
Q: weird positioning of the cursor in the UITextView I am writing from scratch growing UITextView in my swift app.
I put a textView on the view like this:

it is right above the keyboard.
The textView has constraints attached to the view: leading, bottom, top and trailing, all equals = 4.
The view has the following constraints:
trailing, leading, bottom, top and height
Height is an outlet in my code. I'm checking how many lines are in the textView and based on that I'm modifying height:
func textViewDidChange(textView: UITextView) { //Handle the text changes here
    switch(textView.numberOfLines()) {
    case 1:
        heightConstraint.constant = 38
        break
    case 2:
        heightConstraint.constant = 50
        break
    case 3:
        heightConstraint.constant = 70
        break
    case 4:
        heightConstraint.constant = 90
        break
    default:
        heightConstraint.constant = 90
        break
    }
}

The number of lines above is calculated by this extension:
extension UITextView{

  func numberOfLines() -> Int{
      if let fontUnwrapped = self.font{
          return Int(self.contentSize.height / fontUnwrapped.lineHeight)
      }
      return 0
  }
}

The initial height of the textView is 38.
The initial font size in the textView is 15.
Now, it works nice, when user starts typing new line, but the textView is not set within full bounds of the view. I mean by that the fact, that it looks like this:

and it should look like this:

Why there is this extra white space being added and how can I get rid of it?
Currently when new line appears there's this white space, but when user scrolls the textView to center the text and get rid of the white space - it is gone forever, user is not able to scroll it up again so the white line is there. So for me it looks like some problem with refreshing content, but maybe you know better - can you give me some hints?

A: Here is a bit different approach I use in the comment section of one of the apps I'm developing. This works very similar to Facebook Messenger iOS app's input field. Changed outlet names to match with the ones in your question.
//Height constraint outlet of view which contains textView.
@IBOutlet weak var heightConstraint: NSLayoutConstraint!
@IBOutlet weak var textView: UITextView!

//Maximum number of lines to grow textView before enabling scrolling.
let maxTextViewLines = 5
//Minimum height for textViewContainer (when there is no text etc.)
let minTextViewContainerHeight = 40

func textViewDidChange(textView: UITextView) {
    let textViewVerticalInset = textView.textContainerInset.bottom + textView.textContainerInset.top
    let maxHeight = ((textView.font?.lineHeight)! * maxTextViewLines) + textViewVerticalInset
    let sizeThatFits = textView.sizeThatFits(CGSizeMake(textView.frame.size.width, CGFloat.max))

    if sizeThatFits.height < minTextViewContainerHeight {
        heightConstraint.constant = minTextViewContainerHeight
        textView.scrollEnabled = false
    } else if sizeThatFits.height < maxHeight {
        heightConstraint.constant = sizeThatFits.height
        textView.scrollEnabled = false
    } else {
        heightConstraint.constant = maxHeight
        textView.scrollEnabled = true
    }
}

func textViewDidEndEditing(textView: UITextView) {
    textView.text = ""
    heightConstraint.constant = minTextViewContainerHeight
    textView.scrollEnabled = false
}

A: I'm using ASTextInputAccessoryView. It handles everything for you and is very easy to set up:

import ASTextInputAccessoryView

class ViewController: UIViewController {

    var iaView: ASResizeableInputAccessoryView!
    var messageView = ASTextComponentView()

    override func viewDidLoad() {
        super.viewDidLoad()

        let photoComponent = UINib
            .init(nibName: "PhotosComponentView", bundle: nil)
            .instantiateWithOwner(self, options: nil)
            .first as! PhotosComponentView

        messageView = ASTextComponentView(frame: CGRect(x: 0, y: 0, width: screenSize.width , height: 44))
        messageView.backgroundColor = UIColor.uIColorFromHex(0x191919)
        messageView.defaultSendButton.addTarget(self, action: #selector(buttonAction), forControlEvents: .TouchUpInside)

        iaView = ASResizeableInputAccessoryView(components: [messageView, photoComponent])
        iaView.delegate = self
    }
}

//MARK: Input Accessory View
extension ViewController {
    override var inputAccessoryView: UIView? {
        return iaView
    }

    // IMPORTANT Allows input view to stay visible
    override func canBecomeFirstResponder() -> Bool {
        return true
    }

    // Handle Rotation
    override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)

        coordinator.animateAlongsideTransition({ (context) in
            self.messageView.textView.layoutIfNeeded()
        }) { (context) in
            self.iaView.reloadHeight()
        }
    }
}

// MARK: ASResizeableInputAccessoryViewDelegate
extension ViewController: ASResizeableInputAccessoryViewDelegate {

    func updateInsets(bottom: CGFloat) {
        var contentInset = tableView.contentInset
        contentInset.bottom = bottom
        tableView.contentInset = contentInset
        tableView.scrollIndicatorInsets = contentInset
    }

    func inputAccessoryViewWillAnimateToHeight(view: ASResizeableInputAccessoryView, height: CGFloat, keyboardHeight: CGFloat) -> (() -> Void)? {

        return { [weak self] in
            self?.updateInsets(keyboardHeight)
            self?.tableView.scrollToBottomContent(false)
        }
    }

    func inputAccessoryViewKeyboardWillPresent(view: ASResizeableInputAccessoryView, height: CGFloat) -> (() -> Void)? {
        return { [weak self] in
            self?.updateInsets(height)
            self?.tableView.scrollToBottomContent(false)
        }
    }

    func inputAccessoryViewKeyboardWillDismiss(view: ASResizeableInputAccessoryView, notification: NSNotification) -> (() -> Void)? {
        return { [weak self] in
            self?.updateInsets(view.frame.size.height)
        }
    }

    func inputAccessoryViewKeyboardDidChangeHeight(view: ASResizeableInputAccessoryView, height: CGFloat) {
        let shouldScroll = tableView.isScrolledToBottom
        updateInsets(height)
        if shouldScroll {
            self.tableView.scrollToBottomContent(false)
        }
    }
}

Now you just need to set up the actions for the buttons of the AccessoryView.
// MARK: Actions
extension ViewController {

    func buttonAction(sender: UIButton!) {

        // do whatever you like with the "send" button. for example post stuff to firebase or whatever
        // messageView.textView.text <- this is the String inside the textField

        messageView.textView.text = ""
    }

    @IBAction func dismissKeyboard(sender: AnyObject) {
        self.messageView.textView.resignFirstResponder()
    }

    func addCameraButton() {

        let cameraButton = UIButton(type: .Custom)
        let image = UIImage(named: "camera")?.imageWithRenderingMode(.AlwaysTemplate)
        cameraButton.setImage(image, forState: .Normal)
        cameraButton.tintColor = UIColor.grayColor()

        messageView.leftButton = cameraButton

        let width = NSLayoutConstraint(
            item: cameraButton,
            attribute: .Width,
            relatedBy: .Equal,
            toItem: nil,
            attribute: .NotAnAttribute,
            multiplier: 1,
            constant: 40
        )
        cameraButton.superview?.addConstraint(width)

        cameraButton.addTarget(self, action: #selector(self.showPictures), forControlEvents: .TouchUpInside)
    }

    func showPictures() {

        PHPhotoLibrary.requestAuthorization { (status) in
            NSOperationQueue.mainQueue().addOperationWithBlock({
                if let photoComponent = self.iaView.components[1] as? PhotosComponentView {
                    self.iaView.selectedComponent = photoComponent
                    photoComponent.getPhotoLibrary()
                }
            })
        }
    }
}


text:
Q: my second "levelup" button is not working also update function is not getting called from fight and levelup functions html code
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <button id="btnAddMonster" type="button" onclick="addMonster()">Buy Monster</button>

    <button id="btnLevelUpMonster" type="button" onclick="levelUpMonster()">Levelup Monster</button>

    <button type="button" onclick="fight()">Fight</button>

        monster

</button>

javascript code
var Monster = [{
    "HitPoint" : 100,
    "Damage" : 5,
    "level" : 1
},
]
var log = ["Welcome to DungeonCircus",""]
var gold = 500;
var monsterLevel = 1;
var exp = 0;

function addMonster(){
    if (gold>=Monster.length*80){
        gold-=Monster.length*80
        var temp={};
        temp.level=monsterLevel;
        temp.Damage = 5*temp.level+Math.floor((Math.random()-Math.random())*0.8*temp.level);
        temp.HitPoint = 100*temp.level+Math.floor(10*(Math.random()-Math.random())*temp.level);
        Monster.push(temp);
        monstersInfoUpdate();
        document.getElementById("btnAddMonster").innerHTML="Add Monster ("+(Monster.length*80).toString()+")";
    }
    else{
        alert("Low on gold")
    }
}

function levelUpMonster(){
    if(exp>=monsterLevel * 10){
        exp-=monsterLevel * 10;
        monsterlevel += 1;
        document.getElementById("btnLevelUpMonster").innerHTML="LevelUp Monster ("+(monsterLevel*10).toString()+")";
        variablesUpdate();
    } else{
        alert("Low on exp")
    }

}

function fight(){
    var hpPoints=0;
    var damagePoints=0;
    var i;
    var l=Monster.length;
    for(i=0;i<Monster.length;i++){
        hpPoints+=Monster[i].HitPoint;
        damagePoints+=Monster[i].Damage;
    }
    gold+=damagePoints*80;
    exp += hpPoints;
    while(Monster.length){
        Monster.pop();
    }
    monstersInfoUpdate();
}

function monstersInfoUpdate(){
    var str="";
    var i=Monster.length;
    str+="
Monster : "+(i).toString()+"";
    for (var i=0;i<Monster.length;i++){

        str+="
 Level : "+Monster[i].level + "     HitPoints : " + Monster[i].HitPoint + "      Damage : " + Monster[i].Damage;
        document.getElementById("monstersInfo").innerHTML=str;

    }
    variablesUpdate();
}

function variablesUpdate(){
    var str="Gold : "+gold;
    str+=" Monster Level : "+monsterLevel;
    str+=" Exp : "+ exp;
    document.getElementById("variables").innerHTML=str;
    document.getElementById("btnAddMonster").innerHTML="Add Monster ("+(Monster.length*80).toString()+")";
    document.getElementById("btnLevelUpMonster").innerHTML="LevelUp Monster ("+(monsterLevel*10).toString()+")";
}

monstersInfoUpdate();
document.getElementById("btnAddMonster").innerHTML="Add Monster ("+(Monster.length*80).toString()+")";
document.getElementById("btnLevelUpMonster").innerHTML="LevelUp Monster ("+(monsterLevel*10).toString()+")";

document.getElementById("logs").innerHTML=log;

the "levelup monster" is not working as it should and the updatevariable function is not being called in levelup monster and updatemonsterInfo is not getting called in fight function. any help is appreciated. the buttons are working fine with alert message but it is not working when the given functions are called.
Added this to the code and the heroInfoUpdate is not getting called same problem as before

function heroesInfoUpdate(){
    var str="";
    var i=Heroes.length;
    str+="
Heroes : "+(i).toString()+"";
    for (i=0;i<Heroes.length;i++){

        str+="
 Level : "+Heroes[i].level + "     HitPoints : " + Heroes[i].HitPoint + "      Damage : " + Heroes[i].Damage;
        document.getElementById("heroesInfo").innerHTML=str;

    }
    variablesUpdate();
}

function addHero(){
    if (gold>=Heroes.length*80){
        gold-=Heroes.length*80
        var temp={};
        temp.level=heroesLevel;
        temp.Damage = 10*temp.level+Math.floor((Math.random()-Math.random())*0.8*temp.level);
        temp.HitPoint = 80*temp.level+Math.floor(10*(Math.random()-Math.random())*temp.level);
        Heroes.push(temp);
        heroesInfoUpdate();
    }
    else{
        alert("Low on gold")
    }
}

function levelUpHeroes(){
    if(exp>=HeroesLevel * 100){
        exp-=HeroesLevel * 100;
        heroLevel += 1;
        variablesUpdate();
    } else{
        alert("Low on exp")
    }

}

the new html
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <button id="btnAddMonster" type="button" onclick="addMonster();">Buy Monster</button>

    <button id="btnLevelUpMonster" type="button" onclick="levelUpMonster();">Levelup Monster</button>

    <button id="btnAddHero" type="button" onclick="addHero();">Buy Hero</button>

    <button id="btnLevelUpHero" type="button" onclick="levelUpHero();">Levelup Hero</button>

    <button type="button" onclick="fight()">Fight</button>

        HeroInfo

        monsterInfo

</button>

A: There is a typo in the LevelupMonster Function.
function levelUpMonster(){
    if(exp>=monsterLevel * 10){
        exp-=monsterLevel * 10;
        monsterlevel += 1; //==============> here should come monsterLevel "L" caps
        document.getElementById("btnLevelUpMonster").innerHTML="LevelUp Monster ("+(monsterLevel*10).toString()+")";
        variablesUpdate();
    } else{
        alert("Low on exp")
    }

}

A: function variablesUpdate(){
    var str="Gold : "+gold;
    str+=" Monster Level : "+monsterLevel;
    str+=" Exp : "+ exp;
    document.getElementById("variables").innerHTML=str;
    document.getElementById("btnAddMonster").innerHTML="Add Monster ("+(Monster.length*80).toString()+")";//the * operator needs to be seperated with a whitespace everywhere
    document.getElementById("btnLevelUpMonster").innerHTML="LevelUp Monster ("+(monsterLevel*10).toString()+")";
}

the * operator needs to be seperated with a whitespace everywhere most probably.
And there are some typos here and there.


text:
Q: Term in transformation to build a general bivariate normal. When using $Z_{1}, Z_{2} \sim \mathcal{N}(0,1)$ to build a general bivariate normal with arbitrary parameters $\mu_{X}, \mu_{Y}, \sigma_{X}, \sigma_{Y}, \rho$,  where does the term $\left[\rho Z_{1}+\sqrt{1-\rho^{2}} Z_{2}\right]$ in the transformation below come form ?
\begin{array}{l}
X=\sigma_{X} Z_{1}+\mu_{X} \\
Y=\sigma_{Y}\left[\rho Z_{1}+\sqrt{1-\rho^{2}} Z_{2}\right]+\mu_{Y}
\end{array}
Is this related to the variance-covariance matrix $\sum$ ?
Any clues appreciated, just getting started with bivariate normal theory.

A: Let $Z_{1}, Z_{2} \sim \mathcal{N}(0,1)$ then
$$
\begin{aligned}\left(\begin{array}{c}X \\ Y\end{array}\right) &=\boldsymbol{\mu}+\operatorname{Chol}(\boldsymbol{\Sigma}) \mathbf{Z} \\ &=\left(\begin{array}{c}\mu_{X} \\ \mu_{Y}\end{array}\right)+\left(\begin{array}{cc}\sigma_{X} & 0 \\ \rho \sigma_{Y} & \sigma_{Y}\left(1-\rho^{2}\right)^{1 / 2}\end{array}\right)\left(\begin{array}{c}Z_{1} \\ Z_{2}\end{array}\right) \\ &=\left(\begin{array}{c}\mu_{X} \\ \mu_{Y}\end{array}\right)+\left(\begin{array}{c}\sigma_{X} Z_{1} \\ \rho \sigma_{Y} Z_{1}+\sigma_{Y}\left(1-\rho^{2}\right)^{1 / 2} Z_{2}\end{array}\right) \\ X &=\mu_{X}+\sigma_{X} Z_{1} \\ Y &=\mu_{Y}+\sigma_{Y}\left[\rho Z_{1}+\left(1-\rho^{2}\right)^{1 / 2} Z_{2}\right] \end{aligned}
$$
where $\operatorname{Chol}(\mathbf{\mathbf{\sum}})$ is
the Cholesky decomposition.
We define the Cholesky Decomposition  for a symmetric, positive definite matrix $\mathbf{X}$ as $\mathbf{L}=\operatorname{Chol}(\mathbf{X})$
where $L$ is a lower triangular matrix such that $L L^{T}=X$
To find  the lower triangular matrix $L$, we solve for $a,b,c$ in the following system:
$\left(\begin{array}{cc}a & 0 \\ b & c\end{array}\right)\left(\begin{array}{cc}a & b \\ 0 & c\end{array}\right)=\left(\begin{array}{cc}a^{2} & a b \\ a b & b^{2}+c^{2}\end{array}\right)=\left(\begin{array}{cc}\sigma_{X}^{2} & \rho \sigma_{X} \sigma_{Y} \\ \rho \sigma_{X} \sigma_{Y} & \sigma_{Y}^{2}\end{array}\right)$
The right-hand matrix is the variance-covariance matrix.
See these lecture slides:
https://www2.stat.duke.edu/courses/Spring12/sta104.1/Lectures/Lec22.pdf


text:
Q: Create a query to remove rows with a 0 value I'm sure this is probably a simple answer but I can't work out where I'm going wrong.  I have a data table that I've copied to a new tab from (ForMaster!A511:G574).  It brings in 7 columns data, the last 2 columns containing numerical values.
Sample Doc
https://docs.google.com/spreadsheets/d/1zcIHvSM1V_rVH8uiRE1ZhQHkptJLLlw9gnumSurZOps/edit?usp=sharing
I've been trying to set up a query that would look at columns F & G and remove rows where there is a zero in both columns.  Ultimately, I want rows that have a $value in either to remain.  This is a live doc, so if a row initially has a zero, I'd like it to be visible if a value is added at a future date.
I've tried using
=QUERY({ForMaster!A511:G574},"select * where Col6 >=0 or Col7 >=0"), but it doesn't eliminate any rows.
Please help.

A: The comparison should be only greater than 0 to eliminate rows with both zero values.
=QUERY({ForMaster!A511:G574},"select * where  F>0 or G>0")
Sample Data:

A: try:
=QUERY(ForMaster!A511:G574; "where F+G <> 0"; 1)


text:
Q: limit a random number generator to only output 20 of 50 numbers I need some help or advice I am trying to limit the random number to only generate 20 out of the 50 numbers and this activated when a button is pressed/clicked sometimes i get duplicates too which i would to stop happening
function lottoNumbers()
    {
      var lottoNums = [];
      for(var i=0; i <1 ; i++)
      {
        var temp = Math.floor(Math.random() *50);
        if(lottoNums.indexOf(temp) == -1)
        {
          lottoNums.push(temp);
          document.getElementById('circle'+i).innerHTML = lottoNums[i];
        }
        else
        {
          i--;
        }
      }
    }

A: Rather than using a for loop - use a while loop (ie - while length < 20) and as you are doing - only push the numbers into it if they are not already there.
For demo purposes- i am building a list dynamically and then styling the li's to give a rounded shape with border-radius;

lottoNumbers();

function lottoNumbers() {
  var lottoNums = [];
  var lottoNumStr = '';

  while(lottoNums.length <20) {
    var temp = Math.floor(Math.random() *50);
    if(lottoNums.indexOf(temp) == -1) {
      lottoNums.push(temp);
      lottoNumStr += '
' + temp + '
';
    }
  }

  document.getElementById('lottoNumList').innerHTML = lottoNumStr;
}
#lottoNumList {
  list-style: none;
}

#lottoNumList li {
 border: solid 1px #d4d4d4;
 border-radius: 50%;
 display: inline-block;
 margin: 5px;
 padding: 4px;
 width: 30px;
 height: 30px;
 line-height: 30px;
 text-align: center;
}

Lotto Numbers


text:
Q: Create Wrapper class for google analytics in objective c I am using google analytics service in my Application to track the screen view and events like button pressing. But for code reusability i want to create a WRAPPER CLASS for it. Please tell me how to do that !
Code for tracking events like button press :-
-(void)logButtonPress:(UIButton *)button{

    id<GAITracker> tracker = [[GAI sharedInstance] defaultTracker];

    [tracker set:kGAIScreenName value:@"Google Analytics"];
    [tracker send:[[GAIDictionaryBuilder createEventWithCategory:@"UX"
                                                          action:@"touch"
                                                           label:[button.titleLabel text]
                                                           value:nil] build]];
    [tracker set:kGAIScreenName value:nil];
}

Code for page view :-
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    id<GAITracker> tracker = [[GAI sharedInstance] defaultTracker];
    [tracker set:kGAIScreenName value:@"Google Analytics"];
    [tracker send:[[GAIDictionaryBuilder createScreenView] build]];
}

A: You can refer this GTrack
https://github.com/gemr/GTrack
Manual Screen Tracking
- (void)viewDidAppear {
    [super viewDidAppear];

    [[GTTracker sharedInstance] sendScreenEventWithTitle:@"Your Screen Name Here"];
}

Sending Events
[[GTTracker sharedInstance] sendAnalyticsEventWithCategory:@"Your Category" action:@"Your Action" label:@"Your Label" value:@(yourValue)];
[[GTTracker sharedInstance] sendAnalyticsEventWithCategory:@"Your Category" action:@"Your Action" label:@"Your Label"];
[[GTTracker sharedInstance] sendAnalyticsEventWithCategory:@"Your Category" action:@"Your Action"];
[[GTTracker sharedInstance] sendAnalyticsEventWithCategory:@"Your Category"];


text:
Q: Accurately calculate moon phases For a new project I like to calculate the moon phases. So far I haven't seen any code that does that. I don't want to rely on online-services for this.
I have tried some functions, but they are not 100% reliable. Functions I have tried:
NSInteger r = iYear % 100;

    r %= 19;
    if (r>9){ r -= 19;}
    r = ((r * 11) % 30) + iMonth + iDay;
    if (iMonth<3){r += 2;}
    r -= ((iYear<2000) ? 4 : 8.3);
    r = floor(r+0.5);

other one:
float n = floor(12.37 * (iYear -1900 + ((1.0 * iMonth - 0.5)/12.0)));
    float RAD = 3.14159265/180.0;
    float t = n / 1236.85;
    float t2 = t * t;
    float as = 359.2242 + 29.105356 * n;
    float am = 306.0253 + 385.816918 * n + 0.010730 * t2;
    float xtra = 0.75933 + 1.53058868 * n + ((1.178e-4) - (1.55e-7) * t) * t2;
    xtra = xtra + (0.1734 - 3.93e-4 * t) * sin(RAD * as) - 0.4068 * sin(RAD * am);
    float i = (xtra > 0.0 ? floor(xtra) :  ceil(xtra - 1.0));
    float j1 = [self julday:iYear iMonth:iMonth iDay:iDay];
    float jd = (2415020 + 28 * n) + i;
    jd = fmodf((j1-jd + 30), 30);

and last one
        NSInteger thisJD = [self julday:iYear iMonth:iMonth iDay:iDay];
    float degToRad = 3.14159265 / 180;
    float K0, T, T2, T3, J0, F0, M0, M1, B1, oldJ = 0.0;
    K0 = floor((iYear-1900)*12.3685);
    T = (iYear-1899.5) / 100;
    T2 = T*T; T3 = T*T*T;
    J0 = 2415020 + 29*K0;
    F0 = 0.0001178*T2 - 0.000000155*T3 + (0.75933 + 0.53058868*K0) - (0.000837*T + 0.000335*T2);
    M0 = 360*[self getFrac:((K0*0.08084821133)) + 359.2242 - 0.0000333*T2 - 0.00000347*T3];
    M1 = 360*[self getFrac:((K0*0.07171366128)) + 306.0253 + 0.0107306*T2 + 0.00001236*T3];
    B1 = 360*[self getFrac:((K0*0.08519585128)) + 21.2964 - (0.0016528*T2) - (0.00000239*T3)];
    NSInteger phase = 0;
    NSInteger jday = 0;
    while (jday < thisJD) {
        float F = F0 + 1.530588*phase;
        float M5 = (M0 + phase*29.10535608)*degToRad;
        float M6 = (M1 + phase*385.81691806)*degToRad;
        float B6 = (B1 + phase*390.67050646)*degToRad;
        F -= 0.4068*sin(M6) + (0.1734 - 0.000393*T)*sin(M5);
        F += 0.0161*sin(2*M6) + 0.0104*sin(2*B6);
        F -= 0.0074*sin(M5 - M6) - 0.0051*sin(M5 + M6);
        F += 0.0021*sin(2*M5) + 0.0010*sin(2*B6-M6);
        F += 0.5 / 1440;
        oldJ=jday;
        jday = J0 + 28*phase + floor(F);
        phase++;
    }
    float jd = fmodf((thisJD-oldJ), 30);

All are working more and less, but none is really giving the correct dates of full moon for 2017 and 2018.
Does anyone have a function that will calculate the moon phases correctly - also based on time zone?
EDIT:
I only want the function for the Moonphases. SwiftAA offers a lot more and only produces not needed overhead in the app.


text:
Q: Why does this casting from a super to a sub-interface work? I'm looking at this example from a Spring Boot guide:
@Component
public class SimpleCORSFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}

And am confused by this line:
HttpServletResponse response = (HttpServletResponse) res;

I understand the cast from ServletResponse to HttpServletResponse is necessary because the latter interface has #setHeader(). But why does this cast work? Does it work because the underlying object passed to the method is a HttpServletResponse?
But runtime aside, why does the compiler allow this? I'm new to Java and would have expected this cast to fail, since it's from a less to more specific type. For example, using Element and Vertex, I've had this fail:
Vertex v = (Vertex) e; // `e` is an `Element`

A: The JLS pretty much explains it perfectly.

5.1.6 Narrowing Reference Conversion
Such conversions require a test at run time to find out whether the actual reference value is a legitimate value of the new type. If not, then a ClassCastException is thrown.

i.e. When you do such a conversion you explicitly cast the type S to the type T. By doing so you are telling the compiler "I am sure this is ok".
If you think it might fail, then you should try...catch for a ClassCastException and stop your program terminating unexpectedly.


text:
Q: How to get data from database in javascript based on the value passed to the function In my web application, I want to retrieve data from database based on the value that is passed to the function. I wrote the query as follows.

In body tag,

   ---
     getValues

I got the problem while retrieving data from database, i.e., at SELECT query. It doesn't accept the value parseInt(val), if I give the condition as 'name = 1' it simply accepts the condition and give the result, but it doesn't accept 'name = parseInt(val)' and throws error as 'no such column: val code: 1'
Please tell me how to pass value in 'val'..
Thanks in Advance..

A: 'SELECT * FROM Employ where number = ' + parseInt(val, 10) + ';'

For example, if val is "10" then this will end up building the string:
"SELECT * FROM Employ where number = 10;"

A: The error is coming as your query is getting formed as
SELECT * FROM Employ where number = parseInt(val);

I dont know which DB you are using but no DB will understand parseInt.
What you can do is use a variable say temp and store the value of parseInt(val) in temp variable and make the query as
SELECT * FROM Employ where number = temp;

A: Try the following:

You don't have access to javascript variable names in SQL, you must pass the values to the Database.


text:
Q: If I replace files that are in use by a hung process and start a new process, will it use the new files or the old ones? I am on Red hat GNU/linux 2.6.32-431.29.2.el6.x86_64.
Recently - One of my process hung. This process was using few files from a directory - say DIR-1 .
While process was in hung state, I moved ( and not copied )  these files to a backup dir - say DIR-BKP and added newer version of the files to DIR-1 directory. Note these newer version of files have exactly same as the ones from DIR-BKP folder.
Since my process is still in hung state during all this, what will happen if I start a new process, which is going to use files from DIR-1 ? Will the new process use files from DIR-BKP or DIR-1 ? Since old process is still using older version of files ( albeit they are moved to DIR-BKP directory ) , not sure if the new process will use newer version of files or will keep using older version.

A: If you copy files to a new location, then no process is going to be aware of that unless you change something to direct it to the new location (e.g. change a command line option or edit a config file somewhere). A process isn't going to automatically follow the files if you move them. So, the new process should attempt to use the files from DIR-1.
A couple of questions though:

*

*Why don't you just kill the hung process before starting a new one (possibly safer)?

*Why didn't you just copy the files, rather than move, if the new ones are exactly the same?


text:
Q: problem when going back to old version of nodejs I tried to upgrade the node version, rolled back the version to the old one and started getting typescript errors that weren't there before.
I understand that my question will seem stupid to many and even get disadvantages, but I really do not know much about this issue.
But now the project does not run locally with exactly the same version of the wizard (the same package.json) with which everything worked
I need to start, I will raise the typescript version in the future and solve all existing problems, but now I urgently need to solve another, and I cannot even start.
Could this also happen due to the fact that when I updated node I used the following commands, including clearing the cache as I understand it:
npm cache clean -f
sudo npm install -g n

// package.json
{
 "name": "projectname",
 "version": "1.0.0",
 "main": "index.js",
 "description": "project description",
 "private": true,
 "scripts": {
    "dev": "DEBUG=projectname:* DEBUG_DEPTH=5 nodemon server/server.ts",
    "build": "next build && tsc --project tsconfig.server.json",
    "start": "NODE_ENV=production LANG=en node .next/production-server/server/server.js",
    "postbuild": "cp -r static .next/",
    "analyze": "BUNDLE_ANALYZE=both yarn build"
 },
 "dependencies": {
    "@zeit/next-bundle-analyzer": "^0.1.2",
    "@zeit/next-css": "^1.0.1",
    "@zeit/next-sass": "^1.0.1",
    "@zeit/next-typescript": "^1.1.1",
    "app-root-path": "^2.1.0",
    "aws-sdk": "^2.404.0",
    "bbcode-to-react": "^0.2.9",
    "bcrypt": "^3.0.6",
    "body-parser": "^1.18.3",
    "chart.js": "^2.7.3",
    "compression": "^1.7.3",
    "connect-memcached": "^1.0.0",
    "connect-memjs": "^0.2.1",
    "connect-mongo": "^2.0.1",
    "cookie-parser": "^1.4.3",
    "cookie-session": "^1.3.3",
    "cron": "^1.7.0",
    "cross-fetch": "^3.0.1",
    "csv-parse": "^4.4.1",
    "debug": "^4.1.1",
    "diff": "^3.5.0",
    "export-to-csv": "^0.2.1",
    "express": "^4.16.3",
    "express-http-proxy": "^1.5.1",
    "express-session": "^1.15.6",
    "find-remove": "^1.2.2",
    "form-data": "^3.0.0",
    "geoip-lite": "^1.3.8",
    "humps": "^2.0.1",
    "immutable": "^3.8.2",
    "js-base64": "^2.5.2",
    "json-immutable": "^0.4.0",
    "jsonwebtoken": "^8.3.0",
    "locale": "^0.1.0",
    "lodash": "^4.17.10",
    "lru-cache": "^5.1.1",
    "md5": "^2.2.1",
    "mic-recorder-to-mp3": "^2.2.1",
    "moment-timezone": "0.3.0",
    "mongoose": "^5.2.9",
    "multer": "^1.3.1",
    "next": "^8.0.3",
    "next-compose-plugins": "^2.1.1",
    "next-cookies": "^1.1.2",
    "next-redux-wrapper": "^3.0.0-alpha.2",
    "next-routes": "^1.4.2",
    "node-sass": "^4.9.3",
    "nodemailer": "^4.6.8",
    "normalizr": "^3.2.4",
    "passport": "^0.4.0",
    "passport-custom": "^1.1.0",
    "passport-jwt": "^4.0.0",
    "passport-local": "^1.0.0",
    "paypal-rest-sdk": "^1.8.1",
    "pmx": "^1.6.7",
    "query-string": "^6.2.0",
    "rc-slider": "^8.6.3",
    "react": "^16.8.4",
    "react-beautiful-dnd": "^9.0.2",
    "react-chartjs-2": "^2.7.4",
    "react-collapse": "^4.0.3",
    "react-copy-to-clipboard": "^5.0.1",
    "react-cropper": "^1.0.1",
    "react-csv": "^1.0.19",
    "react-datasheet": "^1.3.14",
    "react-day-picker": "^7.3.0",
    "react-dom": "^16.8.4",
    "react-dropzone": "^5.1.0",
    "react-flags": "^0.1.17",
    "react-ga": "^2.6.0",
    "react-google-recaptcha": "^1.0.5",
    "react-infinite-scroller": "^1.2.4",
    "react-joyride": "^2.0.5",
    "react-js-pagination": "^3.0.2",
    "react-lazy-load": "^3.0.13",
    "react-mic-record": "^1.0.6",
    "react-modal": "^3.8.1",
    "react-player": "^1.6.6",
    "react-quill": "^1.3.3",
    "react-redux": "^6.0.1",
    "react-select": "^2.1.0",
    "react-share": "^2.4.0",
    "react-sizeme": "^2.5.2",
    "react-to-print": "^2.4.0",
    "read-excel-file": "^4.0.7",
    "redux": "^4.0.0",
    "redux-form": "^8.1.0",
    "redux-saga": "^0.16.0",
    "set-value": "^3.0.0",
    "shelljs": "^0.8.2",
    "shortid": "^2.2.13",
    "slugify": "^1.3.4",
    "socket.io": "^2.2.0",
    "socket.io-client": "^2.2.0",
    "socket.io-redis": "^5.2.0",
    "twig": "^1.12.0",
    "typegoose": "^5.2.1",
    "uuid": "^3.3.2"
  },
  "devDependencies": {
     "@babel/plugin-proposal-decorators": "^7.1.0",
     "@types/body-parser": "^1.17.0",
     "@types/connect-mongo": "^0.0.38",
     "@types/cookie-parser": "^1.4.1",
     "@types/debug": "^4.1.0",
     "@types/express": "^4.16.0",
     "@types/express-session": "^1.15.10",
     "@types/mongodb": "^3.1.4",
     "@types/mongoose": "^5.2.6",
     "@types/multer": "^1.3.7",
     "@types/node": "^10.7.1",
     "@types/passport": "^0.4.6",
     "@types/passport-local": "^1.0.33",
     "@types/react": "^16.4.11",
     "@types/react-dom": "^16.0.7",
     "@types/redux-form": "^7.4.7",
     "@types/set-value": "^2.0.0",
     "@types/shortid": "^0.0.29",
     "autoprefixer": "^9.4.3",
     "babel-plugin-module-resolver": "^3.1.1",
     "babel-plugin-transform-class-properties": "^6.24.1",
     "babel-plugin-transform-decorators-legacy": "^1.3.5",
     "babel-plugin-wrap-in-js": "^1.1.1",
     "css-purify-webpack-loader": "^1.0.1",
     "eslint": "^5.4.0",
     "eslint-plugin-react": "^7.11.1",
     "faker": "^4.1.0",
     "next-purgecss": "^3.0.1",
     "next-size": "^2.0.2",
     "optimize-css-assets-webpack-plugin": "^5.0.1",
     "purgecss-whitelister": "^2.3.1",
     "stylelint-config-recommended": "^2.1.0",
     "tailwindcss": "^0.7.4",
     "ts-node": "^7.0.1",
     "typescript": "^3.0.1",
     "webpack-pwa-manifest": "^4.0.0"
   }
}

// ts-node -v =>
ts-node v7.0.1
node v10.19.0
typescript v3.0.1
cache "/tmp/ts-node-83......"

[UPDATED] I changed "typescript": "^3.0.1" > "typescript": "3.0.1", and in project v3.0.1 now, global v3.7.5
I switch them to VSCode and it does not underline anything, I also took a commit where I made corrections when I tried to raise versions of all packages, but I used the original package.json, and now it swears at the import format (If I understand correctly, this import format goes in later versions: import moment from 'moment-timezone'):
// utils.ts:
import * as moment from 'moment-timezone';

// traceback error
/home/roma/project/app/utils.ts:379
    value: {startDate: moment().startOf('day').unix() * 1000, endDate: moment().unix() * 1000},

TypeError: moment is not a function
at Object.<anonymous> (/home/roma/project/app/utils.ts:379:29)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Module.m._compile (/home/roma/project/node_modules/ts-node/src/index.ts:439:23)
at Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Object.require.extensions.(anonymous function) [as .ts] (/home/roma/project/node_modules/ts-node/src/index.ts:442:12)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Module.require (internal/modules/cjs/loader.js:692:17)
at require (internal/modules/cjs/helpers.js:25:18)
at Object.<anonymous> (/home/roma/project/server/models/user.ts:10:1)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Module.m._compile (/home/roma/project/node_modules/ts-node/src/index.ts:439:23)
at Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Object.require.extensions.(anonymous function) [as .ts] (/home/roma/project/node_modules/ts-node/src/index.ts:442:12)
at Module.load (internal/modules/cjs/loader.js:653:32)
[nodemon] app crashed - waiting for file changes before starting...

P.S. In the future, I still plan to update all packages to the latest versions including node as required by Next.js v11. What is the best and most correct way to do this so that while work is underway to be able to quickly switch to support the site and resolve urgent problems, without facing such a situation as it is now?


text:
Q: measurement converter for selecting unit I'm seeing quite a few measurement conversion relating gems, but I haven't been able to find one that will select the best/closest unit.
For example
If I give the gem the measurement of

9 inches + 6 inches

I'm trying to get the result

1 foot, 3 inches

The conversion tools I've seen, I'd have to tell the convertor to try to convert to feet, and then decide which is the most appropriate measurement.

A: Not sure how complicated you wanted to get but for your example I did this:
def plain_english_conversion(inches)
    divmod_output = inches.divmod(12)
    puts "#{divmod_output[0]} ft, #{divmod_output[1]} in"
end

puts "15 "
plain_english_conversion(15)

puts "37 "
plain_english_conversion(37)

With the output of:

15
1 ft, 3 in
37
3 ft, 1 in

Certainly I restricted it to feet/inches but you can abstract it out if necessary (inches & yards, feet & yards, etc.)


text:
Q: Is there a standard terse name for "number of"? I've found that in programs, I inevitably have a couple of variables that are named along the lines of numberOfBooks, or numberOfPeople. Is there a commonly used word that makes sense that's a bit shorter than numberOf?

A: Count or quantity are the usual suspects so you could get away with things like:
bookCount
bookQty
bookQuant

and so forth. But you don't have to use full words, as shown in the Qty abbreviation above.
If you wanted to stay close to what the other programs are using, just use something like:
numBooks
numPeople

A: How about bookCount and peopleCount?

A: I usually use "qty", short for "quantity".


text:
Q: How to solve the error target script cannot be loaded as python module when django app deploy without port number When i deploy django app on aws ec2 instance using ubuntu 16.04 server then it gives an error:
[Sun May 05 16:13:25.466264 2019] [wsgi:error] [pid 5649:tid 140262036731648] [remote 157.50.50.61:56646] mod_wsgi (pid=5649): Target WSGI script '/var/www/html/simple_django_project/django_project/django_project/wsgi.py' cannot be loaded as Python module.
[Sun May 05 16:13:25.466312 2019] [wsgi:error] [pid 5649:tid 140262036731648] [remote 157.50.50.61:56646] mod_wsgi (pid=5649): Exception occurred processing WSGI script '/var/www/html/simple_django_project/django_project/django_project/wsgi.py'.
[Sun May 05 16:13:25.466388 2019] [wsgi:error] [pid 5649:tid 140262036731648] [remote 157.50.50.61:56646] Traceback (most recent call last):
[Sun May 05 16:13:25.466409 2019] [wsgi:error] [pid 5649:tid 140262036731648] [remote 157.50.50.61:56646]   File "/var/www/html/simple_django_project/django_project/django_project/wsgi.py", line 12, in <module>
[Sun May 05 16:13:25.466413 2019] [wsgi:error] [pid 5649:tid 140262036731648] [remote 157.50.50.61:56646]     from django.core.wsgi import get_wsgi_application
[Sun May 05 16:13:25.466429 2019] [wsgi:error] [pid 5649:tid 140262036731648] [remote 157.50.50.61:56646] ImportError: No module named 'django'

000-default.conf
<VirtualHost *:80>
   ServerName pythontestdjangoapp.tk
   ServerAlias www.pythontestdjangoapp.tk

    DocumentRoot /var/www/html/simple_django_project

    ErrorLog/var/www/html/simple_django_project/django_project/logs/error.log
    CustomLog
     /var/www/html/simple_django_project/django_project/logs/debug.log
    combined

   <Directory />
     #Options FollowSymLinks
     Options Indexes FollowSymLinks Includes ExecCGI
     AllowOverride All
     Require all granted
   </Directory>

   <Directory
     /var/www/html/simple_django_project/django_project/django_project/>
        <Files wsgi.py>
            AllowOverride All
            Require all granted
        </Files>
   </Directory>
   WSGIDaemonProcess django_project python-
   path=/var/www/html/simple_djnago_project/django_project python-
   home=/var/www/html/simple_django_project/myvenv
   WSGIProcessGroup django_project

   WSGIScriptAlias /
   /var/www/html/simple_django_project/django_project/django_project/wsgi.py
</VirtualHost>

When i start apache server then it gives me an internal server error


text:
Q: Unauthorized 401 error even without using middleware Struggling with a newbee issue. I created a laravel app, registered an endpoint under the JSON:API facade. When I try to hit this endpoint with a GET request, I get the error:
Status:401 Unauthorized
This is what I have in api.php:
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

JsonApiRoute::server('v1')
    ->prefix('v1')
    ->namespace('App\Http\Controllers\Api\V1')
    ->resources(function ($server) {
        $server->resource('posts');
    });

and in config-> sanctum:
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
    '%s%s',
    'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
    Sanctum::currentApplicationUrlWithPort()
))),

and in PostsController:
class PostController extends Controller
{

    use Actions\FetchMany;
    use Actions\FetchOne;
    use Actions\Store;
    use Actions\Update;
    use Actions\Destroy;
    use Actions\FetchRelated;
    use Actions\FetchRelationship;
    use Actions\UpdateRelationship;
    use Actions\AttachRelationship;
    use Actions\DetachRelationship;

}

Any pointers on what I'm missing?


text:
Q: Bing webmaster API GetKeywordStats UnknownError and empty response I'm trying to get keyword statistics using the bing webmaster API by sending JSON GET requests. The parameters are as following:
List<KeywordStats> GetKeywordStats(
    string q,
    string country, //optional
    string language //optional
)

So at first I generated my uri this way:

https://ssl.bing.com/webmaster/api.svc/json/GetKeywordStats?apikey=myAPIKey&q=kreeft&country=BE&language=nl

This returned the following response:

status: 400
  {
      "ErrorCode": 2,
      "Message": "UnknownError"
  }

Trying to solve the problem I simplified my url by not setting the optional parameters resulting in the following query:

https://ssl.bing.com/webmaster/api.svc/json/GetKeywordStats?apikey=myApiKey&q=kreeft

The response on this query was even more puzzling:

status: 200
  {"d":[]}

Which just looks like an empty response to me.
I queried those links both from localhost (using postman) and from my webserver at one.com, both giving the same results.
So I have 2 questions actually:
- Why do I have empty responses
- Why are my parameters not accepted
Thanks in advance

A: The country code must be lowercase, and the language code must include the country component (in uppercase). yes, it is inconsistent and not specified anywhere.
https://ssl.bing.com/webmaster/api.svc/json/GetKeywordStats?apikey=myAPIKey&q=kreeft&country=be&language=nl-BE

For more, see the blog article: http://bing-webmaster-api.analyticsedge.com/2014/05/getkeywordstats/