text:
Q: Set a upper bandwidth limit for Infiniband HCAs I have to deal with PCIe congestion and I need to find a way to reduce PCIe traffic. I get several IB cards in one node (among other PCIe devices). HCAs are FDR Infiniband.
Putting those HCAs in FDR-10 or QDR reduces too much the total bandwidth. Ideally I would like to limit each HCA to run between 5 and 5.5 GB/s. I'm not sure if a QoS managed by the IB switch could effectively set a upper limit per HCA (I think it rather uses weights for setting priorities).
Is there other ways to set a upper bandwidth limit for Infiniband HCAs?

A: AFIK, there is no way to set a real limit to IB traffic other than changing link speed to a lower one.
IB QoS is about arbitration between different traffic streams, not about limiting a traffic BW.
You can, however, enable Congestion Control (if your SW/HW supports it).
It's not really what it is meant for - it's more for solving congestion on switches - but it might solve your issue as well.


text:
Q: Macro to define javascript constructor keyword I have many classes which are like this:
struct A_Insert
{
    Data &d;
    A_Insert(d) : d(d){}

    // ...
}

struct A_Query
{
    Data &d;
    A_Query(d) : d(d){}

    // ...
}

struct B_Insert
{
    Data &d;
    B_Insert(d) : d(d){}

    // ...
}

struct B_Query
{
    Data &d;
    B_Query(d) : d(d){}

    // ...
}

The best thing I can think to do is define a macro like this:
#define Data_Query(name, body) struct name{Data &d; name(Data &d) : d(d) {} body}

but this leads to somewhat ugly code as I have to use parentheses to define my structs and my IDE doesn't handle it very well.
Data_Query(A_Insert,
    int bind_params(stmt &stmt){}
    ...
)

I would like a macro which could allow me to get the name of the containing type for the constructor so I could write code like:
#define constructor CONTAINING_TYPE
#define Data_Construct Data &d; constructor (Data &d) : d(d) {}

struct A_Insert
{
Data_Construct
// ...
}
and this way my IDE could treat it like a normal struct declaration. Any suggestions would be appreciated.

A: Inheritance:
struct DataReference
{
    Data &d;

    DataReference(Data& d) : d(d) {}
};

struct A_Insert : DataReference
{
    using DataReference::DataReference;

    ...
};

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cannot get some friend-tag-me photos by v2.0, but fine with v1.0 One of my friend's photo, can be searched by the following GRAPH API with v1.0 friends_photos & friends_status permissions.

v1.0/me/photos?type=tagged&since=1403366399&until=1404014399

To check this in v2.0, I did told my friend to become a user of our Facebook application.  However, no matter which V2.0 permission is granted, the similar query cannot get that photo.

v2.0/me/photos?type=tagged&since=1403366399&until=1404014399

I did some pre-condition checks for this problem, and the results are

*

*v2.0/me/photos?type=tagged works fine and can get some friends photos which tagged me.

*v2.0/me/friends work fine, and that friend is in the friend list.

Any suggestion for this problem?
p.s. Forget to mention, that photo is posted at 2014/6/23, so, should not be legacy-related.

A: *

*https://developers.facebook.com/docs/apps/changelog

*https://developers.facebook.com/docs/apps/review
Check out the changelog, in v2.0 you have to go through a review process with most permissions including user_photos. Else, the permissions will only work for users with a role in your App (Developer, Admin, Tester). I assume your friend does not have a role in your App, so user_photos will not work before getting it approved by Facebook.

A: Our application just got the approve of user_photos, however, what my friend grant to our application is user_friends.  And used test page to let her grant user_photos to our application, that photo still cannot be searched by V2.0/V2.1 API.
And after invited her to be developer, and grant our application user_status permission, that photo can get searched by v2.0/v2.1.
After some tests, user should grant user_photos, and user's friend should grant user_photos ,user_status.  Then, the user can get all privacy-allowed photos fro that friend.


text:
Q: Using gluUnProject() to draw a quad at the cursor position I am using SDL with OpenGL and up until now I have done everything in 2d (Using glOrtho())
Now I want to try drawing things in 3D but of course since I have now thrown a 3rd dimension into the mixture, things are getting more complicated.
What I want to do is, take the screen co-ordinates of the cursor, translate them to (?)world co-ordinates (Co-ordinates I can use in OpenGL since I now have perspective etc.), and draw a quad at that position (The mouse cursor being at the center of the quad)
I have read a few tutorials on gluUnProject() and I sort of understand what I am supposed to do, but since I am learning by myself it is very easy to get confused and not properly understand what I am doing.
As such, I have mainly copied from examples I have found.
Below is my code (I took out error checking etc in an attempt to cut it down a bit)
As you can see, I have mouseX, mouseY and mouseZ variables, of which mouseX and mouseY get their values from SDL.
I tried to use glReadPixel() to get mouseZ but I am not sure if I am doing it right.
The problem is that when I click, the quad is not drawn in the correct position (I guess partly due to the fact that I don't know how to get mouseZ properly, so I just replaced it in gluUnProject() with 1.0?)
I am using the new co-ordinates (wx, wy, wz) in the glTranslatef() function but once again because I don't know how to get mouseZ properly I am guessing this is the reason it doesn't work properly.
If I replace wz with -499 it seems to work ok, but I need to know how to get accurate results without manually finding the correct (Or almost correct) numbers
If anybody can tell me what I am doing wrong, or give me any advice it would be greatly appreciated.
#include <SDL/SDL.h>
#include <SDL/SDL_opengl.h>

SDL_Surface* screen = 0;
SDL_Event event;
bool isRunning = true;

int mouseX, mouseY, mouseZ = 0;

GLint viewport[4];
GLdouble mvmatrix[16], projmatrix[16];
GLint realY; /* OpenGL y coordinate position */
GLdouble wx, wy, wz; /* returned world x, y, z coords */

int main(int argc, char **argv) {
    SDL_Init(SDL_INIT_EVERYTHING);

    screen = SDL_SetVideoMode(800, 600, 32, SDL_OPENGL);

    glEnable(GL_DEPTH_TEST);
    glDepthMask(GL_TRUE);

    glViewport(0, 0, 800, 600);

    glClearDepth(1.f);
    glClearColor(0, 0, 0, 0);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    gluPerspective(90.f, 1.f, 1.f, 500.f);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    while(isRunning) {
        while(SDL_PollEvent(&event)) {
            if(event.type == SDL_QUIT) {
                isRunning = false;
            }

            if(event.type == SDL_MOUSEBUTTONDOWN) {
                if(event.button.button == SDL_BUTTON_LEFT) {
                    SDL_GetMouseState(&mouseX, &mouseY);

                    glGetIntegerv(GL_VIEWPORT, viewport);
                    glGetDoublev(GL_MODELVIEW_MATRIX, mvmatrix);
                    glGetDoublev(GL_PROJECTION_MATRIX, projmatrix);
                    realY = viewport[3] - (GLint) mouseY - 1;
                    glReadPixels(mouseX, realY, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &mouseZ);

                    gluUnProject((GLdouble)mouseX, (GLdouble)realY, 1.0, mvmatrix, projmatrix, viewport, &wx, &wy, &wz);
                }
            }
        }

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        glPushMatrix();

        glTranslatef(wx, wy, wz);

        glBegin(GL_QUADS);
            glColor4f(1.f, 0.f, 0.f, 1.f);
            glVertex3f(-20.f, -20.f, 0.f);

            glColor4f(0.f, 1.f, 0.f, 1.f);
            glVertex3f(-20.f, 20.f, 0.f);

            glColor4f(0.f, 0.f, 1.f, 1.f);
            glVertex3f(20.f, 20.f, 0.f);

            glColor4f(1.f, 0.f, 1.f, 1.f);
            glVertex3f(20.f, -20.f, 0.f);
        glEnd();

        glPopMatrix();

        SDL_GL_SwapBuffers();
    }

    SDL_FreeSurface(screen);

    return 0;
}

A: I found that if I added the following:
GLfloat depth[2];

then changed the glReadPixels() from:
glReadPixels(mouseX, realY, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &mouseZ);

to:
glReadPixels(mouseX, realY, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, depth);

then I just changed gluUnProject() from:
gluUnProject((GLdouble)mouseX, (GLdouble)realY, mouseZ, mvmatrix, projmatrix, viewport, &wx, &wy, &wz);

to:
gluUnProject((GLdouble) mouseX, (GLdouble) realY, depth[0], mvmatrix, projmatrix, viewport, &wx, &wy, &wz);

then I could get the Z value I wanted.
Then I just added a small value to wz, for example: wz += 1; to make sure the quad appeared above the place I clicked and it seems to work as I intended now.

A: To guess a Z you need to have a meaning for this z :
Usually the meaning is that you want to intersect the line corresponding to (camera origin,pixel) with a 3d object with is displayed. You can use the Z buffer for this.
If not ( you want to stick a polygon to the cursor with no 3D relation ), just use the 2D functions, you can just alternate between 3D and 2D projections while drawing in the same frame (with either the projection matrix or with 2D specific functions), thus you don't need a z.
Setting a default value for Z is a bad idea if it has no rationale in your design.
There is only one value of Z which will give you correct pixel coordinates.
The link between 2D and 3D coordinates in openGL is that OpenGl uses a projection plane at Z = 1.
And then scales the pixel coordinates from [-1,1] to pixels coordinates.


text:
Q: How to auto refresh a computed property at axios in vuejs I'm calling restapi data with axios in vuejs , i want this data to be auto refreshed everysecond to see any change in numbers. I can see data, its working but refresh is not working
I've put setinterval function in methods area but it doesnt refresh any data.
import axios from 'axios';
export default {
  data () {
    return {
      btctrk: null,
      bnnc: null,
    }
  },
  computed: {
          result1: function(){
              return  this.btctrk[0].ask / this.btctrk[4].bid;
          },
          result2: function(){
              return  this.btctrk[0].bid / this.btctrk[4].ask;
          },
          result3: function(){
              return  (1-(this.bnnc[11].bidPrice / this.result1))*100;
          },
          result4: function(){
              return (1-(this.result2 / this.bnnc[11].askPrice))*100;
          },
      },
  mounted () {
    axios
      .get('https://www.api1.com/api/ticker')
      .then(response => (this.btctrk = response.data))
      .catch(error => console.log(error))
    axios
      .get('https://api.api2.com/api/v3/ticker/bookTicker')
      .then(response => (this.bnnc = response.data))
      .catch(error => console.log(error))
  },
  methods: {
              startInterval: function () {
                   setInterval(() => {
                      this.result1;
                      this.result2;
                      this.result3;
                      this.result4;
                   }, 1000);
          }
  }
}

A: Computed properties are only re-evaluated if some of its dependencies have changed, meaning that they have some sort of "cache" if we can put it like that. See: Computed caching vs Methods
Another thing is that you are running your Axios get call when mounted(), meaning that your call is only running once the component is mounted and not refreshing at all. See: Lifecycle Diagram
My solution to your problem will be something like this:
  export default {
    data () {
        return {
        btctrk: null,
        bnnc: null,
        }
    },
    computed: {
        result1: function(){
            return  this.btctrk[0].ask / this.btctrk[4].bid;
        },
        result2: function(){
            return  this.btctrk[0].bid / this.btctrk[4].ask;
        },
        result3: function(){
            return  (1-(this.bnnc[11].bidPrice / this.result1))*100;
        },
        result4: function(){
            return (1-(this.result2 / this.bnnc[11].askPrice))*100;
        },
    },
    methods: {
        btcTrkAPICall: function () {
            axios
                .get('https://www.api1.com/api/ticker')
                .then(response => (this.btctrk = response.data))
                .catch(error => console.log(error))
        },
        bnncAPICall: function () {
            axios
                .get('https://api.api2.com/api/v3/ticker/bookTicker')
                .then(response => (this.bnnc = response.data))
                .catch(error => console.log(error))
        },
        intervalFetchData: function () {
            setInterval(() => {
                this.btcTrkAPICall();
                this.bnncAPICall();
                }, 1000);
        }
    },
    mounted () {
        // Run the functions once when mounted
        this.btcTrkAPICall();
        this.bnncAPICall();
        // Run the intervalFetchData function once to set the interval time for later refresh
        this.intervalFetchData();
    }
}

I think this is a plausible solution, feel free to test it out.


text:
Q: cannot pass function to `map` I am seeing the following behavior in the Chrome dev tools:
var $el = $("<div>", { "data-row-idx": 1, "data-col-idx": 2 })
// n.fn.init [div]

$el.data("row-idx")
// 1

$el.data("col-idx")
// 2

["row-idx", "col-idx"].map(function(x) { return $el.data(x) })
// (2) [1, 2]

["row-idx", "col-idx"].map($el.data)
// jquery.min.js:3 Uncaught TypeError: this.each is not a function
//     at data (jquery.min.js:3)
//     at Array.map (<anonymous>)
//     at <anonymous>:1:24
// data @ jquery.min.js:3

[1,2,3].map(function(x) { return x})
// (3) [1, 2, 3]

(codepen link)
I thought that:
["row-idx", "col-idx"].map(function(x) { return $el.data(x) })

and
["row-idx", "col-idx"].map($el.data)

were equivalent. Is this not so?


text:
Q: Can't call default constructor explicitly
Possible Duplicate:
Error on calling default constructor with empty set of brackets

Why does the following code compile without problems but when I switch the line
MCl<char, a> tryout;

to
MCl<char, a> tryout();

I receive "error C2228: left of '.ea' must have class/struct/union" ? Isn't tryout() a call to the default constructor?
Here's the full code
template <class T, T myval> class MCl
{
public:
    T ea;
    MCl() : ea(myval)
    {
    }
};

int main()
{

    const char a = 'e';
    MCl<char, a> tryout;
    // MCl<char, a> tryout();

    cout << tryout.ea;

    return 0;
}

A: MCl<char, a> tryout();

declares function tryout, that receives nothing and returns MCl<char, a>.
n3337 8.2/1

the choice is between a function declaration
with a redundant set of parentheses around a parameter name and an object declaration with a function-style
cast as the initializer. Just as for the ambiguities mentioned in 6.8, the resolution is to consider any construct
that could possibly be a declaration a declaration. [ Note: A declaration can be explicitly disambiguated by
a nonfunction-style cast, by an = to indicate initialization or by removing the redundant parentheses around
the parameter name. —end note ]

A: MCl<char, a> tryout();

This is ambiguous as either a function prototype or instantiation through a void constructor. This ambiguity has been covered to death as 'the most vexing parse' - it is even discussed in the C++03 standard itself!
However, people tend not to mention that C++11 introduces a new syntax to disambiguate this through uniform initialization. Under this new syntax, your instantiation of MCl would be expressed as so:
MCl<char, a> tryout{};

A: Declares a variables;
MCl<char, a> tryout;    // uses default constructor if user defined one.
                        // If compiler generated constructor uses value-initialized
                        // of members which for POD types means uninitialized.

Is a forward declaration to a function (called tryout):
MCl<char, a> tryout();

What you wanted was probably: (for C++03 for C++11 see Mike Kwan).
MCl<char, a> tryout  = MCl<char, a>(); // uses default constructor if user defined one.
                        // If compiler generated constructor uses zero-initialized
                        // of members which for POD types means 0 is placed in them.


text:
Q: Why does bulk load causes indexing on Couchbase Server? I am reading bulk data from a Couchbase bucket and inserting this bulk data to another bucket. I am using couchbase java sdk 1.4.4 version.Using views for reading the whole data.
I am using the set api to insert the data. After inserting the whole data into Couchbase, I am closing the Couchbase client.
Data gets inserted into Couchbase but as soon as it gets inserted, it starts indexing the data which I can see from couch base web console. As per couch base documentation, it should start indexing when we are reading the data , based on STALE parameter.
The other issue which I am facing is, at my java application console, it shows lots of warnings until indexing is not done.
jvm 1    | WARN  [OperationFuture] Exception thrown wile executing com.couchbase.client.CouchbaseClient$15.operationComplete()
jvm 1    | java.lang.IllegalStateException: Shutting down
jvm 1    |      at net.spy.memcached.MemcachedClient.broadcastOp(MemcachedClient.java:298) ~[spymemcached-2.11.4.jar:2.11.4]
jvm 1    |      at net.spy.memcached.MemcachedClient.broadcastOp(MemcachedClient.java:292) ~[spymemcached-2.11.4.jar:2.11.4]
jvm 1    |      at com.couchbase.client.CouchbaseClient.observe(CouchbaseClient.java:1670) ~[couchbase-client-1.4.4.jar:1.4.4]
jvm 1    |      at com.couchbase.client.CouchbaseClient.observePoll(CouchbaseClient.java:1803) ~[couchbase-client-1.4.4.jar:1.4.4]
jvm 1    |      at com.couchbase.client.CouchbaseClient$15.onComplete(CouchbaseClient.java:1443) ~[couchbase-client-1.4.4.jar:1.4.4]
jvm 1    |      at com.couchbase.client.CouchbaseClient$15.onComplete(CouchbaseClient.java:1412) ~[couchbase-client-1.4.4.jar:1.4.4]
jvm 1    |      at net.spy.memcached.internal.AbstractListenableFuture$1.run(AbstractListenableFuture.java:117) ~[spymemcached-2.11.4.
jvm 1    |      at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) [na:1.7.0_21]
jvm 1    |      at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334) [na:1.7.0_21]
jvm 1    |      at java.util.concurrent.FutureTask.run(FutureTask.java:166) [na:1.7.0_21]
jvm 1    |      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [na:1.7.0_21]
jvm 1    |      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [na:1.7.0_21]
jvm 1    |      at java.lang.Thread.run(Thread.java:722) [na:1.7.0_21]

Questions:
Why is index creation starting before reading the views?
Why are there warning messages coming on console?.
Please let me know if you need more information.

A: As documented in the Couchbase server manual index are run automatically. Here are the default parameters for the automated index updates.
{
     "updateInterval":5000,
     "updateMinChanges":5000,
     "replicaUpdateMinChanges":5000
}

With these setting the system will check every 5 seconds to see if there has been 5000 mutations made to the bucket. If that is true it will start indexing. Once the bulk load code does 5000 sets the indexing will began.
You can read more about automated index updates in the manual.


text:
Q: Copy Text button function in React JS I am working on project create-react-app create a some function in this project but copytext function not working issues mention in the below line of code. please check the issue...
import React, {useState} from 'react'

export default function TextForm(props) {

    const handleCopy = () => {
        console.log("I am copy");
        let text = document.getElementById("mybox");
        text.Select();
        navigator.clipborad.writetext(text.value);
    }

    const handleOnChange = (event) =>{
        // console.log("on change");
        setText(event.target.value);
    }
    const [text, setText] = useState('');
  return (
    <>

{props.heading}

            <textarea className="form-control"
            value={text} id="myBox" rows="8" onChange={handleOnChange}></textarea>

            <button className="btn btn-primary mx-2 my-2" onClick={handleCopy}>Copy Text</button>

Your text summary

{text.split(" ").length} Word and {text.length} Characters

{0.008 * text.split(" ").length} Minute Read

Preview

{text}

    </>
  )
}

TextForm.js:16
   Uncaught TypeError: Cannot read properties of null (reading 'Select')

A: There are some problems in your code:

*

*You have created a state for text and you don't need to get it by getElementById and Select.

*writetext doesn't exist in navigator.clipborad. It should be writeText (it's case sensitive).

*For using a state in whole component, it needs to define state in top of the component. So, move const [text, setText] = useState(''); to top of your component.

*text state doesn't have value property. You can access its value just by text.

Here's the edited code:
function TextForm(props) {

  const [text, setText] = useState('');

  const handleCopy = () => {
      navigator.clipboard.writeText(text);
  }
  const handleOnChange = (event) =>{
      setText(event.target.value);
  }
  return (
    <>

{props.heading}

            <textarea className="form-control"
            value={text} id="myBox" rows="8" onChange={handleOnChange}></textarea>

            <button className="btn btn-primary mx-2 my-2" onClick={handleCopy}>Copy Text</button>

Your text summary

{text.split(" ").length} Word and {text.length} Characters

{0.008 * text.split(" ").length} Minute Read

Preview

{text}

    </>
  )
}

A: You have text value so You dont need to this
let text = document.getElementById("mybox");
text.Select();

So maybe just do like this
navigator.clipborad.writetext(text);


text:
Q: SQL testing a user defined function I have the following code. I am trying to test the function by passing in a @Hire_Date Datetime and seeing what value would be returned However I am new to SQL server 2012 and have no idea how I would go about doing this.
Thanks.
CREATE FUNCTION dbo.getYearsOfService (@Hire_Date Datetime)
RETURNS int
AS BEGIN

    DECLARE @thisYear int
    DECLARE @thisMonth int
    DECLARE @hireYear int
    DECLARE @hireMonth int
    DECLARE @yearlengthOfService int
    DECLARE @monthlengthOfService int

    SET @thisYear = YEAR(getdate())
    SET @thisMonth = MONTH(getdate())
    SET @hireYear = YEAR('@Hire_Date')
    SET @hireMonth = MONTH('@Hire_Date')

    SET @yearlengthOfService = (@thisYear - @hireYear);
    SET @monthlengthOfService = (@thisMonth - @hireMonth);

    IF (@monthlengthOfService < 0)
        SET @yearlengthOfService = (@yearlengthOfService - 1);

    RETURN @yearlengthOfService
END;

A: You can just use SELECT:
SELECT dbo.getYearsOfService(GETDATE())

or
SELECT dbo.getYearsOfService(CAST('2021-01-20' as DATETIME))

(Perhaps the hire date of the next president of the U.S.)
If you have a table of dates, you can use the value in the table as well:
SELECT dbo.getYearsOfService(datecol)
FROM t;

A: You would just query the function like this:
SELECT dbo.getYearsOfService ('02/25/2017')
;

Or if you want to use the function against a record in a table, you would query it against a value from that row, like this:
SELECT dbo.getYearsOfService(<ColumnName>)
FROM <TableName>
WHERE <SomeColumn> = <SomeValue>
;

Or if you wanted to return values together with it, you could run it against the whole table (or part of it), like this:
SELECT <Column1>, <Column2>, <Column3>, dbo.getYearsOfService(<ColumnName>) AS <WhateverNameYouWant>
FROM <TableName>
WHERE <SomeColumn> = <SomeValue> -- Optional WHERE Clause
;

NOTE:
Please notice that in the body of your function, you have an error:
SET @hireYear = YEAR('@Hire_Date')
SET @hireMonth = MONTH('@Hire_Date')

You don't want to pass strings here, but the parameter value.  Do away with the apostrophes and you should get a clean run with no errors.
SET @hireYear = YEAR(@Hire_Date)
SET @hireMonth = MONTH(@Hire_Date)


text:
Q: How to do a case-insensitive string where in NHibernate Linq query? How to do a case-insensitive where in NHibernate  Linq query?
e.g.
//note this one doesn't work if the entry in database has lowercase
q => q.Where(entity =>
    entity.CaseInsensitiveField == DesiredField.Trim().ToUpper())

A: Use this:
q => q.Where(entity =>
    String.Equals(entity.CaseInsensitiveField , CaseInsensitiveField ,
                  StringComparison.OrdinalIgnoreCase));

UPDATE
It appears (at least via LinqPad) that the above will not translate into SQL, so I would suggest, as ivowiblo has already suggested:
var comparisonValue = CaseInsensitiveField.ToUpper();
q => q.Where(entity =>
    entity.CaseInsensitiveField.ToUpper() == comparisonValue);

The reason to set the ToUpper beforehand is that procedural functions are generally worse in SQL, and since this is not a database field, we can send it in already capitalized.

A: Try this:
q => q.Where(entity => entity.CaseInsensitiveField.ToUpper() == DesiredField.Trim().ToUpper())

Also, I would suggest to set the parameter outside the query:
var value = DesiredField.Trim().ToUpper();

...

q => q.Where(entity => entity.CaseInsensitiveField.ToUpper() == value)


text:
Q: Unity says "error CS1022: Type or namespace definition, or end-of-file expected" I am making a cross board game using Unity based on a tutorial. This problem occurs when I add a jump animation.
All my code is from that tutorial and no changes have been made except for one value.
I know which line of code is wrong but I don't know why and I don't know how to fix it.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Playermovement : MonoBehaviour
{
  private Rigidbody2D rb;
    public float jumpAmount = 1;

    bool isGrounded;
    public Transform groundCheck;
    public LayerMask groundlayer;
    public Animator anim;
    public float overlap = 0.5f;

    void Start()
    {

        rb = gameObject.GetComponent<Rigidbody2D>();
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            if (isGrounded)
            {
                Jump();
            }
        }
    }

    private void FixedUpdate()
    {
        isGrounded = Physics2D.OverlapCircle(groundCheck.position, overlap, groundlayer);
    }

    void Jump()
    {
        rb.AddForce(Vector2.up *5* jumpAmount, ForceMode2D.Impulse);
    }

    if(isGrounded)
        {
            anim.SetBool("Jump",false);
        }
        else
        {
            anim.SetBool("Jump", true);
        }
}

Does anyone know what's wrong with this, please?
Thank you in advance to those who answered!

Assets\Script\Playermovement.cs(52,1): error CS1022: Type or namespace definition, or end-of-file expected

This is the error message I received. I know it tells me the error occurred on the first character of line 52 (which is the last line), but other than that I don't know anything because there is only one curly bracket on that line.

A: The problem is with if (isGrounded) statement. The if/else statement needs to be in a method/function, and can't work without being in one.


text:
Q: being redirected to wrong loginUrl -> account/login instead of account/LOGON I have a strange error I have never run into before.
I secured a controller with:
[Authorize(Roles = "admin")]
public class LoggingController : Controller

When a non-admin user tries to access any protected content, they are redirected to:
http://localhost:50501/Account/Login?ReturnUrl=%2flogging
note: account/login and NOT account/logon
The AccountController.Login action does not exist.
web.config has:
<authentication mode="Forms">
    <forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>

I can of course implement the Login action and redirect to Logon.
I am just puzzled and would like to know why this happens.

A: This worked for me and I'm using MVC 3
<appSettings>
    <add key="loginUrl" value="~/Account/LogOn" />
</appSettings>
<system.web>
    <authentication mode="Forms">
        <forms loginUrl="~/Account/LogOn" name=".ASPXFORMSAUTH" />
    </authentication>
</system.web>

Also I found that adding the followinf part to the web config (only during debugging the config) helped speed up my debugging as had to authenticate for ANY page.
<authorization>
    <deny users="?" /> <!-- remove after debugging -->
</authorization>

A: Search your project for login - it has to be specified somewhere. Is there any other web.config value overriding this (maybe looking at a child root and the parent value is being used)
Also is there any redirect that is happening? Are there any defaults set in your machine's web.config?
Is your default url on the project set to be a /login?
Install glimpse route debugger to see which route is being used for this page as well.
EDIT:
A little more research yields a known issue.
Check out this link:
ASP.NET MVC issue with configuration of forms authentication section
Theres a bug in mvc 3 beta - are you running the beta bits?
Also notice the mentioned item in the above url for RTM bits:
<add key="loginUrl" value="~/LogOn" />

Also check out
http://forums.asp.net/p/1616153/4138366.aspx
EDIT 2
Below is a solid comment about a potential source of this from @santiagoIT (upvote his comment please if the specifics help you)
Today I discovered the root of this problem: I had added 'deployable dependency' on 'ASP.NET Web Pages with Razor Syntax'. This adds a reference to: WebMatrix.Data.dll This assembly has a class with a static constructor that does the following: static FormsAuthenticationSettings(){ FormsAuthenticationSettings.LoginUrlKey = "loginUrl"; FormsAuthenticationSettings.DefaultLoginUrl = "~/Account/Login";} That explains!

A: Just simply remove the WebMatrix dll if they are present in your deployed bin folder.

A: I fixed it this way
1) Go ot IIS
2) Select your Project
3) Click on "Authentication"
4) Click on "Anonymous Authentication" > Edit > select "Application pool identity" instead of "Specific User".
5) Done.


text:
Q: React Formik Default value I am using React formik. I have a dropdown select option. Option is working fine but i want to have default value as Free from the dropdown. If i submit the form without click, it is giving me the option value as blank.
Below is my code:
const defautValue="Free";
const options=["Premium","Gold","Free"]

<Field>
  {(props: any)=>{
    const {field}=props;
    const defaultOption=<option key='default' value={defaultValue}>{defaultValue}</option>
    const option=options.map((i:string)=>{return (<option key={i} value={i}>{i}</option>)})
    const selectOptions=[defaultOption,...option]
    return (

       <select value={field.value}{...field}>{selectOptions}</select>

         )
  }}
</Field>

A: try removing the manual setting of the defaultOption, selectOptions, and use either the formik.values, or form.value, and set the defaultValue of a component using the initialValues of the Formik component:

<Formik
  initialValues={{selectedOption: "Free"}: YourFormData}
  onSubmit={(values, actions) => {console.log(values, actions)}}
>
  {formik => (
    <Form translate="yes">
      <Field name="selectedOption">
          {({ form, field }: FieldProps<YourFormData>) => {
          const options=["Premium","Gold","Free"].map((i:string)=>{return (<option key={i} value={i}>{i}</option>)})
          return (

                 <select {...field}>{options}</select>

               )
        }}
      </Field>
    </Form>
    )}
</Formik>

the {...field} spread operator of field already has the "value" added
<Field name="selectedOption"> automagically connects the selectedOption formik field up to the <select> element, including onChange, onBlur, touched, etc.
Or you can also use as for example:
<Formik
    initialValues={{selectedOption: 'Free'}}
    onSubmit={(values, actions) => {
        setTimeout(() => {
            alert(JSON.stringify(values, null, 2));
            actions.setSubmitting(false);
        }, 1000);
    }}>{(props: FormikProps<any>) => (
    <Form>
        <Field as="select" name="selectedOption">
           {["Premium","Gold","Free"].map((i:string)=>(<option key={i} value={i}>{i}</option>))}
        </Field>
    </Form>
)}
</Formik>

docs:

*

*https://jaredpalmer.com/formik/docs/api/field

A: you can set enableReinitialize option to true
your formik hook

const formik = useFormik({
        enableReinitialize: true,
        initialValues: $yourState
})

A: <Formik
    enableReinitialize // missing piece!!
    initialValues={props.initialValues}

working here

A: You can add an option that is 'disabled' above the options that you are populating dynamically:
<Formik>
 <option disabled value="">(Make a Selection)</option>
 {(props: any)=>{
 //...

</Formik>

It will display as the first default option with a message of your choice, and the user won't be able to select it from the dropdown.

A: You are setting your key to 'default' but your value and innerHTML to {defaultValue} which I don't see defined anywhere. This could cause the blank if defaultValue is undefined.
Also you overwrote defaultOption in your inner scope because it is already defined in the outer scope

A: None of the above worked for me.
Here is what worked.
Formik API setFieldValue
So if you have a custom component that is getting initial values but your changing that say from a backend call, you'd use setFieldValue to get the field value updated from the initial one.
In my case, the drop down would have the initial value. It would not update unless I clicked it. I wanted the initialValue to change and this is how I did it.
<Field className='col form-control form-control-sm' id='department' name='department'>
                                {
                                    (props) => {
                                        const { field, form, meta } = props
                                        return (
                                            <DepartmentList field={field} form={form} hotelId={form.values.hotelId} />
                                        )
                                    }
                                }
                            </Field>

Inside that component, where relevant, change the FieldValue of department like this:
this.props.form.setFieldValue('department', this.state.department[0].id)


text:
Q: How did solr designers/architects/developers decide to use 8983 port by default? Some companies (e.g., google) is known to encrypt their names or the names of the products into port numbers (under which the service is running). I am wondering: is there a historical reason, why solar uses the port 8983 port (7574) be default?

A: they just picked a number that was not being used at the time, see Chris Hostetter's mention in this discussion over changing the port.


text:
Q: Error R Studio and RGUi encountered a fatal error- Crashed. Predictive modelling for categorical large data set I am working on a data set that has 21 attributes. 16 are categorical, 3 are ordinal factors and 2 are date/ time(target variable). Number of rows are 14512.
What I what to achieve: This data set is basically about daily office incidents closed by different teams, and we are trying to predict the time that will be taken in case of certain predictor variables.
I am using R-Studio for the analysis.
Work done: So I thought to use Knn for computation and converted all predictors to binary dummy variables and target variable to A, B,C classed categorical.
Issue: Now once I apply the knn function example:
RPS_test_pred <- knn(train = RPS_train, test = RPS_test,cl = RPS_train_labels, k=1121)

keeping k as 1121(as we have 14513 rows in the data set, also training and test data divided to 70:30 ratio)
R studio crashes and closes stating - a fatal error occurred.
Please suggest any other way to compute this data or any other modelling technique that I should use which will suit this type of data more with example.

A: In the past I have worked with datasets containing many ordinal and categorical variables and have found success in doing some transformations to make them numerical. Here are some examples from work with housing price data.
Ordinal Variables
I would start by recommending to change your ordinal variables into numerical values based on their relative order:
train$Exter.Quality[train$ExterQual == "Excellent"] <- 4
train$Exter.Quality[train$ExterQual == "Good"] <- 3
train$Exter.Quality[train$ExterQual == "Nominal"] <- 2
train$Exter.Quality[train$ExterQual == "Fair"] <- 1

Categorical Variables
Has worked to utilize group rankings based on the mean of the response variable you are looking at(Sale Price in my case):
nbhdprice <- summarize(group_by(train, Neighborhood),
          mean(SalePrice, na.rm=T))

nbhdprice_lo <- filter(nbhdprice, nbhdprice$`mean(SalePrice, na.rm = T)` < 140000)
nbhdprice_med <- filter(nbhdprice, nbhdprice$`mean(SalePrice, na.rm = T)` < 200000 &
                          nbhdprice$`mean(SalePrice, na.rm = T)` >= 140000 )
nbhdprice_hi <- filter(nbhdprice, nbhdprice$`mean(SalePrice, na.rm = T)` >= 200000)

train$nbhd_price_level[train$Neighborhood %in% nbhdprice_lo$Neighborhood] <- 1
train$nbhd_price_level[train$Neighborhood %in% nbhdprice_med$Neighborhood] <- 2
train$nbhd_price_level[train$Neighborhood %in% nbhdprice_hi$Neighborhood] <- 3

More examples can be found in the code space here: https://www.kaggle.com/skirmer/fun-with-real-estate-data/code


text:
Q: Regular expression matches to repeated part although I use a question mark I was needed to check if paths have correct names then I've created a regular expression as below:
^\/2\d{3}(\/2\d{3}-(0[1-9]|1[0-2])(\/[a-z ]+(\/(g|o)(\/[a-z ]+(\/s)?)?)?)?)?$

And it works for correct names but unfortunately, it also matches the wrong one like the next: /2020/2020-05/test/o/test. The last test is invalid I must decline this path.
Examples of correct paths:

*

*/2020/2020-05/test/o

*/2020/2020-05/test/o/s (maximum, a nothing can be yet at the end)

*/2020/2020-05/test

*/2020/2020-05

*/2020
Examples of incorrect paths:

*

*/2020/2020-05/test/o

*/2020/2020/2020-05/test/o/smth

*/2020/2020-05/test/test/o

*/2020/2020-05/test/o/o/smth

*and so on

But as I know the question mark matches zero or one time so I cannot get what's wrong with my expression. Can anyone explain me, plz?
P.S. I use Python regular expressions if it's important.

A: It appears you added the last but one optional group by mistake. You need to remove it:
^/2\d{3}(/2\d{3}-(0[1-9]|1[0-2])(/[a-z ]+(/[go](/s)?)?)?)?$

Or, using non-capturing groups for better performance:
^/2\d{3}(?:/2\d{3}-(?:0[1-9]|1[0-2])(?:/[a-z ]+(?:/[go](?:/s)?)?)?)?$

See the regex demo.
Pattern details

*

*^ - start of string

*/2 - a /2 substring

*\d{3} - three digits

*(?:/2\d{3}-(?:0[1-9]|1[0-2])(?:/[a-z ]+(?:/[go](?:/s)?)?)?)? - an optional occurrence of

*

*/2\d{3}- - /2 and then any three digits

*(?:0[1-9]|1[0-2]) - either 0 and then any non-zero digit or 1 followed with 0, 1 or 2

*(?:/[a-z ]+(?:/[go](?:/s)?)?)? - an optional occurrence of

*

*/[a-z ]+ - / and then one or more spaces or lowercase ASCII letters

*(?:/[go](?:/s)?)? - an optional occurrence of

*

*/[go] - / and g or o

*(?:/s)? -  - an optional occurrence of /s

*$ - end of string.


text:
Q: Limit superior of a sequence of oscillating functions related to Chebyshev polynomials Let $n \in \mathbb N$ and consider the polynomial function $f_n \colon \mathbb R \to \mathbb R$ defined by
$$f_n(x) = \sum_{k=0}^n (-1)^k \binom {2n+1} {2k+1} (1 - x^2)^{n-k} x^{2k}$$
for any $x \in \mathbb R$. (These functions are related to Chebyshev polynomials, see the update below.)
By plotting the graphs of the functions as $n$ increases, one sees that they exhibit an oscillating behavior in $[-1, 1]$. For example, here are the graphs of  $f_3, f_5, f_7$:

As $n \to \infty$, it looks as though the crests of the wave describe the graph of another function. For example, here is the graph of $f_{50}$:

Let $f \colon D \to \mathbb R$ be defined by
$$f(x) = \limsup_{n \to \infty} f_n(x)$$
whenever the limit superior exists and is finite. I would like to find as much information as possible about this function.
So far, I have only been able to show the following (see the update below):

*

*$f$ is an even function, since all of the $f_n$'s are even.

*$0 \notin D$. Indeed, $f_n(0) = 2n + 1 \to \infty$ as $n \to \infty$.

*$f(\pm 1) = 1$, because $f_n(\pm 1) = (-1)^n$ for any $n \in \mathbb N$.

*$f \left (\pm \frac {\sqrt 2} 2 \right ) = 1$. This is because:
$$f_n \left ( \pm \frac {\sqrt 2} 2 \right ) = \sum_{k=0}^n (-1)^k \binom {2n+1} {2k+1} \left ( \frac 1 2 \right )^n = (-1)^{\left \lfloor \frac n 2 \right \rfloor} 2^n \left ( \frac 1 2 \right )^n = (-1)^{\left \lfloor \frac n 2 \right \rfloor} \le 1$$
In particular, $f_{4m} \left (\pm \frac {\sqrt 2} 2 \right ) = 1$ for any $m \in \mathbb N$, so $\limsup_{n \to \infty} f_n \left ( \pm \frac {\sqrt 2} 2 \right ) = 1$.
By looking at the definition of $f_n(x)$, it seems as though one should use the binomial theorem to find a better expression to work with, but I'm not sure how.

What else can we say about $f$? Is it possible to find a "simple" expression?

Thank you in advance for any reply.

Update: By looking up the coefficients of the first few polynomials, I found out that they are closely related to the Chebyshev polynomials of the second kind. In fact, it appears that
$$f_n(\sin \alpha) = \frac {\sin ((2n+1) \alpha)}{\sin \alpha}$$
for any $\alpha \in \mathbb R \smallsetminus \pi \mathbb Z$, which immediately provides us with many other values of $f$. For instance,
$$f_n \left (\sin \frac \pi 6 \right ) = \frac{\sin \left ( (2n+1) \frac \pi 6 \right )}{\sin \frac \pi 6} \le \frac 1 {\frac 1 2} = 2$$
In particular,
$$f_{6m+1} \left (\sin \frac \pi 6 \right ) = \frac{\sin \left ( (12 m + 3) \frac \pi 6 \right )}{\sin \frac \pi 6} = \frac{\sin \left ( 2 m \pi + \frac \pi 2 \right )}{\sin \frac \pi 6} = \frac 1 {\frac 1 2} = 2$$
for any $m \in \mathbb N$, and thus $f \left (\pm \frac 1 2 \right ) = 2$.

How can we get a simple expression for $f$ using this information?

A: This is not an answer since it is just the result from a CAS.
Defining $$u=1-2 x^2-2 \sqrt{x^2 \left(x^2-1\right)} \qquad \text{and}\qquad v=1-2 x^2+2 \sqrt{x^2 \left(x^2-1\right)}$$ a CAS produced
$$f_n(x)=\frac{ \left(u^n+v^n\right)}{2 }+\frac{ \left(u^n-v^n\right)}{2 }\,\frac{\sqrt{x^2 \left(x^2-1\right)}
   }{ x^2}$$
Edit
This will not help much, I am afraid, but after your edit, I computed
$f_n\left(\sin \left(\frac{\pi  k}{12}\right)\right)$ and obtained the (may be) interesting values
$$\left(
\begin{array}{cc}
 k & f_n\left(\sin \left(\frac{\pi  k}{12}\right)\right) \\
 0 & 2 n+1 \\
 1 & \cos \left(\frac{n \pi }{6}\right)+\left(2+\sqrt{3}\right) \sin \left(\frac{n
   \pi }{6}\right) \\
 2 & \cos \left(\frac{n \pi }{3}\right)+\sqrt{3} \sin \left(\frac{n \pi }{3}\right)
   \\
 3 & \cos \left(\frac{n \pi }{2}\right)+\sin \left(\frac{n \pi }{2}\right) \\
 4 & \cos \left(\frac{2 n \pi }{3}\right)+\frac{1}{\sqrt{3}}\sin \left(\frac{2 n \pi
   }{3}\right) \\
 5 & \cos \left(\frac{5 n \pi }{6}\right)+\left(2-\sqrt{3}\right) \sin
   \left(\frac{5 n \pi }{6}\right) \\
 6 & (-1)^n
\end{array}
\right)$$

A: Note that $f_n(0)=2n+1$ and so $f$ is undefined for $x=0$.
Otherwise, for $\alpha \in (0,\pi/2]$ where $\sin(\alpha)>0$ $$f(\sin(\alpha)) = \frac{\sup_n \sin((2n+1)\alpha)}{\sin(\alpha)}.$$
If $\alpha$ is an irrational multiple of $2\pi$ then $(2n+1)\alpha \pmod{2\pi}$ is dense in $[0, 2\pi]$ and therefore $\sup_n \sin((2n+1)\alpha)=1$. So in this case $$f(\sin(\alpha))=\sin^{-1}(\alpha).$$ If $\alpha = 2\pi \frac{p}{q}$ for some coprime integers $p, q$ then a case by case examination on $q \pmod 8$ shows
$$s(q) = \sup_n \sin((2n+1)\alpha) = \begin{cases}
\cos(\frac{\pi}{2q}) & \textrm{If $q$ is odd}\\
\cos(\frac{\pi}q) & \textrm{If $q \equiv 2, 6 \pmod 8$}\\
\cos(\frac{2\pi}q) & \textrm{If $q \equiv 0 \pmod 8$}\\
1 & \textrm{If $q \equiv 4 \pmod 8$}
\end{cases}$$
so in this case $$f(\sin(\alpha))=\frac{s(q)}{\sin(\alpha)}.$$ Since you already noted that $f$ is even this completely describes $f$.


text:
Q: Why do I get a blank pdf when uploaded on S3? I upload a pdf blob object to S3
      const params = {
        Bucket: "poster-print-bucket",
        Key: Date.now().toString() + ".pdf",
        Body: blob,
        contentType: "application/pdf",
      };

      const uploaded = await S3.upload(params).promise();

When I open a url which is i.e https://poster-print-bucket.s3.ca-central-1.amazonaws.com/1633526785678.pdf
It downloads me a blank pdf
I thought maybe my blob is corrupted or something but I managed to upload same blob to firebase storage just fine.
btw I'm using nextjs api/upload-poster route
What's happening?

A: I spent more time fixing this issue than I would like to admit.
Here is the solution:
Frontend (converting blob to base64 before sending to backend):
            function toBase64(blob) {
              const reader = new FileReader();
              return new Promise((res, rej) => {
                reader.readAsDataURL(blob);
                reader.onload = function () {
                  res(reader.result);
                };
              });
            }

            toBase64(currentBlob)
              .then((blob) => {
                return axios
                  .post("/api/upload-poster", blob, {
                    headers: {
                      "Content-Type": "application/pdf",
                    },
                  })
                  .then(({ data }) => data.uploaded.Location);
              })

Backend:
      const base64 = req.body;
      const base64Data = Buffer.from(base64.replace(/^data:application\/\w+;base64,/, ""), "base64");

      const params = {
        Bucket: "poster-print-bucket",
        Key: nanoid() + ".pdf",
        Body: base64Data,
        ContentEncoding: "base64",
        contentType: "application/pdf",
      };

      const uploaded = await S3.upload(params).promise();

Why this all song and dance is required? Can it be something easier?

A: Using the AWS SDK v3 (up-to-date at the time of this post), you could use PutObjectCommand which accepts a Uint8Array as Body params (docs).
Convert your Blob instance to an ArrayBuffer (docs), and your ArrayBuffer to an Uint8Array.
Code would look like:
const { S3Client, PutObjectCommand } = require('@aws-sdk/client-s3');
const client = new S3Client(/* config */);

const arrayBuffer = await blob.arrayBuffer();
const typedArray = new Uint8Array(arrayBuffer);
await client.send(new PutObjectCommand({
   Bucket: /* ... */,
   Key: /* ... */,
   Body: typedArray,
}));


text:
Q: How to make my Overlay not to cover my dropdown content? I am creating a dropdown in my fixed position navbar.   When I click on open button,  I want my overlay to cover everything except my dropdown content.
I have tried setting the z-index my dropdown content to 10000 but it didn't work.

$("#dropDownButton").click(function () {

    $(".dropdown-content").toggleClass("show");

    if ($(".dropdown-content").hasClass("show")) {
        $(".overlayT").fadeIn(500);
    } else {
        $(".overlayT").fadeOut(500);
    }

});
body {
    font-family: "Lato", sans-serif;

}

.overlayT {
    position: fixed;
    top: 0;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 2;
    display: none;
    height: 100%;
    width: 100%;
}

.dropdown {
    position: relative;
    display: inline-block;

}

.dropdown-content {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
    min-width: 200px;
    border-radius: 5px;
    padding-top: 2rem;
    z-index: 10000;
}

.dropdown-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
}

.dropdown-content a:hover {
    background-color: #f1f1f1
}

.show {
    display: block;
}

      ☰ open

              Home
              Account

              Sign Out

How do I make my overlay not to cover my dropdown content?  (It does work if my navbar is not fixed position but I need my navbar to be fixed).   Please help.   Thanks

A: You may move the .overlayT element into the span element to be a sibling of .dropdown-content, because they will be on the same level. It helps to control which one will be in front of each other:

        ☰ open

            Home
            Account
            Sign Out

Then, add left: 0 to overlay in order to position it correctly:
.overlayT {
    position: fixed;
    top: 0;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 2;
    display: none;
    height: 100%;
    width: 100%;
    left: 0;
}


text:
Q: How to export react-froala-wysiwyg editor in an NPM module? This question refers to the react-froala-wysiwyg package.
I have an npm module which consists of re-usable react components which I deploy across various projects.
I've just inserted react-froala into my package and it renders nicely in storybook as you can see below:

However, when I call the component from one of my project applications, I get this:

I notice the following error in my console. How should I resolve this?
/Users/joel/Sites/node_modules/dist/index.js:30398
                __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)):"object"==typeof module&&module.exports?module.exports=function(e,t){return t===undefined&&(t="undefined"!=typeof window?require("jquery"):require("jquery")(e)),n(t)}:n(window.jQuery)}(function(be){var s=function(e,t){this.id=++be.FE.ID,this.opts=be.extend(!0,{},be.extend({},s.DEFAULTS,"object"==typeof t&&t));var n=JSON.stringify(this.opts);be.FE.OPTS_MAPPING[n]=be.FE.OPTS_MAPPING[n]||this.id,this.sid=be.FE.OPTS_MAPPING[n],be.FE.SHARED[this.sid]=be.FE.SHARED[this.sid]||{},this.shared=be.FE.SHARED[this.sid],this.shared.count=(this.shared.count||0)+1,this.$oel=be(e),this.$oel.data("froala.editor",this),this.o_doc=e.ownerDocument,this.o_win="defaultView"in this.o_doc?this.o_doc.defaultView:this.o_doc.parentWindow;var r=be(this.o_win).scrollTop();this.$oel.on("froala.doInit",be.proxy(function(){this.$oel.off("froala.doInit"),t

TypeError: Cannot set property 'froalaEditor' of undefined
    at Object.<anonymous> (/Users/joel/Sites/node_modules/dist/index.js:30398:5564)
    at t.id (/Users/joel/Sites/node_modules/dist/index.js:30397:37)
    at Object.<anonymous> (/Users/joel/Sites/node_modules/dist/index.js:30398:286)
    at __webpack_require__ (/Users/joel/Sites/node_modules/dist/index.js:30:30)
    at Object.<anonymous> (/Users/joel/Sites/node_modules/dist/index.js:30297:1)
    at __webpack_require__ (/Users/joel/Sites/node_modules/dist/index.js:30:30)
    at Object.<anonymous> (/Users/joel/Sites/node_modules/dist/index.js:29418:21)
    at __webpack_require__ (/Users/joel/Sites/node_modules/dist/index.js:30:30)
    at Object.defineProperty.value (/Users/joel/Sites/node_modules/dist/index.js:22870:27)
    at __webpack_require__ (/Users/joel/Sites/node_modules/dist/index.js:30:30)

A: Resolved! Turns out this issue had nothing to do with react-froala per say. The export already works. Issue was that my npm module was not bundling the required styles. I just had to update my webpack config to use the extract-text-webpack-plugin and subsquently import the output css file in my downstream project to get it all going. Good luck!


text:
Q: OpenGL Rotate an Object around It's Local Axes Imagine a 3D rectangle at origin. It is first rotated along Y-axis. So good so far. Now, it is rotated around X-axis. However, OpenGL (API: glrotatef) interprets the X-axis to be the global X-axis. How can I ensure that the "axes move with the object"?
This is very much like an airplane. For example, if yaw (Y rotation) is applied first, and then pitch (X-rotation), a correct pitch would be X-rotation along the plane's local axes.
EDIT: I have seen this called gimbal lock problem, but I don't think it is though.

A: You cannot consistently describe an aeroplane's orientation as one x rotation and one y rotation. Not even if you also store and one z rotation. That's exactly the gimbal lock problem.
The crux of it is that you have to apply the rotations in some order. Say it's x then y then z for the sake of argument. Then what happens if the x rotation is by 90 degrees? That folds the y axis onto where the z axis was. Then say the y rotation is also by 90 degrees. That's now bent the z axis onto where the x axis was. So now what effect does any z rotation have?
That's just an easy to grasp example. It's not a special case. You can't wave your hands out of it by saying "oh, I'll detect when to do z rotations first" or "I'll do 90 degree rotations with a special pathway" or any other little hack. Trying to store and update orientations as three independent scalars doesn't work.
In classic OpenGL, a call to glRotatef means "... and then rotate the current matrix like this". It's not relative to world coordinates or to model coordinates or to any other space that you're thinking in.


text:
Q: Sum of primes using Sieve of Eratosthenes; answer too small For Project Euler problem #10, I wrote a program to find the sum of all prime numbers between 2 and 2,000,000.
My code works for smaller values like 50 or 100, but when I try it with 2,000,000 it returns a value that is too small by 141,675.
I thought it might be because the answer was too long to fit in a long, which is why I use BigInteger, but I've since learned that's not a factor.  I appreciate any thoughts.
public class ProblemTen {

/**
 * Precondition:  all the bits in the set are set to true
 * This method uses the Sieve of Eratosthenes
 * @param p the starting prime number
 * @param b the BitSet array
 * @param s the length of the original BitSet array
 * @return BitSet with all the prime indexes set to true
 */
public static BitSet findPrimes(int p, BitSet b, int s) {
    //System.out.println(b);
    while (p*p < s) {  // repeat until p^2 > size of the ORIGINAL set
        for (int i = 0; i <= b.length(); i++) {
            if (i%p == 0) { // if it's a multiple of p
                b.set(i, false); // set it to false (not prime)
            }
        }
        p = b.nextSetBit(p); // Make p = first bit that is set to true starting after the previous p index.
    }
    return b;
}

/**
 * @param args
 */
public static void main(String[] args) {

    int set = 2000000;

    BitSet bits = new BitSet(set);
    for (int i = 0; i < set; i++) {
        bits.set(i); // set all bits to True; when you print only the true ones print out
    }
    BitSet primeBits = new BitSet(set);
    primeBits = findPrimes(2, bits, set);
    //System.out.println("List of primes: " + primeBits);

    BigInteger sum = BigInteger.ZERO;
    for (int j = 0; j <= primeBits.length(); j++) {
        if (primeBits.get(j) == true ) {
            sum = sum.add(BigInteger.valueOf(j));
        }
    }

    System.out.println("Sum is: " + sum); // I get 142,913,687,247 which is 141,675 too small (142913828922)
}

}

A:     while (p*p < s) {  // repeat until p^2 > size of the ORIGINAL set
        for (int i = 0; i <= b.length(); i++) {
            if (i%p == 0) { // if it's a multiple of p
                b.set(i, false); // set it to false (not prime)
            }
        }
        p = b.nextSetBit(p);
        // Make p = first bit that is set to true starting after the previous p index.
    }

Marks all multiples of the prime p as composite, including p itself. So only the primes larger than the square root of the limit remain unmarked.

*

*This method uses the Sieve of Eratosthenes

No, it doesn't. It uses trial division. You divide each number by all primes smaller than the square root of the limit and check whether the remainder is 0.
The loop should be
for(int i = p*p; i < b.length; i += p)
    b.set(i,false);

to implement the Sieve of Eratosthenes.

A: Your solution is not the Sieve of Eratosthenes, it's trial division; the modulo operator gives it away. Here is pseudocode for a proper Sieve of Eratosthenes that sums the primes that it finds:
function sumPrimes(n)
    sum := 0
    sieve := makeArray(2..n, True)
    for p from 2 to n step 1
        if sieve[p]
            sum := sum + p
            for i from p * p to n step p
                sieve[i] := False
    return sum

I'll leave it to you to translate the code to Java. If you are interested in programming with prime numbers, I modestly recommend this essay at my blog, which includes a Sieve of Eratosthenes in Java. The code there will also help you with some of the other Project Euler problems.

A: for (int i = 0; i <= b.length(); i++)

change it to
for (int i = p+1; i <= b.length(); i++)

Otherwise you're eliminating all primes smaller than 2,000,000^.5


text:
Q: Setting up Google Apps I have registered a domain (though there is no hosting yet, just name registration) and I am trying to set up google apps so that I can have email, but I cannot figure it out.  Is there something I am missing?  I feel like it should be easier than it is right now.

A: You need to correctly set the MX records at your registrar.

A: Have you proved domain ownership including a CNAME record in your DNS server? Just follow the instructions.
If you don't have access to your DNS server for adding records, and don't have a webserver where you can put a verification file I think you wont be able do setup e-mail.

A: If you already have the domain, you just need to follow the registration process, you will be taken through all the steps. If you got to the Admin Console you should have a message bar Top of the page with Verify Domain.
the best way to do it is to try the new Learning Center, http://learn.googleapps.com/.


text:
Q: Why I can't view my UDP received Image in Android Studio? I succeeded in sending a string from Android Studio Java UDP Client to Visual Studio C# UDP Server, and a response back from the Server to the Client.
Now I am trying to send an Image back from the server instead of a string response. So on client button click, I am supposed to get an Image back from the server. No syntax errors and no weird behavior. It's just nothing happens and I can't seem to see the received image on my ImageView and when I step over it my final Bitmap ReceivedImage is null
Do I need to convert into something other than Bitmap? Is this the right way? Maybe something else.. Can anyone help me point out my mistake? Thanks
C# Server:
    class UdpServer
{
    static void Main(string[] args)
    {
        byte[] dataReceived = new byte[1024];
        UdpClient serverSocket = new UdpClient(15000);

        string path = "C:\\Users\\kkhalaf\\Desktop\\Capture.PNG"; // image path
        FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read); // prepare
        BinaryReader br = new BinaryReader(fs); // prepare
        byte[] dataToSend = br.ReadBytes(Convert.ToInt16(fs.Length)); //Convert image to byte[]

        int i = 0;
        while (true) // this while for keeping the server "listening"
        {
            Console.WriteLine("Waiting for a UDP client..."); // display stuff
            IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0); // prepare
            dataReceived = serverSocket.Receive(ref sender); // receive packet
            string stringData = Encoding.ASCII.GetString(dataReceived, 0, dataReceived.Length); // get string from packet
            Console.WriteLine("Response from " + sender.Address); // display stuff
            Console.WriteLine("Message " + i++ + ": " + stringData + "\n"); // display client's string

            // Here I am sending back
            serverSocket.Send(dataToSend, 8, sender);
        }
    }
}

Java Client: On button click this function gets called to send-receive-display
    public void SendUdpMsg(final String msg)
{
    Thread networkThread = new Thread() {

        // No local Host 127.0.0.1 in Android
        String host = "192.168.200.3"; // Server's IP
        int port = 15000;
        DatagramSocket dsocket = null;

        public void run() {
            try {
                // Get the Internet address of the specified host
                InetAddress address = InetAddress.getByName(host);

                // wrap a packet
                DatagramPacket packetToSend = new DatagramPacket(
                        msg.getBytes(),
                        msg.length(),
                        address, port);

                // Create a datagram socket, send the packet through it.
                dsocket = new DatagramSocket();
                dsocket.send(packetToSend);

                // Here, I am receiving the response
                byte[] buffer = new byte[1024]; // prepare
                DatagramPacket packetReceived = new DatagramPacket(buffer, buffer.length); // prepare
                dsocket.receive(packetReceived); // receive packet
                byte[] buff = packetReceived.getData(); // convert packet to byte[]
                final Bitmap ReceivedImage = BitmapFactory.decodeByteArray(buff, 0, buff.length); // convert byte[] to image

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // this is executed on the main (UI) thread
                        final ImageView imageView = (ImageView) findViewById(R.id.imageView);
                        imageView.setImageBitmap(ReceivedImage);
                    }
                });
                dsocket.close();
            } catch (Exception e) {
                e.printStackTrace();
            }//catch
        }//run
    };// Networkthread
    networkThread.start();//networkThread.start()
}

A: Isn't much of an answer, but since I can't comments yolo
You should use TCP, it is so much better. Using UDP, I even loose data when it is 400 bytes.
It might be
serverSocket.Send(dataToSend, 8, sender);

Change it to
serverSocket.Send(dataToSend, dataToSend.Length, sender);

Also, try first sending the length of the image (dataToSend.Length) to the client, then have the client use the length you sent it to create a byte array. Kind like
byte[] buffer = new byte[recievedLengthOfImage]


text:
Q: Replace a NaN index value in dataframe I'm new to Python and things in general are going pretty well. However, I've come across a problem that seems pretty simple, but it's killing me!
I have a dataframe with a NaN value in the index. I want to change this so that it makes more sense when I come to plotting it.
I have:
       Open
NaN    50
Yes    102
No     134

And all I want is to replace the NaN so I have:
               Open
No response    50
Yes            102
No             134

What's the easiest way to do it?

A: You can use Index.fillna:
df.index = df.index.fillna('No response')
print (df)
              Open
No response     50
Yes            102
No             134


text:
Q: R shiny | How to list Months  as a radioButton list I'm working with a summary table that looks like this:

This is the dataset for a heat map. In my Shiny app, I would like to visualize the heatmap with the option of selecting the year and month (the table is already excluding null values).
I have extracted the year and the month for my lists of options as follows:
OverageYPool <- Overagelogbypool$Year %>% as.list(Year) %>% unique()
OverageMPool <- Overagelogbypool$Month %>% as.list(Month) %>% unique()

This is how my OverageMPool is displayed:
> OverageMPool
[[1]]
[1] Jul
Levels: Jan < Feb < Mar < Apr < May < Jun < Jul < Aug < Sep < Oct < Nov < Dec

[[2]]
[1] Aug
Levels: Jan < Feb < Mar < Apr < May < Jun < Jul < Aug < Sep < Oct < Nov < Dec

[[3]]
[1] Sep
Levels: Jan < Feb < Mar < Apr < May < Jun < Jul < Aug < Sep < Oct < Nov < Dec

[[4]]
[1] Oct
Levels: Jan < Feb < Mar < Apr < May < Jun < Jul < Aug < Sep < Oct < Nov < Dec

[[5]]
[1] Nov
Levels: Jan < Feb < Mar < Apr < May < Jun < Jul < Aug < Sep < Oct < Nov < Dec

[[6]]
[1] Dec
Levels: Jan < Feb < Mar < Apr < May < Jun < Jul < Aug < Sep < Oct < Nov < Dec

[[7]]
[1] Jan
Levels: Jan < Feb < Mar < Apr < May < Jun < Jul < Aug < Sep < Oct < Nov < Dec

[[8]]
[1] Feb
Levels: Jan < Feb < Mar < Apr < May < Jun < Jul < Aug < Sep < Oct < Nov < Dec

[[9]]
[1] Mar
Levels: Jan < Feb < Mar < Apr < May < Jun < Jul < Aug < Sep < Oct < Nov < Dec

>

While the year doesn't present any issues, when I display the month list in the app I get the month number rather than the month name, and I get an error (Error in <-: replacement has length zero) in place of the plot.  I assume that there is no match between the input format and the table format and that's why I'm getting the error.

I'm not sure how to convert the values in that list to match the format in the table (and to order them by month) other than hardcode them in the list. Any suggestions?
I'm adding the rest of the code for the function for completeness:
reactive filtering
  filteredPoolbyYandM <- reactive({
    dplyr::filter(Overagelogbypool, Year == input$poolyear & Month == input$poolmonth)
  })

  output$Poolheatmap <- renderPlot(V_Overagelogbypool(filteredPoolbyYandM()), res = 96)

plot function
filteredPoolbyYandM <- Overagelogbypool

V_Overagelogbypool <- function(filteredPoolbyYandM) {
                             filteredPoolbyYandM %>%
                               ggplot(aes(x = Context, y = Pool)) +
                               geom_tile(mapping = aes(fill = Exceeding), alpha = 0.5) +
                               scale_x_discrete(expand = c(0.3, 0)) +
                               labs(x = "Destination call context", y = "Pool", color = "Exceeding (m)")
     }

Thanks in advance!

A: The numbers appearing in the radio boxes is down to the way the radioButtons works with a list of factors compared to a vector. If you keep them as a vector you won't have this issue.
OverageMPool <- sort(unique(Overagelogbypool$Month))

Alternatively, in base R there is month.abb which contains the shortened month names in order.


text:
Q: EF Query using .Contains() and .ToLowerInvariant() Results in no matches when match is found at the end of a string Is it possible to step into a linq query? I have a linq to entity framework 4 query in it's simplest form:
List = List.Where(f => f.Value.ToString().ToLowerInvariant().Contains(filter.ToLowerInvariant()));

It's a query against an Entity Framework DbContext and I'm having trouble seeing why it works for something like:
List searching for 001 yields no results against the following list

*

*Test001

*Test002

*Test003

*Test004

However any other search yields results (Such as t00 or Test)
Update
Basically I'm looking for why a query such as the above wouldn't return a result when I'm using a contains and the value matches the end of a string vs just the middle or begining. It's really confusing.
OK, it appears to have something to do with ToLowerInvariant() - when I removed that method it works just fine.

A: It appears that ToLowerInvariant() produces the error. ToLower() works just fine.

A: try working with linqpad

A: As Dani suggested, LinqPad is a great tool for this. And, even though it will not allow you to "step into" Linq queries, you can use an extended method offered in LinqPad named Dump() that will show you the value of IEnumerable or IQueryable objects as you progress through your query. It is extremely useful.

A: Is this query being run against the database (LINQ to EF) or against objects already in memory (LINQ to objects).   I'm guessing that it is LINQ to objects based on a comment you made on another answer, in which case you should be able to set a breakpoint in the lambda expression.

A: Why don't you do a selection on that ToLowerInvariant() to see what it is returning.


text:
Q: Dynamically profile the name of the class called for reflection site in java Is there any possible way to know the name of the class called for each reflection site in runtime Java?
For a more concrete example, in java code we may have
   String className = readfromXMlConfig; //read from xml config file
  class c = Class.forName(className);

  ExampleInterface factory = (ExampleInterface)c.newInstance();

The className is not clear in static analysis, however the information can be known in runtime. I would like to record the resolved names of the classes dynamically for future analysis.
I have investigated state-of-the-art static analysis tools (e.g., Soot) for handling reflection, and found this is what they commonly do. Unfortunately I cannot use Soot for version-compatibility reason and have to implement the dynamic part myself.


text:
Q: process.on('unhandledRejection') is not logging error In my server.js file i'm trying to log errors and not cause them to crash the app, this is the code im using
const server = app.listen(3000, () =>
    console.log('Server Up and running')
);

process.on('unhandledRejection', (err, promise) => {
    console.log(`Error: ${err}`);
    server.close(() => process.exit(1));
})

when i produce an error instead of it logging the error and closing the server it just logs the error how it normally would and causes the app to crash. If you need more info let me know. Sorry if this is a dumb question

A: I suppose you know the difference between Unhandled Rejection and Uncaught Exception.

it just logs the error how it normally would

Because you're console logging the same error object!
Also don't use process.exit(). Because you might lose your logs. read more
Express docs explained how to do graceful shutdown, you can use similar approach.


text:
Q: Charge conservation in the complex Klein-Gordon Field This is an extremely naive question (based on a knowledge of chapter 2 of peskin and schroeder) so apologies for any things that seem obvious. The complex scalar field, when quantized, has a conserved charge $$Q \propto\int d^3x\left(\phi^*(x)\dot\phi(x)-\dot\phi^*(x)\phi(x)\right)=\int\frac{d^3p}         {(2\pi)^3}\Big(a^\dagger(\vec p)a(\vec p)-b^\dagger(\vec p)b(\vec p)\Big)$$ (up to an infinite constant, etc). We interpret the $a$ particles as positively charged and the $b$ particles as equally negatively charged, and further we see that $$Q\propto N(a)-N(b)$$ where $N(a,b)$ are the number operators. According to this, charge conservation predicts that if we create an $a$ particle then a $b$ particle must be created also to cancel out charge (and similarly for destruction).

*

*In general, does this mean that no charged particles can be created in a QFT without a corresponding antiparticle appearing also (and is this the mathematical apparatus usually used to display this?)

*Also, if this is all true, how is it even possible that there are more electrons in the universe than positrons?

A: For the first question: there may be several species of particle in a theory, so charge conservation can be upheld without creating a particle and its antiparticle together. For example, in beta decay, an electron is `created', but no positron, and charge conservation is upheld by a neutron being exchanged for a proton.
This partially answers question two (for example, at high energies it is expected that lepton and baryon conservation should be violated, so it may be possible to create an electron and a proton starting with neutral stuff), though it still remains a problem to explain matter/antimatter asymmetry.


text:
Q: android.content.ActivityNotFoundException: Unable to find explicit activity class { have you declared this activity in your AndroidManifest.xml? I'm having these error

android.content.ActivityNotFoundException: Unable to find explicit activity class {}; have you declared this activity in your AndroidManifest.xml?
          at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:2005)
          at android.app.Instrumentation.execStartActivity(Instrumentation.java:1673)
          at android.app.Activity.startActivityForResult(Activity.java:4586)
          at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:676)
          at androidx.core.app.ActivityCompat.startActivityForResult(ActivityCompat.java:234)
          at androidx.fragment.app.FragmentActivity.startActivityFromFragment(FragmentActivity.java:791)
          at androidx.fragment.app.FragmentActivity$HostCallbacks.onStartActivityFromFragment(FragmentActivity.java:933)
          at androidx.fragment.app.Fragment.startActivity(Fragment.java:1185)
          at androidx.fragment.app.Fragment.startActivity(Fragment.java:1173)
          at com.example.gerobokgo.AccountFragment.openUpdateProfile(AccountFragment.java:110)
          at com.example.gerobokgo.AccountFragment.access$000(AccountFragment.java:29)
          at com.example.gerobokgo.AccountFragment$2.onClick(AccountFragment.java:93)

I'm having error on these code
// For update and pass information method
    private void openUpdateProfile() {

        Intent intent= new Intent(getActivity(), UpdateProfileFragment.class);

        //pass value from current to next page
        intent.putExtra("name",tv_name.getText().toString().trim());
        intent.putExtra("email", tv_email.getText().toString().trim());
        intent.putExtra("Home Address",tv_home.getText().toString().trim());
        intent.putExtra("Telephone", tv_phone.getText().toString().trim());
        startActivity(intent);

    }

public class AccountFragment extends Fragment

 //For Update Method

        btn_update.setOnClickListener( new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                openUpdateProfile();
            }

AndroidManifest
<application
        android:name=".Home"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".RegisterActivity"
            android:screenOrientation="portrait"></activity>
        <activity android:name=".LoginActivity"
            android:screenOrientation="portrait"/>
        <activity
            android:name=".splashScreen"
            android:theme="@style/SplashScreen">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".MainActivity"
            android:theme="@style/AppTheme" />
    </application>

UpdateProfileFragment.java
public class UpdateProfileFragment extends Fragment implements View.OnClickListener {
    EditText tv_name, tv_email, tv_home, tv_phone;
    Button btn_update;

    FirebaseAuth firebaseAuth;
    FirebaseUser currentUser;
    DatabaseReference databaseReference;

    public UpdateProfileFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_update_profile, container, false);

        //get data from intert (data from previous page)

        Intent intent = getActivity().getIntent();
        String name = intent.getStringExtra("Name");
        String email = intent.getStringExtra("Email");
        String address = intent.getStringExtra(" Shipping Address");
        String phone = intent.getStringExtra("Telephone Number");

        //ini
        firebaseAuth = FirebaseAuth.getInstance();
        currentUser = firebaseAuth.getCurrentUser();
        databaseReference = FirebaseDatabase.getInstance().getReference("Customer").child(firebaseAuth.getUid());

        tv_name = view.findViewById(R.id.tv_name);
        tv_email = view.findViewById(R.id.tv_email);
        tv_home = view.findViewById(R.id.tv_home);
        tv_phone = view.findViewById(R.id.tv_phone);

        tv_name.setText(name);
        tv_email.setText(email);
        tv_home.setText(address);
        tv_phone.setText(phone);

        btn_update.setOnClickListener(this);

        return view;
    }

    @Override
    public void onClick(View view) {

    }

    private void updateProfile() {
        Intent intent = getActivity().getIntent();

        String userUid = firebaseAuth.getCurrentUser().getUid();
        String name = tv_name.getText().toString().trim();
        String email = tv_email.getText().toString().trim();
        String home = tv_home.getText().toString().trim();
        String phone = tv_phone.getText().toString().trim();

        Customer cust = new Customer(userUid, name, email, home, phone);
        databaseReference.child("Customer").child(userUid).setValue(cust).addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                if (task.isSuccessful()) {
                    Toast.makeText(getActivity(), "Update Successfully", Toast.LENGTH_SHORT).show();
                    getActivity().finish();
                    startActivity(new Intent(getActivity(), AccountFragment.class));

                }
            }
        });
    }
}

A: As per your Code UpdateProfileFragment is activity inside openUpdateProfile method.
You should declare the UpdateProfileFragment activity in AndroidManifest before using.
Edit:
As UpdateProfileFragment is fragment, So you are calling in wrong way fragment by startActivity(). To call fragemnt from activity do like following -
private void openUpdateProfile() {
Bundle bundle = new Bundle();

bundle.putString("name",tv_name.getText().toString().trim());
bundle.putString("email", tv_email.getText().toString().trim());
bundle.putString("home_address",tv_home.getText().toString().trim());
bundle.putString("telephone", tv_phone.getText().toString().trim());

UpdateProfileFragment updateFrag = new UpdateProfileFragment ();
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();

updateFrag.setArguments(bundle);

transaction.add(R.id.fragmentContainer, updateFrag);
transaction.commit();

}

And in UpdateProfileFragment you can get data like following
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    String name = getArguments().getString("name");
    String email = getArguments().getString("email");
    String address= getArguments().getString("home_address");
    String telephone= getArguments().getString("telephone");
    // rest of your code here.
    ...
    ...

}
NOTE: Incase of UpdateProfileFragment is fragment, no need of declare in manifest file.

A: According to you, UpdateProfileFragment is a fragment.
So you can't call fragment by startActivity(). To call fragemnt from activity you have to do like following.
UpdateProfileFragment frag = new UpdateProfileFragment ();
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.fragmentContainer,frag,"Test Fragment");
transaction.commit();

Also, you can pass data to fragment using setArguments
Example:
private void openUpdateProfile() {

    Bundle bundle = new Bundle();

    bundle.putString("name",tv_name.getText().toString().trim());
    bundle.putString("email", tv_email.getText().toString().trim());
    bundle.putString("home_address",tv_home.getText().toString().trim());
    bundle.putString("telephone", tv_phone.getText().toString().trim());

    UpdateProfileFragment frag = new UpdateProfileFragment ();
    FragmentManager manager = getSupportFragmentManager();
    FragmentTransaction transaction = manager.beginTransaction();

    frag.setArguments(bundle);

    transaction.add(R.id.fragmentContainer,frag,"Test Fragment");
    transaction.commit();

    }

And in your fragment you can get data like following
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        .....
        String name = this.getArguments().getString("name");
        String email = this.getArguments().getString("email");
        String address= this.getArguments().getString("home_address");
        String telephone= this.getArguments().getString("telephone");
        // rest of your code here.
        ...
        ...
}

Hope it helps you.


text:
Q: Sum of product - I am having some issue in minimize the following sum of products.

My solution is:
not A and not B or A and ((B and not C)or C)
But I think it is not right.

A: From the table (the last term is used twice for  a simple reduction) $$\begin{aligned}d&=\underbrace{\big(\bar{a} \wedge \bar b \wedge \bar c\big)\vee\big(\bar{a} \wedge \bar b \wedge  c\big)}\vee \big(a\wedge b \wedge \bar c\big)\vee \big(a\wedge \bar b \wedge  c\big)\vee \big(a\wedge b \wedge c\big)\color{blue}{\vee \big(a\wedge b \wedge c\big)}\\
&=\quad\quad\quad\quad\big(\bar{a} \wedge \bar b )\quad\quad\quad\;\,\vee \underbrace{\big(a\wedge b \wedge \bar c\big)\color{blue}{\vee \big(a\wedge b \wedge c\big)}}\vee \underbrace{\big(a\wedge \bar b \wedge  c\big)\vee \big(a\wedge b \wedge c\big)}\\
&=\quad\quad\quad\quad\big(\bar{a} \wedge \bar b )\quad\quad\quad\;\;\vee\quad\quad\quad\quad\big(a \wedge b\big) \quad\quad\quad\;\vee \quad\quad\quad\;\,\big( a \wedge c\big)\end{aligned}$$
so $$\begin{aligned}d&=\big(\bar{a} \wedge \bar b )\vee\big(a \wedge b\big)\vee\big( a \wedge c\big)\\
&=\big(\bar{a} \wedge \bar b )\vee\big(a \wedge(b\vee c)\big)\end{aligned} $$


text: Q: How to save and retrieve text styled with Spans on Firebase realtime database I used Spans to color and style my texts, how do I save the and retrieve them in their saved state from firebase realtime database?


text: Q: How to add external .java files as library in IntelliJ? I've been looking everywhere, and every post on SO, or tutorial explains how to import a library to a project using .jar files, but the files I have are .java, and nothing I've tried worked so far. Our teacher wants us to implement a JSON file reader in our assignment, using this library, and importing it using import org.json.*; but no matter how I tried (using project settings -> modules -> dependencies or proj. settings -> libraries), IntelliJ gives me an error when I try importing it. What am I missing?


text:
Q: Test an implementation of an abstract service in an android test project I have an abstract service that is implemented several times in my app.
(https://developer.android.com/reference/android/app/Service.html)
Is it possible to have a custom implementation of this service under the android test project and test this custom implementation ?


text:
Q: How to set Uart Baudrate to 345600 for Raspberry Pi 4 I would like to set the Baudrate of my ttyUSB0 device to 345600 Baud. but looks like its not a standard baud rate (230400 or 460800 is supported). Is there any way to set the baud rate to 345600 in the linux shell?
I did it with my c program but there I loose packages and would like to try it with minicom or any standard shell program.
thanks for your help!


text:
Q: How to get sum of custom attributes in jquery I am trying to retrieve the value of the custom attribute "mrbvalue". The html is what sharepoint gives me after I enter the data in the database. So I can't add my own classes or change anything. The console.log() is just me seeing if it works. The code works but when I click the radio button's "No" & "Sometimes" the console prints the "Yes" value.

                 P1

<input type="radio" name="td_p1"  mrbvalue="Yes"> Yes

<input type="radio" name="td_p1"  mrbvalue="No"> No

<input type="radio" name="td_p1"  mrbvalue="Sometimes"> Sometimes

$(".mrb-item").click(function() {
    var checkboxes = $(".mrb-item");

    for(var i =0; i < checkboxes.length; i++){

    if($('input').attr("mrbvalue")  == "Yes" ){
        console.log("yes");
        }
    }
    if($('input').attr("mrbvalue")  == "No" ){
        console.log("No");
        }
    }
    if($('input').attr("mrbvalue")  == "Sometimes" ){
        console.log("Sometimes");
        }
    }
})

A: Modify the code as below.

 P1

<input type="radio" name="td_p1"  mrbvalue="Yes"/> Yes

<input type="radio" name="td_p1"  mrbvalue="No"/> No

<input type="radio" name="td_p1"  mrbvalue="Sometimes"/> Sometimes

A: The problem is with your if statement, every time you loop, you always get the first input. You need to use eq.
    // This is wrong
    if($('input').attr("mrbvalue")  == "No" ){
        console.log("No");
    }

    // This is right
    if($('input').eq(i).attr("mrbvalue")  == "No" ){
        console.log("No");
    }

A: *

*jQuery: $('input[name="td_p1"]:checked').attr('mrbvalue')

*pure javascript: document.querySelector('input[name="td_p1"]:checked').getAttribute('mrbvalue')


text:
Q: How to set Jenkins installation file location? I want to set Jenkins file location to E:\Programs\Jenkins kind of location
I'm using the command java -jar jenkins.war
How do i specify the file location with that commad

A: I think you mean jenkins home. Just specify JENKINS_HOME environment variable before launching jenkins. If you are using Windows go to user accounts configuration and change your environment variables. Add variable JENKINS_HOME with value E:\Programs\Jenkins.


text:
Q: Automatically paste the selected text into a file Want to create a soft, which will copy the selected text to a desired file on press a certain shortcut !!
While trying to save my SQL commands, i developed the need for something like this


text:
Q: How to parse a string or value of something in xslt I am new to xslt trying to capture and evaluate the IP address of user through authzrule using xslt. I know the IP can be evaluated by azn_cred_ip_address
<xsl:choose>
<xsl:when test=" azn_cred_ip_address = '100.200.300.400'">!TRUE!</xsl:when>
<xsl:otherwise>!FALSE!</xsl:otherwise>
</xsl:choose>

However the IP is not always the same, but I want to check to see if the first 3 digits are 100.
How can I modify the above xslt to see if the IP starts with 100 or not?

A: You could use substring-before here (as this will also work if the first number is less than 3 digits too.
<xsl:when test="substring-before(azn_cred_ip_address, '.') = '100'">!TRUE!</xsl:when>

A: probably the most direct translation of the test would be
<xsl:when test="starts-with(azn_cred_ip_address,'100.')">


text:
Q: How to add an image to the hyperlink in html? I have tried the following code
Visit this for tutorials

When I executed this I was getting an image first and then the link but I am not getting that image included in the link.
I want the answer using both HTML tags and CSS.

A: You can use the HTML code  Insert the image link in "Picture URL" and the link you want to take the viewer to in "website URL".


text:
Q: How pkg is choosing its repos (FreeBSD 10) I'm using pfSense, which uses a customised base of FreeBSD 10. pkg -vv shows the following relevant definitions:
PKG_DBDIR = "/var/db/pkg";
PKG_CACHEDIR = "/var/cache/pkg";
PORTSDIR = "/usr/ports";
REPOS_DIR [
    "/etc/pkg/",
    "/usr/local/etc/pkg/repos/",
]
Repositories:
    pfSense-core: {
      url             : "pkg+https://pkg.pfsense.org/pfSense_v2_3_2_amd64-core",
      enabled         : yes,
      priority        : 0,
      mirror_type     : "SRV"
    }
    pfSense: {
      url             : "pkg+https://pkg.pfsense.org/pfSense_v2_3_2_amd64-pfSense_v2_3_2",
      enabled         : yes,
      priority        : 0,
      mirror_type     : "SRV"
    }

Looking at the two directories named in REPOS_DIR:

*

*/etc/pkg contains what looks like a default FreeBSD.conf (enabled=yes).

*/usr/local/etc/pkg/repos contains a different FreeBSD.conf (enabled=no) and also a pfsense.conf that contains the two repo definitions reported by pkg -vv.

*There is also /usr/local/share/pfSense/pkg/repos which contains the same FreeBSD.conf and pfsense.conf as /usr/local/etc/pkg/repos (the latter under a different filename though: pfSense-repo.conf), and also a link to further development repos in a separate file pfSense-repo-devel.conf.

I'm trying to work out the logic by which pkg chooses which of these overrides which others, especially since when a priority is given, in each case it's the same (=0).
Does a /usr/local/etc/pkg/*.conf file automatically override a similarly-named file at /etc/pkg/*.conf, if both are present? If not, what's going on and how is pkg choosing which repos to pay attention to?

A: The behaviour is actually all documented in the manual (q.v.).  REPOS_DIR is taken from pkg.conf and its directories are processed in the order given.  Files in each directory are processed in alphabetical order.  There's no notion of comparing filenames.  Rather, a file that is processed later overrides anything earlier that it conflicts with.
Further reading

*

*pkg.conf.  §5.  FreeBSD Manual.  2015.


text:
Q: jQuery datepicker allow specific dates I have a basic problem and I think I almost found the solution but I can't tell what I did wrong.
I have a multiple jQuery datepicker and I don't want the user to be able to select non working days.
Here is what I've done so far :
function enableAllTheseDays(date) {
    var sdate = moment(date).format('YYYY-MM-DD');

    if ($.inArray(sdate, enabledDates) !== -1) {
        return [true];
    }
    console.log(date);
    return [false];
}

$('#newOrderDates').datepicker({
    todayHighlight: true,
    format: 'yy-mm-dd',
    multidate: true,
    startDate : new Date(),
    beforeShowDay: enableAllTheseDays
});

So the datepicker will be able to select multiple dates and I don't want the user to be able to select past days and non working days.
The array enabledDates looks like this :

What I don't understant is the console displays the non working days, but for some reason, the user is still able to select them with the datepicker ! I guess the error is coming from the return[true] and return [false] but I didn't find any relevant documentation to fix this so far.

Thanks for your help.
Louis

A: Here is the example of bootstrap datepicker, you can restrict or enabled/disabled dates based on the requirement.

var enabledDates = new Array('2020-01-12', '2020-01-16', '2020-01-18', '2020-01-30', '2020-02-05', '2020-02-10');

$(document).ready(function() {
  $("#newOrderDates").datepicker({
    todayHighlight: true,
    format: 'yyyy-mm-dd',
    multidate: true,
    startDate: new Date(),
    beforeShowDay: function(date) {
      var sdate = moment(date).format('YYYY-MM-DD');
      if ($.inArray(sdate, enabledDates) !== -1) {
        return {
          enabled: true
        }
      } else {
        return {
          enabled: false
        }
      }
    }
  });
});
h1 {
  color: green;
}

.ui-datepicker {
  width: 12em;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.0/css/datepicker.css" rel="stylesheet" type="text/css" />

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.0/js/bootstrap-datepicker.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.js"></script>

<input type="text" id="newOrderDates">

A: Here is the example of jquery datepicker, you can restrict or enabled/disabled dates based on requirement.

var enabledDates = new Array('2020-01-12', '2020-01-16', '2020-01-18', '2020-01-30', '2020-02-05', '2020-02-10');

$(document).ready(function() {
  $(function() {
    $("#newOrderDates").datepicker({
      todayHighlight: true,
      dateFormat: 'yy-mm-dd',
      multidate: true,
      startDate: new Date(),
      beforeShowDay: enableAllTheseDays
    });
  });

  function enableAllTheseDays(date) {
    var sdate = moment(date).format('YYYY-MM-DD');

    if ($.inArray(sdate, enabledDates) !== -1) {
      return [true];
    }

    return [false];
  }
})
h1 {
  color: green;
}

.ui-datepicker {
  width: 12em;
}
<link href='https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/ui-lightness/jquery-ui.css' rel='stylesheet'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js">
</script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.js"></script>

<input type="text" id="newOrderDates">


text:
Q: How can I find all nested Active Directory groups within a group in Powershell? I am wanting to see all nested groups inside a particular AD group. Doing this one level down is easy, but what I am needing is to see all nested groups. This means say we have an AD group  and it has two groups inside of it that are nested  and  Im wanting to see all of the nested groups inside of these and then the nested groups inside of those nested groups. So in the end if I input  it tells me every group that is nested and subnested inside of ,GroupA>.
Here is my code so far.
function get-nestedgroups{
    [cmdletbinding()]
    param(
        [Parameter(Mandatory = $true)]
        [string]$group
    )
    Begin{
        $ADGrp = Get-ADGroup -identity $group
        $NestedGroups = Get-ADGroup -LDAPFilter "(&(objectCategory=group)(memberof=$($ADGrp.DistinguishedName)))"
    }
    Process{
        if($NestedGroups.name -ne $null){
            return $NestedGroups.SamAccountName
        }
    }
    END{}
}

My thought is to create another function that takes in a group and runs this function on that group. then it takes the output groups from that function and does the same thing over and over until all of the nested groups are found but everytime I try and map it out I cannot figure out a solution to handle all of the foreach loops in a way that it will work with a while loop.


text:
Q: Hosting WCF Service using unmanaged DLLs I have a managed DLL that internally references a couple of unmanaged DLLs.  This managed DLL is added as a reference to my WCF service project.  However, the unmanaged DLLs have to be manually copied to the build output path of my project.  They cannot be referenced within Visual Studio.
If I try to run my service DLL within the WCF Service Host in Visual Studio, latter crashes without any exceptions  and automatically restarts.  Sampe applies if I try to host service DLL in IIS.  I was able to catch one of the WERReportMetadata crash logs when trying to host in IIS and the ProblemSignatures says:
<ProblemSignatures>
    <EventType>CLR20r3</EventType>
    <Parameter0>webdev.webserver40.exe</Parameter0>
    <Parameter1>10.0.0.0</Parameter1>
    <Parameter2>4d5f345a</Parameter2>
    <Parameter3>GTAPIASM</Parameter3>
    <Parameter4>2.0.5.0</Parameter4>
    <Parameter5>4e9254a5</Parameter5>
    <Parameter6>166</Parameter6>
    <Parameter7>23</Parameter7>
    <Parameter8>System.AccessViolationException</Parameter8>
  </ProblemSignatures>

What does this mean and what can I do about it?   Any reference material on WCF hosting with unmanaged DLLs will be useful too.
Edit 1:  Copying the unmanaged DLLs to %systemroot%\syswow64 allows me to host my service using Visual Studio WCF Service Host. I got the tip from here.  However, this does not stop WebDev.WebDServer40.exe from crashing.
Edit 2  This is .NET Runtime error captured from Event Viewer:

Application: WebDev.WebServer40.exe Framework Version: v4.0.30319
  Description: The process was terminated due to an unhandled exception.
  Exception Info: System.TypeInitializationException Stack: at
  System.RuntimeMethodHandle._InvokeConstructor(System.IRuntimeMethodInfo,
  System.Object[], System.SignatureStruct ByRef, System.RuntimeType) at
  System.RuntimeMethodHandle.InvokeConstructor(System.IRuntimeMethodInfo,
  System.Object[], System.SignatureStruct, System.RuntimeType) at
  System.Reflection.RuntimeConstructorInfo.Invoke(System.Reflection.BindingFlags,
  System.Reflection.Binder, System.Object[],
  System.Globalization.CultureInfo) at
  System.ServiceModel.Description.ServiceDescription.CreateImplementation(System.Type)
  at
  System.ServiceModel.Description.ServiceDescription.SetupSingleton(System.ServiceModel.Description.ServiceDescription,
  System.Object, Boolean) at
  System.ServiceModel.Description.ServiceDescription.GetService(System.Type)
  at
  System.ServiceModel.ServiceHost.CreateDescription(System.Collections.Generic.IDictionary`2
  ByRef) at
  System.ServiceModel.ServiceHostBase.InitializeDescription(System.ServiceModel.UriSchemeKeyedCollection)
  at System.ServiceModel.ServiceHost.InitializeDescription(System.Type,
  System.ServiceModel.UriSchemeKeyedCollection) at
  System.ServiceModel.ServiceHost..ctor(System.Type, System.Uri[]) at
  System.ServiceModel.Activation.ServiceHostFactory.CreateServiceHost(System.Type,
  System.Uri[]) at
  System.ServiceModel.Activation.ServiceHostFactory.CreateServiceHost(System.String,
  System.Uri[]) at
  System.ServiceModel.ServiceHostingEnvironment+HostingManager.CreateService(System.String)
  at
  System.ServiceModel.ServiceHostingEnvironment+HostingManager.ActivateService(System.String)
  at
  System.ServiceModel.ServiceHostingEnvironment+HostingManager.EnsureServiceAvailable(System.String)
  at
  System.ServiceModel.ServiceHostingEnvironment.EnsureServiceAvailableFast(System.String)
  at
  System.ServiceModel.Activation.HostedHttpRequestAsyncResult.HandleRequest()
  at
  System.ServiceModel.Activation.HostedHttpRequestAsyncResult.BeginRequest()
  at
  System.ServiceModel.Activation.HostedHttpRequestAsyncResult.OnBeginRequest(System.Object)
  at
  System.Runtime.IOThreadScheduler+ScheduledOverlapped.IOCallback(UInt32,
  UInt32, System.Threading.NativeOverlapped*) at
  System.Runtime.Fx+IOCompletionThunk.UnhandledExceptionFrame(UInt32,
  UInt32, System.Threading.NativeOverlapped*) at
  System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32,
  UInt32, System.Threading.NativeOverlapped*)

Edit 2:
Turns out I have to run Visual Studio as admin at all times.  This eliminates the previous error.
Thanks.

A: I needed to add unmanaged DLLs to %systemroot%\syswow64.  Did this and can run my service in WCF Service Host in Visual Studio as well as ASP Development server.