Compare each cell for equality in two data frames of equal size in R

Question: I have 2 dataframe, say A and B, of equal size (rows and columns). I would like to output a dataframe, say C, of same size with all the values as 0 or 1.
C[i,j] = 0, if A[i,j] != B[i,j]
C[i,j] = 1, if A[i,j] == B[i,j]

I do not want to use loops or ifelse statement as I have successfully done that but it takes very long time. If there is any other straight forward way to do the same, it would be really helpful. Thanks
Comment: Is there a reason why you want the result C as `data.frame` but not e. g. as `matrix`?
Comment: When somebody post an answer, deleting a question is not appropriate
Answer: Simply compare the two data.frames to get a matrix with the same size and a logical in the cells indicating the comparison result:
A <- mtcars
B <- mtcars

A == B

Result (first rows shown only):
                     mpg  cyl disp   hp drat   wt qsec   vs   am gear carb
Mazda RX4           TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
Mazda RX4 Wag       TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
Datsun 710          TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
Hornet 4 Drive      TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE

To get a data.frame from the comparison use:
C <- as.data.frame(A == B)

You can use the fact that TRUE == 1 and FALSE == 0 in R (as the OP asked for) to coerce the result into an integer explicitly:
as.data.frame(lapply(as.data.frame(A == B), as.integer))

Multiplying by 1 (as proposed in another answer) is prettier and probably more efficient (avoids :
as.data.frame(1 * (A == B))

Edit++ [Benchmark added; Benchmark improved for consistency]:
A benchmark between the different answers based on data.frames with 10 Mio. rows (about 260 MB)...
library(microbenchmark)   # install.packages("microbenchmark")
library(data.table)

A <- data.frame(col1 = 1:1E7,
                col2 = rep(c("a string", "another string"), 1E7/2),
                col3 = 1:1E7,
                col4 = 1:1E7,
                col5 = rep(LETTERS[1:10],1E6),
                stringsAsFactors = FALSE)
B <- A
B[1,1]=100  # change one cell to create a copy of the data.frame

microbenchmark(DF.equals       = as.data.frame(A == B),
               DF.mult         = as.data.frame(1 * (A == B)),
               DF.map          = as.data.frame(Map(`==`, A, B)),
               matrix.equals   = A == B,
               matrix.mult     = 1 * (A == B),
               matrix.map      = do.call(cbind, Map(`==`, A, B)),  # causes a warning: duplicated levels in factors are deprecated
               list.map        = Map(`==`, A, B),                  # fast cause it does not construct a matrix but only vectors
               times = 100)

shows the Map() function as the clear winner (on my system) being twice to four times faster as other variants and that the result as matrix is much faster than a data.frame:
Unit: milliseconds
          expr      min       lq     mean   median       uq      max neval    cld
     DF.equals 627.2541 630.7565 654.0266 635.1831 678.8903 686.0753   100     e
      DF.mult  743.8531 751.7933 781.1876 796.2282 799.1881 848.2455   100      f
        DF.map 169.6967 170.5842 176.5944 171.5072 173.5665 223.3354   100 a
 matrix.equals 294.2570 297.5330 311.8095 299.8093 345.0827 351.9193   100   c
  matrix.mult  402.6166 406.5279 422.9322 408.3012 453.4484 602.2139   100    d
    matrix.map 206.2596 208.4230 217.8891 209.8968 211.4139 266.1867   100  b
      list.map 169.1922 170.5403 175.7539 171.4602 173.3891 224.7062   100 a

BTW:
What I really like is how you can do some statistics now, e. g. count the number of mismatches per column (or row if you use rowSums instead):
colSums(C != TRUE)

or
colSums(A != B)

to get a result usable for automatic checking of preconditions (e. g. no mismatches allowed):
 mpg  cyl disp   hp drat   wt qsec   vs   am gear carb
   0    0    0    0    0    0    0    0    0    0    0

Comment: Your benchmark doesn't make much sense. Why the `Map` answer is the only one without a `data.frame` wrapper? Also you mainly comparing performance between different `data.frame` wrappers which has nothing to do with the question IIRC. Also, what's the point in converting this into a `data.frame` anyway? How is a boolean `data.frame` any better than a boolean `matrix`? You are basically have two methods here ```do.call(cbind, Map(`==`, A, B))``` vs simply `A == B`
Comment: @DavidArenburg: Fair points, I will reconsider my benchmarks. Regarding `data.frame`: The OP requested it "I would like to output a dataframe, say C, of same size with all the values as 0 or 1", but in fact we should ask him/her why not using a matrix.
Answer: Try:
C <- data.frame(1 * (A == B))

The 1* is for turning TRUE/FALSE to 0/1 as required.
Comment: It might be helpful to comment on why you included `1*` instead of just `A == B`
Answer: We can use Map to compare the corresponding columns of two data.frame 'A' and 'B'
Map(`==`, A, B)

The advantage is that we get a list of logical vectors instead of a matrix in the workspace.  If the datasets are really big, it could be memory limiting to have matrix output
Comment: Great idea, `Map`  uses `mapply` internally and therefor avoids the construction of full matrix in memory. This allows doing statistics on a "per column base" which does not use overly much memory but only one logical vector per column at a time. E. g.: Count the number of mismatches per column via `Map( function(a, b)  sum(a != b), A, B)`
Comment: This answer is the clear winner regarding performance (see the benchmark in [my answer](http://stackoverflow.com/a/41790501/4468078)).
Answer: This example produces a T/F matrix which can be effectively treated as 0/1 in R
x = matrix(1:9, nrow = 3)
y = matrix(9:1, nrow = 3)
x == y

Since there were a couple of other suggestions in the answers I thought I'd test which was the quickest since that was a requirement of the question.
Here equals refers to the A == B solution and map_xy is the Map solution.
microbenchmark(equals(x,y), map_xy(x,y), times = 1000)
Unit: nanoseconds
         expr   min    lq      mean  median    uq   max neval
 equals(x, y)   360   399   468.491   459.0   508  3473  1000
 map_xy(x, y) 10909 12114 13506.830 13132.5 14158 77743  1000

It looks like equals is a much faster option - but as the Map answer indicates it might perform better with larger datasets. So I tested again with reasonably sized data:
x_big = matrix(1:900000, nrow = 3)
> y_big = matrix(900000:1, nrow = 3)
> microbenchmark(equals(x_big,y_big), map_xy(x_big,y_big), times = 100)
Unit: milliseconds
                 expr        min          lq        mean      median          uq
 equals(x_big, y_big)   1.579069    2.118332    2.515257    2.225747    2.375377
 map_xy(x_big, y_big) 846.172497 1040.383027 1165.354138 1147.239396 1321.166762
        max neval
   21.48414   100
 1489.81884   100

Which suggests that equals is still the faster option.
EDIT
In response to comments here is the code for each function. I have edited these slightly to convert the output to a data.frame (although I personally think this step is unnecessary)
equals = function(x,y){
  as.data.frame(x == y)
}

map_xy = function(x,y){
  Map('==', x, y) %>%
    unlist(.) %>%
    matrix(., nrow = 3) %>%
    as.data.frame(.)
}

This changes the benchmark results but not the outcome:
For small matrices:
Unit: microseconds
         expr     min       lq      mean   median       uq      max neval
 equals(x, y)  18.090  20.3205  24.31075  22.0205  23.7285  781.048  1000
 map_xy(x, y) 172.699 186.0775 209.39585 193.3645 204.0220 2646.419  1000

For large matrices:
Unit: milliseconds
                 expr       min        lq     mean    median        uq      max
 equals(x_big, y_big)  533.3274  646.0605  744.063  705.4923  871.3479 1067.411
 map_xy(x_big, y_big) 1637.2882 1820.8714 1938.458 1921.2563 2041.0533 2564.669
 neval
   100
   100

If you want the functions I originally used - just take out the code for converting into a data.frame.
Comment: +1 for your efforts to do a benchmark. Can you please add the code of the `equals` and `map_xy` functions for a reproducibility`? Please note that the OP wanted the comparison of two `data.frame`s and not two matrices so the results may be completely different then (esp. when some columns are string columns). THX!
Comment: Have updated. Also benchmarking is super easy with the library micro benchmarking! So not sure if I deserve the effort points haha.


Python Errors: Correct is not defined. Trivia Game

Question: I'm asked to produce a trivia game that has 10 questions.  Each question should be picked at random.  Every four questions Python should ask if the user wants to play again.  If the user says "yes" then it continues again, if they say "no" it ends.  If the game reaches the point that there are no more questions it should apologize and end the program.
I have two issues. Right now it doesn't seem to be using my playAgain() function.  It also is giving me this error, "NameError: global name 'rounds' is not defined" this also comes up for the correct variable.  I'm not sure how I can define these outside the mainObject() without modifying the data that they obtain in mainObject().
What should I do?
import random, sys

question1 = "In which US state would you find the zip code 12345?"
question2 = "What never works at night and requires a gnomon to tell the time?"
question3 = "What color is a polar bear's skin?"
question4 = "What is Indiana Jones' first name?"
question5 = "Which is bigger, the state of Florida or England?"
question6 = "How many white stripes are there on the American flag?"
question7 = "How many daily tides are there?"
question8 = "Which country has the longest coastline?"
question9 = "How many of the gifts in the song 'The Twelve Days of Christmas' do not     involve birds?"
question10 = "It occurs once in a minute Twice in a week and once in a year what is it?"

answer1 = "New York"
answer2 = "Sundial"
answer3 = "Black"
answer4 = "Henry"
answer5 = "Florida"
answer6 = "Six"
answer7 = "Two"
answer8 = "Canada"
answer9 = "Six"
answer10 = "E"

Questions = [question1, question2, question3,
      question4, question5, question6,
      question7, question8, question9, question10]

Answers = [answer1, answer2, answer3, answer4,
   answer5, answer6, answer7, answer8, answer9,
   answer10]

print ("Welcome to the Dynamic Duo's WJ Trivia Game!!")
print ("Press \"enter\" to play.")

input()

last = len(Questions)-1
#rounds = 0
#correct = 0
playagain = " "

def playAgain():
    if (rounds == 4 or rounds == 8):
            print("Do you want to play another round? (Yes or No)")
            playAgain = input()
            accept = "Yes"
            if PlayAgain.lower() == accept.lower():
                    mainObject()
            else:
                    sys.quit()

def mainObject():
    correct = 0
    last = len(Questions)-1
    rounds = 0
    playagain = "yes"
    while (last>=0):  #This continually checks to make sure that there is a new question
            randomQuestion = random.randint(0, last)
            rounds += 1

            print ("Round " + str(rounds))
            print (Questions[randomQuestion])
            userAnswer = input()
            questionAsked = (Questions[randomQuestion])
            answerRequired = (Answers[randomQuestion])
            isitcorrect = False
            if answerRequired.lower() == userAnswer.lower():
                    isitcorrect = True
            if isitcorrect == True:
                    print("Good job! You got the correct answer of " + Answers[randomQuestion])
                    correct += 1
                    print("You have " + str(correct) + " points.")
            else: print("Too bad, you got it wrong.  The correct answer is " + answerRequired)
            Questions.remove(questionAsked)
            Answers.remove(answerRequired)
            last = len(Questions)-1
            playAgain()

mainObject()

print("I'm sorry, there are no more trivia questions.  Your total score is " +   str(correct))
print("Thanks for playing!")

Comment: Having a function called "mainObject" is a little confusing. From the name it sounds like it should be an object--that is, an instance of a class. And if you _did_ have a class, you'd have a place to put "member variables" that could be shared by all of the methods, which might be a nice design here.
Answer: You need to uncomment
rounds = 0  # at the top

and insert
global rounds

in the functions. You are incrementing rounds (local) in main, but rounds in playAgain is undefined.
There are other ways to solve the problem. But this is likely the quickest, and easiest to understand.
Comment: AHHH  That makes perfect sense!!  Thank you!!
Answer: The variable rounds is defined in the mainobject() function, and is local to that function. It is not accessible from outside of that function.
One simple fix would be to pass rounds to the playagain() function
thus
def playagain(rounds):
...

def mainobject():
....
playagain(rounds)


Look for equality in selected listbox items

Question: Is it possible to compare two listboxes and their respected selected values?
Basically I want to check if listbox A's selected values == listbox B's selected values.
I tried this code, but it didn't work:
if(listA.SelectedItems == listB.SelectedItems)
{
    Console.WriteLine("equal");
}
else
{
    Console.WriteLine("not equal");
}

Comment: What is the object inside listbox? string or some other class? Also, Is the sequence important?
Comment: Both listboxes contain the same data. For example, listbox A contains values `A, B, C, D, E` and likewise for listbox B...and in that order for both boxes. So, if A, B and C are selected in box A and likewise for B, the statement would return true. If box A selected was A and C, while box B was A, D, it would return false.
Comment: possible duplicate of [Does .NET have a way to check if List a contains all items in List b?](http://stackoverflow.com/questions/1520642/does-net-have-a-way-to-check-if-list-a-contains-all-items-in-list-b)
Answer: You can sort both the SelectedItems collection and then use SequenceEqual.
var orderedA = listA.SelectedItems.Cast<object>().OrderBy(x=> x);
var orderedB = listB.SelectedItems.Cast<object>().OrderBy(x=> x);
if(orderedA.SequenceEqual(orderedB))
{
    Console.WriteLine("equal");
}
else
{
    Console.WriteLine("not equal");
}

Comment: Simple and easy to understand. Thanks!
Answer: The simplest way would be to check if any of the second list contains the items from the first
var listAItems = listA.SelectedItems
var listBItems = listB.SelectedItems
if(listAItems.Count == listBItems.Count &&
   listAItems.Any(i => !listBItems.Contains(i)))
    //Something missing
else
    //All there

Note: this works for all IEnumerables
I'm not sure if this answer would be more efficient for your usage than the one in the duplicate since this will return true as soon as it finds an entry that doesn't exist - The duplicates answer has the possibility to return the items that are missing
var missing = listA.SelectedItems.Except(listB.SelectedItems);
if(missing.Any())
    //something missing use the missing variable to see what

Comment: Your answer checks whether `listA.SelectedItems` contains any items which is not there in `listB`. but OP asks for equals. Your answer will return true when listA contains [`A`, `B`] and listB [`A`, `B`, `C`]. I believe op needs to return false in this case
Comment: @SriramSakthivel - Thanks I've updated to cater for that, although I admit this still assumes that the list has no duplicates
Answer: You are using two properties with a different meaning for your comparison. SelectedItem is an object (could be anything depending on how you have filled the combo, ValueMember is just the name of a property to use as the actual value for the items in the ListBox.
However the two classes (ListBox and ComboBox) share the same pattern for storing their list items, so supposing that both are populated using a list of strings then your code could be
dynamic curComboItem = ComboBox1.SelectedItem.ToString();
for (i = 0; i <= ListBox1.Items.Count - 1; i++) {
    if (curComboItem == ListBox1.Items(i).ToString()) {
        Interaction.MsgBox("DATA FOUND");
        break; // TODO: might not be correct. Was : Exit For
    }
}


div going beneath instead of to the side

Question: I am trying to make 4 columns side by side, but the middle two are slightly shorter and have a single div underneath both of them.  See image here: http://postimg.org/image/rw67rh5zf/
I'm sure it's something simple I'm screwing up but I can't tell what it is.
All the other posts on here similar to this are resolved by either correcting the float or the width but the inner divs have enough room to fit side by side inside and they're all float left.
HTML:

one

two

three

four

five

six

seven

eight

nine

            Benefits and Cost of Membership

ten

eleven

twelve

Answer: You will need to float the midCols to the left and set your main div width to a wider value so it doesn't force the floating divs to wrap.
Example: http://jsfiddle.net/j1voh4kf/

Here's a screenshot diffing your code with my changes:
Comment: Adam - thanks, I knew it would be something stupidly simple I missed.  I had the bottomDiv set to 956 which is big enough but I must have changed it on accident while resizing things.  Staring at the code so long made it hard to see my mistake.
Answer: I would suggest separating your styles from your markup to make it a little more clear to see what is going on.
You can tweak the widths as needed from here:

#bottomDiv > div {
  float: left;
}
#midCols > div {
  float: left;
}
#divBenefits {
  background-color: #941a41;
  color: white;
  clear: both;
}

one

two

three

four

five

six

seven

eight

nine

      Benefits and Cost of Membership

ten

eleven

twelve

Comment: i do, I just combined it to keep it all together so you wouldn't have to look at two different code snippets to determine what was going on.
Comment: Talmid - I do, I combined it to make it so I could ask the question with 1 code snippet.  Thought it would make it easier to read.


Repair Drywall after electrical work

Question: We've had some electrical work done which has resulted in a number of holes in drywall about 8cm in length by 2cm in height similar to below:

I was intending on making small cuts of plasterboard but since the cable doesn't go through the stud this won't be possible. What's my best option for repairing these holes?
Comment: It's called "laziness". They should have drilled a hole through the stud. But that would have required a much larger hole in the drywall. A notch would be fine, but oops, extra work. Plus, if it is with a notch (instead of a hole set a couple of inches back in the stud) then there should be a metal plate to prevent accidentally putting a nail into the wire when hanging a picture.
Comment: Where do you live?  This wouldn't be legal in the US.  But anywhere - how does the electrician plan on this being finished?  You can't just mud over a piece of wire and call it a day...
Comment: Is the stud notched to allow the wire through?
Comment: No, it doesn't appear to be. Does this fail building regulations? We've just had this done (I haven't paid yet)
Comment: This is in the UK
Comment: Look at [this question](https://diy.stackexchange.com/q/101066/43874) for how this should be handled.  Even if they were too lazy to use nail protectors, they could have drilled holes through the studs with the same size cuts they made in the drywall.
Comment: If it is an "old" drywall, then the studs may be too thin even if the hole is drilled in the middle of the stud....
Comment: Is this mains electrical power, or is it low voltage such as ethernet, doorbell, thermostat, burglar alarm, fire alarm etc.?
Comment: Mains voltage, it's for a light switch. @solarmike - what would be the options if the studs we're too thin?
Comment: A steel tube...
Comment: 'Electrician' is claiming that because because I was intending on putting cupboards over this wall that it covers more than the 50mm and still meets code. Building regs in UK state "A cable concealed in a wall or partition at a depth of less than 50 mm"  and then lists the requirements, none of which are met. Putting a cupboard over a wall does not extend the width of the wall!
Comment: @Fraser - Your workman has not used the correct cable either. If you haven't paid him yet - refuse to do so. Employ a *proper* electrician to do your wiring properly. The proper electrician may also want details of the workman who did this so that he can report it.
Answer: That's not cool. Don't know your codes in the UK but that certainly is a fail in Canada and the US. Hanging a picture with a thumb tac can potentially puncture that. Actually no it's not to code, it can't be unless there is literally no code in place. (highly unlikely in the UK it might be code in a third world country)
You need to have it fixed before you conceal it. If this is the only spot that is like this, it could be a apprentice or just a moment of extreme laziness on the part of the worker. Ask the person to fix it to code by at least notching the stud if it's not load bearing and adding a striker plate.
I don't know why guys do stupid things like this. If you have to do a patch it really doesn't matter if it's 12x12" or 6x1" in just make the whole big enough to do your job.
Once the repairs done properly patching the holes will be a lot easier. If you ever did have to patch a hole similar to this it's often easier to just make it bigger anyway so you can add blocking into the back.
Comment: Also note that "repair" in this case is to pull out the whole wire and do it right.  They can't just cut the wire, drill a hole, run the wire through and then splice it.  Splices are not allowed in walls when running new wires (again, unless the UK is some wild free-for-all with electrical codes).
Comment: @JPhi1618 agreed I mentioned notching the studs but if that's not practical then pull it all out and rerun it. ;-)

Repair Drywall after electrical work


Autofac with service, repository and web api

Question: Autofac registers Service with IService, and Service is using repository for logic
<code>        builder.Register(c => new Service(IServiceRepository)).As<IService>()
            .InstancePerLifetimeScope();
</code>
When I register repository like this
<code>    builder.Register(c => new Repository(DbContext)).As<IRepository>()
        .InstancePerRequest();
</code>
Autofac doesn't register it, why?
Service is using IServiceRepository in constructor and Repository is using DbContext in his constructor, Autofac registers Service well with IService, but not with Repository
Answer: If anyone is new to autofac solution is create modules for service and repository in separate files with RegisterType and use RegisterAssemblyModules to connect/register them in Startup


How to get a menu when fired a long click in ImageView

Question: I have an adapter class in android to adapt images. I want to add an onLongClickListener() in it to inflate menu. But now it is not working i can't find the problem here please help me to fix this
adapter class
public class FullScreenImageAdapter extends PagerAdapter {

    private Activity _activity;
    private ArrayList<String> _imagePaths;
    private LayoutInflater inflater;

    // constructor
    public FullScreenImageAdapter(Activity activity,
            ArrayList<String> imagePaths) {
        this._activity = activity;
        this._imagePaths = imagePaths;
    }

    @Override
    public int getCount() {
        return this._imagePaths.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == ((RelativeLayout) object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        TouchImageView imgDisplay;
        Button btnClose;

        inflater = (LayoutInflater) _activity
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View viewLayout = inflater.inflate(R.layout.layout_fullscreen_image, container,
                false);

        imgDisplay = (TouchImageView) viewLayout.findViewById(R.id.imgDisplay);
        btnClose = (Button) viewLayout.findViewById(R.id.btnClose);

        imgDisplay.setOnLongClickListener(new View.OnLongClickListener() {

            @Override
            public boolean onLongClick(View v) {
                ((Activity)_activity).openContextMenu(v);
                return true;
            }
        });
        ImageLoader2 imageLoader = new ImageLoader2(_activity);
        imageLoader.DisplayImage(_imagePaths.get(position), imgDisplay);

        // close button click event
        btnClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                _activity.finish();
            }
        });

        ((ViewPager) container).addView(viewLayout);

        return viewLayout;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        ((ViewPager) container).removeView((RelativeLayout) object);

    }

    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
        _activity.onCreateContextMenu(menu, v, menuInfo);
        //menu.setHeaderTitle(getString(R.string.menu_context_title));
        MenuInflater inflater = _activity.getMenuInflater();
        inflater.inflate(R.menu.grid_view, menu);
    }

    public boolean onContextItemSelected(MenuItem item) {

        switch (item.getItemId()) {
        case R.id.about_id:
            // do something useful
            return true;
        default:
            return _activity.onContextItemSelected(item);
        }

}
}

Comment: Firstly, in `Java` fields are prefixed with an 'm'. E.g, mWidth, mAverage, etc.
Answer: You have the right idea. A ContextMenu is a floating menu that appears when the user performs a long-click on an element or any View. I decided to take the root View, for my convenience. You can adjust the code to suit your needs.
View view;
view = this.getWindow().getDecorView().getRootView();

You must register each View that you want to have associated with the ContextMenu.
registerForContextMenu(v);  // I think you missed this

You then need to override the onCreateContextMenu() to create the menu:
@Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    menu.setHeaderTitle("Context Menu");
    menu.add(0, v.getId(), 0, "Action 1");
    menu.add(0, v.getId(), 0, "Action 2");
}

And override onContextItemSelected() to preform the action when an option is selected from this menu:
@Override
public boolean onContextItemSelected(MenuItem item) {
   if(item.getTitle()=="Action 1") {
      function1(item.getItemId());// just place holders you can replace them with your functionality
    }
    else if(item.getTitle()=="Action 2") {
      function2(item.getItemId());// just place holders you can replace them with your functionality
    }
    else{
        return false;
    }
    return true;
}


ModuleNotFoundError when running Jupyternotebook in Virtual Environment

Question: I have created a virtual environment using Anaconda and installed all the packages I need based on a requirements text file. Followed by installing the ipykernel. This is the code I've used.
conda create --name venv_nlp python=3.8
conda activate venv_nlp
pip install -r requirements.txt
python -m ipykernel install --user --name=venv_nlp

Afterwards, I did entered pip list in the anaconda prompt to see the list of packages installed.
The package I needed, bertopic, is in the list.
I've opened my Jupyternotebook, changed kernel to venv_nlp.
However, when running
from bertopic import BERTopic

I do get an error:
C:\ProgramData\Anaconda3\lib\site-packages\ipykernel\ipkernel.py:287: DeprecationWarning: `should_run_async` will not call `transform_cell` automatically in the future. Please pass the result to `transformed_cell` argument and any exception that happen during thetransform in `preprocessing_exc_tuple` in IPython 7.17 and above.
  and should_run_async(code)

And when I do
!pip list

I do get a warning and the list of packages installed. Bertopic is not in it:
C:\ProgramData\Anaconda3\lib\site-packages\ipykernel\ipkernel.py:287: DeprecationWarning: `should_run_async` will not call `transform_cell` automatically in the future. Please pass the result to `transformed_cell` argument and any exception that happen during thetransform in `preprocessing_exc_tuple` in IPython 7.17 and above.
  and should_run_async(code)

My virtual environment path is C:\ProgramData\Anaconda3\envs\virtualenv_nlp
And it seems that the code is looking for the packages in C:\ProgramData\Anaconda3\lib\site-packages\ instead. Thus creating a ModuleNotFoundError.
May I know what should be done here? I am quite new with creating virtual environments.
Answer: This error could be due to several reasons:

The package bertopic should not be installed properly therefore you can re-
install this package while your venv_nlp environment is activated:

Command for re-install
 pip install bertopic

There could be some missing dependencies in your environments. You can use the following command  while your venv_nlp environment is activated:

pip install -r requirements.txt
Comment: I've done the reinstallations but I am still getting the same error
Comment: re-install seemed to fix it for me.


Does Magic 2015 For PC Change The Location Of The Multiplayer Chat Window?

Question: One of my prior grievances with Magic 2014 for PC was that the chat window was placed in an awkward location (front and center) that obstructed view of the player's deck.  Has this changed in Magic 2015 for PC?  I didn't see this mentioned at all on forums or the developers web site. Multiplayer isn't available in the demo.
Answer: Seem to be in the same place. My friend sent me the screen shot, and I don't know if you can move it.
Comment: It is in that place, and you can't move it. +1 for the screenshot.
Comment: It should be noted that you can hide it however by clicking the chat bubble again.


Download packages (different architecture) different Ubuntu version

Question: Ideally, I would like to specify architecture and Ubuntu version and download all dependencies for that package, then take them to another computer.
I know about apt-get download.... and that would work fine if the architectures and versions matched.  I do see an architecture modifier, but not a version modifier.
Any help, or pointing me toward how to accomplish this with aptitude or another package tool would be appreciated.
even if I could take one .deb to the target computer and list all concrete dependencies... that would really solve the problem.
Answer: Try using dpkg-offline. Install bzr, then:
bzr branch lp:dpkg-offline

there's a tutorial and a readme file included in there.
Assuming you want to install git on an Ubuntu 14.04 amd64 system, even if your system is e.g. 12.04 i386, you can:

download the ubuntu-14.04-desktop-amd64.iso image
Run dpkg-offline ubuntu-14.04-desktop-amd64.iso git
You'll obtain a tar.gz which you can transport to the target system, it will contain the seed package (git) and all its dependencies. It also includes a helper script to add a local repository, so you can use apt-get to install your packages.

Disclaimer: I wrote dpkg-offline.
Comment: You should consider adding this answer to http://askubuntu.com/questions/974/how-can-i-install-software-or-packages-without-internet-offline.
Answer: Maybe you want to create a local repository?
For that you should download all packages from the public repository and save them in our local Ubuntu server hard drive.
If so this is the procedure:
First install the main applications:
sudo su
apt-get update
apt-get install apt-mirror apache2

Now create a directory on your harddisk to save all packages:
sudo su
mkdir /localrepo

Now, open the file /etc/apt/mirror.list and make the changes as shown below:
sudo su
nano /etc/apt/mirror.list

############# config ##################
#
set base_path    /localrepo
#
# set mirror_path  $base_path/mirror
# set skel_path    $base_path/skel
# set var_path     $base_path/var
# set cleanscript $var_path/clean.sh
# set defaultarch  <running host architecture>
# set postmirror_script $var_path/postmirror.sh
# set run_postmirror 0
set nthreads     20
set _tilde 0
#
############# end config ##############

deb http://archive.ubuntu.com/ubuntu trusty main restricted universe multiverse
deb http://archive.ubuntu.com/ubuntu trusty-security main restricted universe multiverse
deb http://archive.ubuntu.com/ubuntu trusty-updates main restricted universe multiverse
#deb http://archive.ubuntu.com/ubuntu trusty-proposed main restricted universe multiverse
#deb http://archive.ubuntu.com/ubuntu trusty-backports main restricted universe multiverse

deb-src http://archive.ubuntu.com/ubuntu trusty main restricted universe multiverse
deb-src http://archive.ubuntu.com/ubuntu trusty-security main restricted universe multiverse
deb-src http://archive.ubuntu.com/ubuntu trusty-updates main restricted universe multiverse
#deb-src http://archive.ubuntu.com/ubuntu trusty-proposed main restricted universe multiverse
#deb-src http://archive.ubuntu.com/ubuntu trusty-backports main restricted universe multiverse

clean http://archive.ubuntu.com/ubuntu

Control + O, save file. Control + X, close nano
In the above configuration file, you can add the Ubuntu source lists depending upon the 32bit and 64bit architectures and distribution you use.
Once you saved the configuration file, populate your repository using the following command:
sudo su
apt-mirror

You need to run this command every week to get new softwares/updates.
To configure in client side. Just open your client systems file /etc/apt/sources.list and add your local repository path:
sudo su
nano /etc/apt/sources.list

##########################
deb http://10.120.1.2/ubuntu trusty universe
deb http://10.120.1.2/ubuntu trusty main restricted
deb http://10.120.1.2/ubuntu trusty-updates main restricted
##########################

Here 10.120.1.2 is your Ubuntu server IP address
Control + O, save file. Control + X, close nano
The clients need not to be connected to the Internet to download packages.
The clients will get all packages from your Ubuntu local repository.
Source: https://wiki.debian.org/HowToSetupADebianRepository


Differentiation of norm

Question: How do I differentiate the "norm" of  $(x-μ)$, with respect to $μ$, where both $x$ and $μ$ are vectors ?
How will I start and proceed ?
Thank you in advance.
Comment: The euclidean norm?
Comment: yes it is... :)
Answer: I'll assume 2D vectors to show the idea:
$$x = (x_1, x_2)^T$$
$$\mu = (\mu_1, \mu_2)^T$$
$$\|x-\mu\| = \sqrt{(x_1-\mu_1)^2 + (x_2-\mu_2)^2}$$
\begin{align}
\frac{d}{d\mu} \|x-\mu\|
&= \frac{-2(x_1-\mu_1)\frac{d\mu_1}{d\mu} - 2(x_2-\mu_2)\frac{d\mu_2}{d\mu}}{2\sqrt{(x_1-\mu_1)^2 + (x_2-\mu_2)^2}} \\
&= \frac{\mu_1-x_1}{\|x-\mu\|} \frac{d\mu_1}{d\mu} - \frac{\mu_2-x_2}{\|x-\mu\|}\frac{d\mu_2}{d\mu} \\
&= \frac{\mu_1-x_1}{\|\mu-x\|} (1,0)^T + \frac{\mu_2-x_2}{\|\mu-x\|} (0,1)^T \\
&= \frac{(\mu_1-x_1,\mu_2-x_2)^T}{\|\mu-x\|}  \\
&= \frac{\mu-x}{\|\mu-x\|}
\end{align}
The result is $\mu-x$ normalized, i.e. a unit vector in the same direction.
Comment: thank you very much, sir @GDumphart
Answer: Assuming the Euclidean norm in finite dimensional $\mathbb{R}^n$, the function you want to differentiate is this:
$$f(x_1,\dots, x_n)=\left(\sum_{i=1}^n(x_i-\mu_i)^2\right)^{1/2}$$
The derivative of this function is it's gradient, namely, the vector of it's partial derivatives. Now, for each $i$, you have
$${\partial f\over\partial x_i}(x_1,\dots,x_n)={(x_i-\mu_i)\over f(x_1,\dots,x_n)}$$
(Prove this!), and so you have the gradient.
In vector notation it looks much nicer:
$$D(||x-\mu||)={x-\mu\over||x-\mu||}$$
Comment: thank you, sir @uniquesolution
Answer: Let $\;\phi=\|x-\mu\|\;\;{\rm and}\;\;w = (\mu-x)$
Use a dot product to rewrite the norm to obtain
$$\eqalign{
\phi^2 &= \|w\|^2 \;=\; w\cdot w \\
2\phi\,d\phi &= 2\,w\cdot dw \;=\; 2\,w\cdot d\mu \\
\frac{d\phi}{d\mu} &= \frac{w}{\phi} \;=\; \frac{\mu-x}{\|x-\mu\|} \\
}$$

Differentiation of norm


How to install python-docx at Ubuntu?

Question: I have Ubuntu 19.04 without PIP.
Typically, I installed modules for Python using sudo apt-get install 'module', but it doesn't work for docx(or python-docx).
Answer: Simply download https://files.pythonhosted.org/packages/e4/83/c66a1934ed5ed8ab1dbb9931f1779079f8bca0f6bbc5793c06c4b5e7d671/python-docx-0.8.10.tar.gz (or a later version found at https://pypi.org/project/python-docx/#files)
Then un-tar it with tar -x, (or python -mtarfile -e python-docx-0.8.10.tar.gz python-docx).
Finally change directory to where you extracted it and run python setup.py install
Note that you will have to ensure that the dependencies are met first, at the time of writing they are:

behave>=1.2.3
flake8>=2.0
lxml>=3.1.0
mock>=1.0.1
pyparsing>=2.0.1
pytest>=2.5

But the latest will be in the requirements.txt file within the tar file.

How to install python-docx at Ubuntu?


'Field never assigned error" message meaning

Question: What does the error message 'field never assigned' mean and how can you assign the field. I wanted to know for the sake of learning so I can learn what it means and how to assign so I won't get this error again.

private NavigationDrawerFragment mNavigationDrawerFragment;

 @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (!mNavigationDrawerFragment.isDrawerOpen()) {
            // Only show items in the action bar relevant to this screen
            // if the drawer is not showing. Otherwise, let the drawer
            // decide what to show in the action bar.
            getMenuInflater().inflate(R.menu.main, menu);
            restoreActionBar();
            return true;

How would I assign in this one for example
Comment: Why is your code enclosed in a JavaScript code block? It won't run!
Comment: @DerGolem I couldn't find anywhere else to put it and I'm kinda new to stackoverflow so I wasn't sure where to put it. I thought that javascript was the closest thing to the java class. For future reference where can I put it so it runs?
Comment: **IT WILL NEVER RUN**. Simply select your code and press `Ctrl` + `+`
Answer: This simply means you are trying to use (say assign) a field which you never initialized. For e.g.
.. mymethod() {
    int a;
    ..
    int b = a;
    ..

Now since you never assigned/defined a, you cannot assign a to b. Hence compiler will complain as you see now.


Adding config file entries to specific sections

Question: I am trying to write a script that configures mySQL. Let's say I want to configure the port to 3333, so I want the config file to contain the lines
[mysqld]
port=3333
[client]
port=3333

At first, I was simply echoing the new lines:
echo "[mysqld]" >> /etc/mysql/my.cnf
echo "port=3333" >> /etc/mysql/my.cnf
echo "[client]" >> /etc/mysql/my.cnf
echo "port=3333" >> /etc/mysql/my.cnf

But then I realized that the config file will contain all entries several times in case I run it multiple times. Therefore I applied a check using a function:
function appendconfig {
    grep -qF "$1" "$2" || echo "$1" >> "$2"
}
cfg=/etc/mysql/my.cnf
appendconfig "[client]" $cfg
appendconfig "port=3333" $cfg
appendconfig "[mysqld]" $cfg
appendconfig "port=3333" $cfg

That function will only add the line if it does not exist yet.
Unfortunately, when configuring port=3333 in the [mysqld] section, it detects that port=3333is already present (but in [client]).
What way would I write config files like the one from mySQL in a Linux Bash script?
Basically I'm looking for something like
setconfigvalue
 <value> <file>

so I could write
setconfigvalue [mysqld] port=3333 /etc/mysql/my.cnf

I have tried the suggestions from this U&L sister site question "Editing INI like files with a script".
The accepted answer just provides solutions which are hard coded for the OP's problem. I would need to adapt them, but that's error prone.
I have tried crudini, which seems to be the right tool from its syntax. But it can't parse mySQL config files due to the includes:
crudini --get /etc/mysql/my.cnf client port
File contains parsing errors: <???>
    [line 22]: !includedir /etc/mysql/conf.d/
    [line 23]: !includedir /etc/mysql/mariadb.conf.d/

Answer: It turned out that I have version 0.7-1 of crudini installed from the official packages. There's a newer version available on Github, 0.9 at the time of writing.
I replaced the old version by the new version using wget:
wget -q https://raw.githubusercontent.com/pixelb/crudini/master/crudini -O /usr/bin/crudini

That way, the error message about parsing error disappeared:
crudini --get /etc/mysql/my.cnf mysqld port
Parameter not found: port

And I was able to set the parameters I wanted:
crudini --set /etc/mysql/my.cnf mysqld port 3333
crudini --get /etc/mysql/my.cnf mysqld port
3333


Inode number shows same in soft link

Question: When I create soft link for directory,after that I check inode number its show me same when I check in following pattern,why it show me same?
mkdir /focus
ln -s /focus /tmp/focus1
ls -lid /focus/ -> eg.1122
ls -lid /tmp/focus1/ -> 1122
Its same but I check like as follow it show differ
ls -lid /tmp/focus1
what is difference between /tmp/focus1/ and /tmp/focus1

Answer: When you include a trailing /, ls is listing the contents of the directory. When you do not, it is providing information about the symbolic link itself.
Comment: Hi William can you ex plane me using example or in simple words,I didn't  understand
Comment: `/fmp/focus1` is a symbolic link to the directory `/focus`, which is empty.  Your implementation of `ls` is simply behaving differently based on the presence of `/` at the end of the argument.  It would help if you showed the actual output you are getting.

Inode number shows same in soft link


why filewriter not working in java?

Question: I using FileReader to read and FileWriter to a file. I am seeing that reading is successful (by printing to console) but writing does not happen.
here is the code:
public class ReadingIO {

    public static void main(String[] args){
        try {
            processfile();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private static void  processfile() throws IOException{
        BufferedReader fi = new BufferedReader(new FileReader("words.txt"));
        Writer out = new BufferedWriter(new FileWriter("testwrite.txt"));
        String b;
        while ((b=fi.readLine())!=null){
            System.out.println(b);
            out.write(b);

        }
    }

}

If I use FileInputStream and FileOutputStream it works. I want to know why FileWriter fails, not alternative ways to accomplish this.
Comment: flush or close your stream.
Comment: I did not close `FileOutputStream` and it worked. but with `FileReader` it fails
Answer: You need to call flush() while using Writer.
But not needed while FileOutputStream
Close calls flush on the stream, so flush is not needed if you want to close the stream.
Comment: but I did not close FileOutputStream and it still worked, why is that?
Comment: because `FileOutputStream` is not buffered, so the data is directly written to the file.
Comment: there is a close method for FileOutputStream too. why is it only for bufferedStream is closing essential?
Comment: @user1988876 Closing is *essential* for *all* streams. However as FileOutputStream isn't buffered, everything you wrote went to the file. If you don't close or flush a buffered stream/writer, you will lose data.
Answer: You need to call out.flush() when you are done.
Comment: not also, just use the `.close()` methods, they implicitly call `.flush()` and it's less to remember/mess up.
Comment: Also  `fi.close()` and `out.close()`
Answer: Add following lines after while loop.
out.close();

This method will cal flush() method automatically to write data to file which is still buffered, then close the stream.
Comment: The flush() is redundant. Closing the stream flushes it.
Comment: The idea is that you amend your answer.

why filewriter not working in java?


Calling Java notify() within an if condition

Question: I have just written a simple java example to get familiar with the concept of wait and notify methods.
The idea is that when calling notify(), the main thread will print the sum.
MyThread class
public class MyThread extends Thread {
    public int times = 0;

    @Override
    public void run() {

        synchronized (this) {
            try {
                for (int i = 0; i < 10; i++) {
                    times += 1;
                    Thread.sleep(500);
                    if (i == 5) {
                        this.notify();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

Main Class
public class Main {

    public static void main(String[] args) {

        MyThread t = new MyThread();
        synchronized (t) {
            t.start();
            try {
                t.wait();
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println(t.times);
        }
    }
}

Expected Results
5 but I got 10 instead.
Well, what I though is that when notify() is called, the main thread will wakeup and execute the System.out.println(t.times) which should give 5. Then the run() will continue till it finishes the for loop which will update the value of times to 10.
Any help is highly appreciated.
Comment: `notify` doesn't release the lock.
Comment: Possible duplicate of [A simple scenario using wait() and notify() in java](http://stackoverflow.com/questions/2536692/a-simple-scenario-using-wait-and-notify-in-java)
Comment: Can you please shed more light on this.
Comment: The thread does not leave the synchronized block. So main will not be able to continue running although wait could return.
Comment: Thank you all. Understood. Well, in this case I could have used join() instead.
Answer: Synchronized blocks imply mutual exclusion. At any given moment, only one thread is allowed to hold the lock and execute the code within a synchronized block. This rule spreads over all the blocks guarded by the same lock.
In your case, there're two such blocks that use the same lock, so it's either the main thread or the MyThread that is allowed to execute code in either of these blocks, the other thread must wait. So, you have the following scenario here:

The main thread acquires the lock.
The main thread starts the second thread.
The second thread hits the synchronized block but cannot enter it since the lock is being hold by the main thread.
The main thread calls wait(). This call releases the lock and puts the main thread into the WAITING state.
The second thread now can acquire the lock and enter the synchronized block.
The second thread counts to five and calls notify(). This call doesn't release the lock, it just notifies the main thread that it can progress as soon as it can reacquire the lock.
The main thread awakes but it cannot make progress because it cannot reacquire the lock (it's still being hold by the second thread). Remember, no two threads can be active within a synchronized block guarded by the same lock at once, and now, the second thread is still active, so the main one must continue waiting.
The second thread continues counting, sets times to 10 and eventually leaves the synchronized block, releasing the lock.
The main thread reacquires the lock and can now make progress to the println. But by this time, the times is already 10.

Using join() won't help you either because the result will be the same – the main thread can only make progress when the second one is finished.
If you want your main thread to continue execution as soon as the second thread hits 5, you need to acquire the lock and release it immediately after that event:
public class MyThread extends Thread {
    public volatile int times = 0;

    @Override
    public void run() {
        try {
            for (int i = 0; i < 10; i++) {
                times += 1;
                Thread.sleep(500);
                if (i == 5) {
                    synchronized(this) {
                        this.notify();
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Don't forget to make times volatile, otherwise JVM won't guarantee that you'll see its actual value in your main thread.
And you should also understand that this approach doesn't guarantee that your main thread prints 5. It might occur that by the time it reaches the println call, the second thread makes one or two or even more iterations and you'll see something greater than 5 (though it's highly unluckily due to the sleep() call on every iteration).
Comment: It is working like a charm. Thank you Andrew.

Much appreciated


Why this icon apears on my bar?

Question: How can I remove it? I think this is from Telegram but I uninstalled it.
When it was installed it was the exact icon there but with some Telegram options to chose.

Maybe this can help you:
KiB Swap:  4091900 total,  3984412 free,   107488 used.   688468 avail Mem

  PID USUARIO   PR  NI    VIRT    RES    SHR S  %CPU %MEM     HORA+ ORDEN
 6597 root      20   0  333336  88340  59492 S  14,1  2,2   1:34.22 Xorg
 7539 yami      20   0 1554200 217316  59584 S  12,2  5,5   1:22.30 compiz
 9332 yami      20   0 1105920 293844  90652 S   5,6  7,4   1:49.35 chrome
10821 yami      20   0  732468  36216  28620 R   5,3  0,9   0:01.22 gnome-term+
  893 root      20   0   32792   3840   3756 S   2,3  0,1   0:19.84 bluetoothd
 8302 yami      20   0 1056816 262684  79936 S   1,6  6,7   0:18.48 chrome
  935 root      20   0    4388   1240   1196 S   1,3  0,0   0:11.19 acpid
 8173 yami      20   0 1328416 222392  86928 S   1,0  5,6   1:29.44 chrome
 8598 yami      20   0 1092328 290372  91788 S   1,0  7,4   0:18.14 chrome
10840 yami      20   0   45756   3872   3232 R   1,0  0,1   0:00.33 top
  487 root       0 -20       0      0      0 S   0,3  0,0   0:02.60 kworker/u9+
 5879 root      20   0       0      0      0 S   0,3  0,0   0:00.98 kworker/u8+
 6244 root      20   0       0      0      0 S   0,3  0,0   0:00.63 kwork

Or this:
KiB Swap:  4091900 total,  3984412 free,   107488 used.   688468 avail Mem

  PID USUARIO   PR  NI    VIRT    RES    SHR S  %CPU %MEM     HORA+ ORDEN
 6597 root      20   0  333336  88340  59492 S  14,1  2,2   1:34.22 Xorg
 7539 yami      20   0 1554200 217316  59584 S  12,2  5,5   1:22.30 compiz
 9332 yami      20   0 1105920 293844  90652 S   5,6  7,4   1:49.35 chrome
10821 yami      20   0  732468  36216  28620 R   5,3  0,9   0:01.22 gnome-term+
  893 root      20   0   32792   3840   3756 S   2,3  0,1   0:19.84 bluetoothd
 8302 yami      20   0 1056816 262684  79936 S   1,6  6,7   0:18.48 chrome
  935 root      20   0    4388   1240   1196 S   1,3  0,0   0:11.19 acpid
 8173 yami      20   0 1328416 222392  86928 S   1,0  5,6   1:29.44 chrome
 8598 yami      20   0 1092328 290372  91788 S   1,0  7,4   0:18.14 chrome
10840 yami      20   0   45756   3872   3232 R   1,0  0,1   0:00.33 top
  487 root       0 -20       0      0      0 S   0,3  0,0   0:02.60 kworker/u9+
 5879 root      20   0       0      0      0 S   0,3  0,0   0:00.98 kworker/u8+
 6244 root      20   0       0      0      0 S   0,3  0,0   0:00.63 kwork

Comment: Have you restarted your system after removing that app?
Comment: Yes, I did twice :S
Answer: Maybe you didn't remove the program completely. Try follow this instructions: How to remove Telegram?
Comment: Didn't worked but thank you very much for your help ;)

Why this icon apears on my bar?


Blackbody curve to floating RGB

Question: I want to set the color of the lamps in my game with a black body curve, but the approximations I can find for it are all in sRGB color space; and I want it in linear floating RGB.
The closest thing i was able to find is this: https://mathematica.stackexchange.com/questions/57389/convert-spectral-distribution-to-rgb-color
But i really don't understand most of the notation in the answer.
Mainly I'm unsure: if i just use planck's law, using the wavelengths of the subpixels in a standard monitor--not that I know what those are--will it get the right answer, or would it need to be an integral with respect to cone response.
Furthermore I'm not sure how to normalize the resulting radiation density from.... whatever units its in, to 1.0 = X nits; as I'm unsure of the conversion between the units...
Comment: I saw your question in gamedev. I was going to post an answer, but the question was already deleted. Took me a while to find the question moved here.
Answer: The Open Shading Language has a complete implementation which is based on this source code from Color Rendering of Spectra by John Walker, according to the comments. I can't vouch for its theoretical correctness but I have used it and it appears to work reasonably well.
Comment: I believe this is the same one used in blender; it produces incorrect results below 2000C if i remember right?  at least when i tried to use blender's black body node to color lava the results were very incorrect.  but thank you though!
Comment: @PatrickJeeves I don't know about blender but this one looks "ok" even at low temperatures. It fades to orange, then red. The dynamic range is extreme but I think that is correct; picture a glowing piece of steel vs an arc welder flash.
Answer: The code below is based on the article How to Convert Temperature (K) to RGB: Algorithm and Sample Code with Neil Bartlett modifications from the article Color Temperature Conversion Of Homestar.io.
Bartlett has released a javascript library neilbartlett/color-temperature which computes RGB from kelvin with the color components in the range 0 to 255. The code below is adjusted for RGB components in the range 0.0 to 1.0.
float t = kelvin / 100.0;
float x;
float red;
float green;
float blue;
if (t <= 66)
{
    red = 1.0;
}
else
{
    x = t - 55.0;
    red = clamp(
        1.38030159086 + 0.00044786845 * x - 0.15785750233 * log(x),
        0.0,
        1.0);
}
if (t <= 10)
{
    green = 0.0;
}
else if (t <= 66)
{
    x = t - 2.0;
    green = clamp(
        -0.60884257109 - 0.00174890002 * x + 0.40977318429 * log(x),
        0.0,
        1.0);
}
else
{
    x = t - 50.0;
    green = clamp(
        1.27627220616 + 0.0003115081 * x - 0.11013841706 * log(x),
        0.0,
        1.0);
}
if (t <= 20)
{
    blue = 0.0;
}
else if (t <= 66)
{
    x = t - 10.0;
    blue = clamp(
        -0.99909549742 + 0.00324474355 * x + 0.45364683926 * log(x),
        0.0,
        1.0);
}
else
{
    blue = 1.0;
}

Note: log refers to natural log.
Comment: which is in sRGB clamped to 0-255; i want it unclamped in linear space; floating point color can have values above 1.0.

Blackbody curve to floating RGB


How to use a angular controller with ion-tab to set badge count?

Question: How to use a controller and assign badge number to a ion-tab using scope variable from the controller ?
I'm getting error when I tried this-
<ion-tab title="Home" badge={{homeBadgeCount}} ...

Syntax Error: Token '{' invalid key at column 2 of the expression angular
Please help...
Answer: Just figured out that I don't need to use the {{}} expression. Without that it works !!!
<ion-tab title="Home" badge=homeBadgeCount ...

Answer: As you can see, you can do it like badge=homeBadgeCount but that is not the best solution.
See w3schools / html attributes in section "We Suggest: Always Quote Attribute Values" to know why your solution works but is not the best practice.
Moreover, to know why your first try didn't work; I advice you to read these pages:

AngularJs directives, the official doc which explain how its parsing works
Stackoverflow - AngularJs - how are attributes evaluated

tl;dr write badge="homeBadgeCount" instead !


Designing a word with css using php

Question: Hey guys am new to css and php .I have been trying to output a php varibale with a custom colour using php.So i have used span tag for acheiving this.But when i tried it it wouldnt worked.
The code which i used is this
<?php
$name = "babe";
echo '
<?php $name; ?>
';
?>

When i run this code i get a blank screen ..
Am i missing something in my code ??
Hope you guys can help me out ..Thanks in advance
Comment: See my answer to solve your problem
Answer: Just delete the PHP code block in $name.
<?php
$name = "babe";
echo '
' . $name . '
';
?>

Answer: You are doing it is absolutely wrong.You are starting the php twice. Use the code below to make your code work. You are seeing the blank screen because your code is getting error. Check your error log , i am sure you will find error there.
<?php
$name = "babe";
echo '
'.$name.'
';
?>

or you can use this code too
<?php
$name = "babe";
echo '
{$name}
';
?>

Hope this helps you

Designing a word with css using php


Thermostat "fan" function actually using air conditioning

Question: A few months ago, my wife and I started sleeping with our bedroom doors closed to keep out our cat. We would wake up in the middle of the night to find our bedroom was very hot and it felt really hard to breathe. We got an Awair some time later and noticed the CO2 was shooting up to about 1500ppm within 2 hours.
To solve this, I began using the thermostat's "Fan" function set to ON to get ventilation continually throughout the night. My understanding is that this only blows air, but is separate from heating/cooling.
The problem is that even when we set our AC to heat or turn that system off, the fan appears to be cooling the house. Despite it never getting below 70°F outside, this fan function is getting the house down to 64°F within a few hours. Then, because I have the heat on to prevent it getting so low, the heat starts running.
I am running heating+cooling all night just to prevent from suffocating. Obviously our energy costs are out of control.
Am I misunderstanding something? Is it possible that thermostat is miswired such that the fan is hooked up to the AC itself? And how would I even begin to diagnose this?
Comment: What make and model are your thermostat and your air-handler, and can you post photos of the control (thermostat) wiring at each end + the wiring diagram for your system?
Answer: Sounds like it's miswired... But maybe your unit has limitations. Pictures would be great.
Answer: As a temporary workaround, shut off the A/C breaker at night.  This is a large double circuit breaker marked typically 20, 30 or 40.  A nearby hand-written map will show which breaker is for what circuit.  After you shut off an A/C unit, wait 10 minutes before turning it back on, to avoid "short cycling" and breaking the compressor.
Let's see... Basic thermostat wiring looks like

W is the white wire, and calls for heat
Y is the yellow wire, and calls for air conditioning
G is the green wire, and calls for fan

The thermostat connects any of them to the R wire, Red, which is the supply. It sounds like R is right, but double check it.
Closely inspect both ends of the thermostat wire to make sure they all go where they are supposed to.
Did you upgrade to a smart 'stat?
Most smart thermostats need a C (common) wire (which you put on any which wire you can, but preferred is blue).  Sometimes, their thermostat was wired with no spare wires, so they poach one of the other wires for that.  There are two strategies used to make up for this, which are of interest here.

They poach the G (fan) wire to use for common, which if done properly would eliminate the "continuous fan" switch functionality. However they have mis-wired it somehow, so the G terminal on the 'stat connects to the Y wire.
They make up for the missing wires with multiplexer boxes at each end. Those multiplexer boxes might fail.

Sanity check your conclusions
There is a large machine situated somewhere outside your house.  If your A/C is actually on, it will be making a lot of noise, and it will be blowing hotter-than-ambient air.  Double check your actual nighttime air temp, It can be cooler than you think, especially in desertine environments like the American southwest.


CNN for variable sized images in pytorch

Question: I want to make a CNN model in pytorch which can be fed images of different sizes. I am trying to use 2d convolution layer, which takes 4D input shape (pytorch's Conv2d expects its 2D inputs to actually have 4 dimensions).
However, I'm not sure how to set up the input layer that can adjust all the variable sized images into fixed number of feature maps to pass over to remaining layers.
For example, the shape of the input for colored images is [4, 3, 32, 32], which corresponds to batch size, number of channel(RGB), width, and height. If images are grayscale, then it will have [4, 1, 32, 32], which will produce an error when the shape is not what the layer expected.
Error message is "RuntimeError: Given groups=1, weight of size [6, 3, 5, 5], expected input[4, 1, 32, 32] to have 3 channels, but got 1 channels instead"
The architecture of my current CNN is like below.
def __init__(self, num_out, kernel_size, num_input_filters):
        super().__init__()
        self.num_input_filters = num_input_filters
        self.num_out = num_out
        self.kernel_size = kernel_size

        self.conv1 = nn.Conv2d(3, 6, 5)
        self.pool = nn.MaxPool2d(2, 2)

def forward(self, inp):
        inp = self.pool(F.relu(self.conv1(inp)))
        return inp

I have referenced similar questions and Fully convolutional networks (FCN) have no limitations on the input size at all, which could be the solution. And pytorch provides ConvTranspose2d() for FCN, but its parameters still seem to require fixed input size.
Are there any methods that can solve this problem?
Answer: You can just convert the grayscale images to RGB by duplicating the single channel to three.
As your example, shape [1, 32, 32] can be converted to [3, 32, 32] by the following codes:
np.concatenate((images,)*3)

If the shape is [32, 32, 1], try
np.concatenate((images,)*3, axis=-1)

If the shape is [32, 32], then you can try codes below to convert to [32, 32, 3]:
img_shape = tuple(np.ones(len(images.shape), dtype=int))
img_shape += (3,)
images = np.tile(np.expand_dims(images, axis=-1), img_shape)


Water flowing into toilet for too long after flush

Question: When I flush my toilet the cistern seems to struggle with filling up because so much water continues to flow into the toilet bowl and I don't know why.
I've removed the cistern top and pulled the red handle on the ball-cock and that stops the flow of water into the bowl, but only whilst I hold it.
However, interestingly the flush button seems to go loose after each flush, kind of like it becomes unconnected and the only way I can get the flow of water into the bowl to stop and the cistern to fill again is to pull off the cistern lid and constantly push on the flush button until I feel a bit of tension go back into the button. Then the cistern fills up fine with no problems and the water stops leaking into the bowl.
Does anyone have any idea what is wrong with it?
Comment: Would help if we knew what kind of toilet internals we're talking about. Is the flap sticking?
Comment: Did you ever get this resolved? If so, please give a check-mark to the answer that helped you the most, or write up your own answer explaining what you did to get it fixed and give yourself a check mark. That will help others with this kind of problem know that this has a resolution and is a good place to look for their answer.
Answer: Not knowing the specifics of your flush and valve system, I can only answer generally.
The fill-valve stops the inflow of water when some sort of sensor, typically an actual float, reaches a certain level of height either operating the fill valve to halt the ingress of water and usually ending the flush cycle, or it may in some way signal another part (unusual) to cease the water flow and end the flush cycle.
Most commonly a 'flapper valve' is physically lifted off of its 'seat' allowing the water in the tank to rush down into the bowl. Then the 'float' which operates the fill valve lowers until the valve opens, allowing water in to refill the tank. After the water exits the tank, the flush valve (or flapper) must lower onto its valve seat and re-seal the tank allowing it to re-fill ready for the next operation (or flush.)
If all of this only happens when you work the correct part manually (removing the cover and pressing with your finger) then one of two things are needed to restore correct operation (generally,)

You may be able to adjust some part of the mechanism to make it flush and re-fill as designed, stopping the fill operation at the correct level of water in the tank and not continue filling and possibly leaking water, usually into the tank. In many toilets the float may need replacement or adjustment. In many the fill valve components may need repair, adjustment or replacement. Often the flapper valve needs repair or adjustment - it may no longer be attached correctly, or the valve seat seal may be worn orobstructed.
In fill mechanisms with a single piece construction you may need to repair, adjust or sometimes replace that entire mechanism.

Either call a plumber or identify the type of mechanism, figure its mode of operation, and then try to determine where the fault occurs in its cycle. Without this info best we can do is guess!
Answer: "constantly push on the flush button until I feel a bit of tension go back into the button" (I've never worked on one with buttons) that's called jiggling the handle. That's what you have to do when the flapper doesn't seat right every time anymore. (replace flapper)
There should be a hose feeding into the overflow tube. Does the hose have a clamp on it for restricting the amount of water it dumps down it? (increase restriction. A less desirable option is to disconnect it from the tube)
Is the valve's float set so that tank level anywhere near overflowing into the tube doesn't happen? (decrease tank 'fill' level; lower the valve float)
Also, could be the chain float is way too low. (raise the chain float)
Answer: I don't think you address that you can turn the button on the flapper or turn the screw on the fill valve. These affect water. Can you address those issues.
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Comment: This does not provide an answer to the question. Once you have sufficient [reputation](https://diy.stackexchange.com/help/whats-reputation) you will be able to [comment on any post](https://diy.stackexchange.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/149139)


Select top 2 rows different from each other

Question: I have this table
 |      date    |  sum  |
 |--------------|-------|
 | 2015-02-19   | 10000 |
 | 2015-02-19   | 10000 |
 | 2015-02-20   | 15000 |
 | 2015-02-20   | 15000 |
 | 2015-02-21   | 18000 |
 | 2015-02-21   | 18000 |

I want to select top 2 rows from the table, but only different ones, meaning my result should return 2015-02-20 and 2015-02-21.
SELECT TOP 2 distinct date
FROM stock

Using this gives me an error:

Incorrect syntax near the keyword 'distinct'.

Help would be highly appreciated.
Comment: What order are you using?
Comment: i'm using "ORDER BY date DESC"
Comment: Do you care about `sum` field?
Answer: You can try like this
select top 2 * from
(
    select distinct date FROM stock
)

Answer: Try something like:
SELECT TOP 2 date
FROM stock
GROUP BY date

Answer: I think Distinct and Top should switch places in your query:
SELECT DISTINCT TOP 2 date FROM stock ORDER BY date DESC

Answer: try
   select distinct top 2 date  from stock

Answer: You can use GROUP BY:
SELECT TOP 2 date
FROM stock
GROUP BY date
ORDER BY date DESC

Sample result:
DATE
2015-02-21
2015-02-20

See result in SQL Fiddle.
Answer: Try this :
  WITH cte AS
 ( SELECT distinct date ,
       ROW_NUMBER() OVER (PARTITION BY date
                          ORDER BY date DESC
                         )
         AS rn
   FROM stock
 )
 SELECT date
 FROM cte
 WHERE rn <= 3
 ORDER BY rn ;

Comment: You ignored the part about distinct values.
Answer: Try this:
SELECT TOP 2 date FROM stock group by date

Comment: @Anik Islam Abhi  No difference, when i was posting the answer SMA i did not see the post.


Moen Bathroom Faucet Cartridge

Question: I need to identify the cartridge for a MOEN sink handle.
I need to know which cartridge to get, so I can purchuse the correct special tool for my sink. It is leaking, and I believe replacing the cartridge will solve this issue. If anyone knows how to go about this I would be greatful, thank you.

I will have a picture up when I get home to take one, but while I have the time I thought I would write the question.
Comment: Step one - call Moen technical support and see if they will send you one for free. Many of their faucets are "guaranteed for life" in residential use.
Comment: @Ecnerwal Gawd damn it I already ordered it. That is really good advice though.
Answer: Okay so I just got home, and took the faucet apart and found a number on the actual cartridge. It was a 6 digit number on the bottem. I googled the number and a bunch of places selling my faucet popped up. I was able to click on one of the selling sites, and pull the model number from there. The odd thing was that the model number only contained 3 of the digits on the brass fixture that the cartridge goes it. Im taking a picture right now with my I-pad and will edit it in. Hope this helps someone!

Moen Bathroom Faucet Cartridge


java internal implementation of java.awt.Button?

Question: In the java's implementation of java.awt.Button why does the ActionListener object is marked as transient?
from impl:    transient ActionListener actionListener;
Answer: The transient keyword in Java is used to indicate that a field should not be serialized.
Variables may be marked transient to indicate that they are not part of the persistent state of an object.
Here, ActionListener instance is a suitable candidate for marking as transient. we don't have any purpose to persist it. we use transient keyword when the class implements Serializable and we don't want the member to be persisted. we mark it as transient field.
Adding to that, java.awt.Button is a subclass of java.awt.Component, which implements Serializable interface. so, to restrict the serialization of actionListener member of the Button instance. actionListener field is marked as transient. Hope you understand
Comment: that's my doubt since we dont have any need to the object be persist can we make as transient?
Comment: we don't need to persist the state of ActionListener instance, since they are not part of the peristent state of Button
Comment: @VishalSantharam For members it is transient, For whole object you need not to do anything. Just don't implement serializable :)
Comment: Yes, Suresh is absolutely right. we use transient keyword when the class implements Serializable and we don't want the member to be persisted. we mark it as transient
Answer: The keyword transient was added, to suppress the normal serialisation: instead the serialisation for that field is done in readObject and writeObject.
And the reason for that is the usage of AWTEventMulticaster to build the structure of event listeners. The methods readObject and writeObject delegate the serialisation for actionListener to that class too.


What do you call a power splitter without a cable?

Question: ...No, this is not a setup for a joke.
In Israel we have gadgets like this one:

It's basically like a power strip, except it doesn't have a cable. You plug it into a lone power socket and now you have 2. It also comes in varieties where it gives you 3 or 4 power outlets.
Is there a name for this device in English?
Comment: VTC - This question has nothing to do with DIY home improvement or repair.
Comment: I would call it a 'double adapter'.
Comment: I'm voting to close this question as off-topic because it is not about do-it-yourself home improvement.
Answer: 'Receptacle multiplier' works on Google.
Answer: Turns out it's called an outlet tap.


What is the probability that the original sign was plus?

Question:
A slip of paper is given to A, who marks it with either a plus or a minus sign; the probability of his writing a plus is $\frac{1}{3}$. He then passes the slip to B, who may either leave it or change the sign before passing it on to C. Next C passes the slip to D after perhaps changing the sign. Finally, D passes it to an honest judge after perhaps changing the sign. The judge sees a plus
  sign on the slip. It is known that B, C, and D each change the sign with probability $\frac{2}{3}$. What is the probability that A originally a plus?

This problem came in my test last week. This is definitely not a H.W problem.
I have no Idea how do I approach it. I think it has to do with conditional probability with,
$x:$ Event that A started with "+"
$y:$ Event that the slip ends with "+"
With the solution as the answer to,
$$\text{P}(x|y)$$
But I am not sure how do I calculate x and y.
There has to be even exchanges given A started with "+" for the slip to end with "+". This is how far I could get.
Any help would be appreciated.
Answer: For the final sign to be a plus there are few possible cases. If $A$ marked a plus, then there must be an even number of sign changes by $B,C$ and $D$ in order for the final sign to be unchanged - i.e. the sign is changed $0$ or $2$ times. If $A$ marked a minus then there must be an odd number of sign changes by $B,C$ and $D$ in order for the final sign to be changed - i.e. the sign is changed $1$ or $3$ times. So;
$$\begin{align}
P((A+)\cap (J+))
&=P(A+)\cdot P(0\text{ or }2\text{ sign changes})\\
&=\frac13\cdot\left(\left(\frac13\right)^3+\binom{3}{2}\left(\frac23\right)^2\left(\frac13\right)\right)\\
&=\frac{13}{81}\\
\end{align}$$
$$\begin{align}
P((A-)\cap (J+))
&=P(A-)\cdot P(1\text{ or }3\text{ sign changes})\\
&=\frac23\cdot\left(\binom{3}{1}\left(\frac23\right)\left(\frac13\right)^2+\left(\frac23\right)^3\right)\\
&=\frac{28}{81}\\
\end{align}$$
By using Baye's theorem the required probability is
$$P(A+|J+)=\frac{P((A+)\cap (J+))}{P(J+)}=\frac{P((A+)\cap (J+))}{P((A+)\cap (J+))+P((A-)\cap (J+))}$$
$$\therefore P(A+|J+)=\frac{\frac{13}{81}}{\frac{13}{81}+\frac{28}{81}}=\frac{13}{41}$$


How can I use JS to assign a value on an input based on a key?

Question: Okay, take two.
Before you continue reading please note that I know basically ZERO JS so if I display some extreme stupidity, I'm trying my best.
I am attempting to implement PayPal into a website I'm creating and I found a button on the PayPal website that was basically exactly what I'm looking for.
I already have a working cart price calculation system that I've had in place for a while now and calculates Sales Tax/Shipping/The total price of the items in the cart TotalPrice and puts it into one h1 tag using document.getElementByID('ID').innerHTML = `$${localStorage.getItem('TotalPrice')}`  This works perfectly well, and has for a few months.
The button code exactly from the PayPal website is as follows:
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
 <input type="hidden" name="business" value="firstname.lastname@example.com">

<input type="hidden" name="cmd" value="_xclick">

<input type="hidden" name="item_name" value="Hot Sauce-12oz. Bottle">
<input type="hidden" name="amount" value="5.95">
<input type="hidden" name="currency_code" value="USD">

<input type="image" name="submit" border="0" src="https://www.paypalobjects.com/en_US/i/btn/btn_buynow_LG.gif" alt="Buy Now">
 </form>

and the value that actually sets the price PayPal charges once the form is submitted is in the hidden input with the name "amount". I figured that it would be relatively easy to set the value of that input by adding an ID and using similar logic to the working cart system. Here is what I have now:
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">

                <input type="hidden" name="business" value="firstname.lastname@example.com">

                <input type="hidden" name="cmd" value="_xclick">

                <input type="hidden" name="item_name" value="Checkout">
                <input type="hidden" name="amount" id="pricebutton" >
                <input type="hidden" name="currency_code" value="USD">

                <input type="submit" name="submit" border="0" id="checkoutbtn" alt="Buy Now" value="Checkout Using Paypal" onclick="payPal()">
            </form>

I also added some JS

What I tried to do was, when the button is clicked and the form is submitted, change the value of the form so that it matches the total value of the items in the cart, TotalPrice. What have I done wrong?
If you need more information, I will do my best to provide it through edits & comments.
Thanks.
Answer: You're better off using a JS smart button (code demo).
Then in createOrder you can just replace the price with localStorage.getItem('TotalPrice')


Can python read images from directory in real-time?

Question: I have written code for taking snap-shot from a selected video and save to image using OpenCV and save the file in a chosen directory, but I don't know how Python can get the list of files in the directory in real-time. Now I have written Python code to get the list of files in the directory but as soon as the file list is updated, the program ends. It is unable to read the directory when images in it get updated or there is a new Image created inside it.
My code:
from PIL import Image
import glob
image_list = []

for filename in glob.glob('path/*.jpg'):
    im=Image.open(filename)
    image_list.append(im)
print(image_list)

Comment: Possible duplicate of [How do I watch a file for changes?](https://stackoverflow.com/questions/182197/how-do-i-watch-a-file-for-changes)
Answer: Sounds like you need to use watchdog:
https://pythonhosted.org/watchdog/quickstart.html#a-simple-example
In a nutshell, you want to write your Python script to monitor a particular directory and watch for on_created events.  Once that event is found, read the file and continue monitoring the directory for additional on_created events.


Redirect to previously loaded page in codeigniter

Question: I have a page to select district and school and when the page is submitted the employees of that school is listed below.And  and from there is an edit page to edit employee details. In that page I have a back button which must redirect to previous page where district, school and employees have to be preloaded.
I'm using codeigniter framework. I used the following code
$ref = $_SERVER['HTTP_REFERER'];
echo anchor($ref,' ');
Bu the problem is  the page is promting to select district and school .The preloaded values are not retaining in the page.Can you please tell how it could be done.
Comment: If I am right , you need the values in the field to be restored...
Comment: Use set value if you are trying to restore form fields
Comment: once you click the edit button in the list page, are u redirecting (using normal page reload) the user to new page and displaying the details to edit or else you are using ajax to display the edit form in same page ?
Answer: To restore the form fields . you can use set_vale()
Example :
<input type = "text" name = "district" value = "<?php echo (set_value("district") != ""):set_value("district"):" "; ?>" />

Answer: Add bewlos lines in all pages before checking login status/session:
$current_url = current_url();
$CI->session->set_userdata('current_url',$current_url);

and after login :
redirect user to above page like :
if($this->session->userdata('current_url') != '')
{
   header('Location: '.$this->session->userdata('current_url'));
   exit();
}
else
{
   header('Location: '.get_client_url().'home');
   exit();
}


Display Vertical text in react native like drawer

Question: I need to display text in vertical position. the text will be dynamic so it can be short or long. i've added the screenshot of what i want. can anybody share the code for this type of ui. thanks in advance.
Like this
see this, this is what i got
<View>
  <View style={{}}>
    <View
      style={{ marginTop: 30, flexDirection: "row", justifyContent: "center" }}
    >
      <Text
        style={{
          textAlign: "center",
          fontSize: 20,
          alignSelf: "center",
          transform: [{ rotate: "90deg" }],
          color: "white",
          fontWeight: "bold",
        }}
      >
        Short
      </Text>
    </View>
  </View>

  <View style={{}}>
    <View
      style={{ marginTop: 30, flexDirection: "row", justifyContent: "center" }}
    >
      <Text
        style={{
          textAlign: "center",
          fontSize: 20,
          alignSelf: "center",
          transform: [{ rotate: "90deg" }],
          color: "white",
          fontWeight: "bold",
        }}
      >
        Long Text
      </Text>
    </View>
  </View>
</View>;

Comment: hey you can use css property for text `transform: rotate(deg);`
Comment: Hi @kunalpanchal i did. but its not working.
Comment: could you please share your  code snippet here so that we can debug it ?
Comment: @kunalpanchal i've updated my question. you can see my code now.
Answer: You're going to be in trouble if you try to apply the transformations one by one in all <Text />. Instead try to apply the transformations in a parent <View /> which gives you more control of what is going on.
const App = () => {
  const {width: screenWidth, height: screenHeight} = Dimensions.get('window');
  const height = 80;

  return (
    <View
      style={{
        transform: [
          {rotate: '-90deg'}, // negative degrees is important for this calculations and have the text face the content as your desired result picture shows
          {translateX: -(screenHeight / 2)}, // rotation is being applied in the center so it's safe to move it half screen
          {translateX: height / 2}, // correct the x translation with half of our component height so it stays on screen
          {translateY: -screenWidth}, // rotation is being applied in the center so it's safe to move it full screen width
          {translateY: height / 2}, // correct the y translation with half of our component height so it stays on screen
        ],
        width: screenHeight, // swap screen width with screen height so the background covers the entirety of the screen
        height, // fixed height is important to apply corrections on transform you could also use a ref and get this size on runtime
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: 'green',
      }}>
      <Text
        style={{
          fontSize: 20,
          color: 'white',
          fontWeight: 'bold',
          margin: 10,
        }}>
        Short
      </Text>

      <Text
        style={{
          fontSize: 20,
          color: 'white',
          fontWeight: 'bold',
          margin: 10,
        }}>
        Long Text
      </Text>

      <Text
        style={{
          fontSize: 20,
          color: 'white',
          fontWeight: 'bold',
          margin: 10,
        }}>
        Very Long Long Text
      </Text>
    </View>
  );
};

You can check the result here.
Comment: Thanks, it works, but it need some changes for my requirement.


Uncaught ReferenceError: FullCalendar is not defined

Question: I tried to use FullCalendar , but it gives me error:

Uncaught ReferenceError: FullCalendar is not defined

and also

error: Cannot read properties of undefined (reading 'datepickerLocale')

I have already tried the solutions:
link1 and link2 but still the same error.
I don't know how to solve this error.

document.addEventListener('DOMContentLoaded', function () {
        var calendarEl = document.getElementById('calendar');

        var calendar = new FullCalendar.Calendar(calendarEl, {
            locale: 'fr',
            eventDisplay: 'block',
            firstDay: 1,

            headerToolbar: {
                left: 'prev,next today',
                center: 'title',
                right: 'dayGridMonth,timeGridWeek,timeGridDay'
            },
            locale: 'fr',
            editable: false,
            droppable: false, // this allows things to be dropped onto the calendar
            eventClick: function (el) {
                el.jsEvent.preventDefault();
                $("#showEventModal").modal('show');
                $("#showEventModal").on('shown.bs.modal', function (e) {
                    $('#loading_zone').hide();
                    $('#target_zone').show();
                });
                $("#target_zone").load(decodeURIComponent( el.event.id));

                console.log($("#target_zone"));
            }
        });

        calendar.render();

    });
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>AGENDA</title>
    <link rel="icon"
      type="image/png"
      href="https://findicons.com/files/icons/2805/squareplex/512/google_calendar.png">

        <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
        <link rel="stylesheet" href="{{ asset('css/style.css') }}">
         <link rel="stylesheet" href="https://email@example.com/dist/flatly/bootstrap.min.css"
              crossorigin="anonymous">

        <link rel="stylesheet" href="https://email@example.com/main.css">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"
              integrity="sha512-iBBXm8fW90+nuLcSKlbmrPcLa0OT92xO1BIsZ+ywDWZCvqsWgccV3gFoRBv0z+8dLJgyAHIhR35VZc2oM/gI1w=="
              crossorigin="anonymous" referrerpolicy="no-referrer"/>

        <link href='https://cdn.jsdelivr.net/npm/@email@example.com/css/all.css' rel='stylesheet'>
        <link rel="stylesheet"
              href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/css/bootstrap-datetimepicker.css"
              integrity="sha512-63+XcK3ZAZFBhAVZ4irKWe9eorFG0qYsy2CaM5Z+F3kUn76ukznN0cp4SArgItSbDFD1RrrWgVMBY9C/2ZoURA=="
              crossorigin="anonymous" referrerpolicy="no-referrer"/>

Comment: N.B. There was no need to repeat your error message multiple times! Once is enough :-)
Comment: You can use this cdn, `https://firstname.lastname@example.com/index.global.min.js`
Answer: Your second locale file won't work because it's for the wrong version of fullCalendar. Only use the file which matches your fullcalendar version.
Also you need to load the main fullCalendar JS file before the locale file, because the locale file depends on fullCalendar. Once you correct those two things, it should work.
Summary of changes:

Remove  because it's not needed in fullCalendar 5

Move  before  in the HTML.

Demo:

document.addEventListener('DOMContentLoaded', function () {
        var calendarEl = document.getElementById('calendar');

        var calendar = new FullCalendar.Calendar(calendarEl, {
            locale: 'fr',
            eventDisplay: 'block',
            firstDay: 1,

            headerToolbar: {
                left: 'prev,next today',
                center: 'title',
                right: 'dayGridMonth,timeGridWeek,timeGridDay'
            },
            locale: 'fr',
            editable: false,
            droppable: false, // this allows things to be dropped onto the calendar
            eventClick: function (el) {
                el.jsEvent.preventDefault();
                $("#showEventModal").modal('show');
                $("#showEventModal").on('shown.bs.modal', function (e) {
                    $('#loading_zone').hide();
                    $('#target_zone').show();
                });
                $("#target_zone").load(decodeURIComponent( el.event.id));

                console.log($("#target_zone"));
            }
        });

        calendar.render();

    });
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>AGENDA</title>
    <link rel="icon"
      type="image/png"
      href="https://findicons.com/files/icons/2805/squareplex/512/google_calendar.png">

        <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
        <link rel="stylesheet" href="{{ asset('css/style.css') }}">
         <link rel="stylesheet" href="https://firstname.lastname@example.com/dist/flatly/bootstrap.min.css"
              crossorigin="anonymous">

        <link rel="stylesheet" href="https://firstname.lastname@example.com/main.css">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"
              integrity="sha512-iBBXm8fW90+nuLcSKlbmrPcLa0OT92xO1BIsZ+ywDWZCvqsWgccV3gFoRBv0z+8dLJgyAHIhR35VZc2oM/gI1w=="
              crossorigin="anonymous" referrerpolicy="no-referrer"/>

        <link href='https://cdn.jsdelivr.net/npm/@firstname.lastname@example.com/css/all.css' rel='stylesheet'>
        <link rel="stylesheet"
              href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/css/bootstrap-datetimepicker.css"
              integrity="sha512-63+XcK3ZAZFBhAVZ4irKWe9eorFG0qYsy2CaM5Z+F3kUn76ukznN0cp4SArgItSbDFD1RrrWgVMBY9C/2ZoURA=="
              crossorigin="anonymous" referrerpolicy="no-referrer"/>


Remove Single Table Row

Question: I've been searching through the web but I've had no luck in finding the solution to this problem. Yes I've tried other ways, but it didn't work either. Any help will be appreciated.
So here it goes: I want to remove on single row from the table, each row has unique ID and I dont know what the problem is... What could be the solution?

          Month
          Savings
          DELETE ROW

   <input type="button" value="ADD" id="btnADD"/>

Answer: You can do it this way -
var cont = 0;

function addRow(array) {
    $("#Mytabel").append("
" + array.Name + "	" + array.Cost + "	<input type='button' class='delete' value='DELETE'/>
");
}

$(function () {
    $("#btnADD").click(function () {
        var vet = {
            Id: cont,
            Name: "jan",
            Cost: 15
        };
        cont++;
        addRow(vet);
    });
    $('#Mytabel').on('click', '.delete', function () {
        $(this).closest('tr').remove();
    })
});

Demo ---> http://jsfiddle.net/UMVyQ/

Remove Single Table Row


Assignability error - cannot use r.x (variable of type int) as Numerator value in return statement

Question: In the below program, composite types(X & map[string]int) doesn't need explicit conversion, for assignability, because underlying type of composite types(X & map[string]int) is map[string]int, looks fine
package main

type X map[string]int

func main() {
    var x X
    var y map[string]int
    x = y
    y = x
}

In the below code,
package main

type RationalNumber struct {
    x int
    y int
}

type Numerator int
type Denominator int

// Constructor
func newRational(n, d int) RationalNumber {
    g := gcd(n, d)
    return RationalNumber{
        x: n / g,
        y: d / g,
    }
}

// Selector
func (r RationalNumber) numer() Numerator {
    return r.x
}

func (r RationalNumber) denom() Denominator {
    return r.y
}

func main() {

}

func gcd(a int, b int) int { // (15, 21) (-15, 21) (15, -21) (-15, -21)

    var f func(int, int) int
    f = func(x int, y int) int {
        if x%y == 0 {
            return y
        }
        return gcd(y, x%y)
    }
    if mod(a) < mod(b) {
        return f(mod(b), mod(a))
    }
    return f(mod(a), mod(b))
}

func mod(x int) int { // helper
    if x < 0 {
        return -x
    }
    return x
}

underlying type of identifier Numerator is int and r.x is of type int, but return r.x gives error.
So, why return r.x gives error? cannot use r.x (variable of type int) as Numerator value in return statement
Answer: This is mentioned in the Tour of Go

Unlike in C, in Go assignment between items of different type requires
an explicit conversion.

But why not use Numerator and Denominator in the definition of RationalNumber?
type Numerator int

type Denominator int

type RationalNumber struct {
    x Numerator
    y Denominator
}

Comment: why not use? Because the representation of data( in `RationalNumber` struct ) can change to `pair [2]int`. `Numerator` type is for usage and exposed to public
Answer:
So, why return r.x gives error? cannot use r.x (variable of type int) as Numerator value in return statement

Because while the underlying types are the same, the types are not. Just convert to the underlying type when returning:
return r.x.(Numerator)

Comment: types are not? Query edited


Group MySQL rows into buckets based on Min value

Question: I have a MySQL table with shopping options which looks like

Product
Seller
Price

ProductA
Seller1
10.0

ProductA
Seller2
10.2

ProductA
Seller3
12

ProductA
Seller4
13.6

ProductB
Seller5
5.0

ProductB
Seller6
5.1

ProductB
Seller7
5.2

ProductB
Seller8
5.7

ProductB
Seller9
5.8

I'd like to group shopping options into buckets based on the minimun product price, and divide all options into 2 groups:
GroupA: minimum price to (minimum price) * 10 % - competitive/fair prices
GroupB: above (minimum price) * 10 % - expensive prices
and count the number of sellers in each group
So the results should look like

Product
Min Price
Price threshold
GroupA sellers count
GroupB sellers count

ProductA
10.0
11.0
2
2

ProductB
5.0
5.5
3
2

Is there a way to do it using MySQL capabilities only?
Comment: *Is there a way to do it using MySQL capabilities only?* Of course. use subquery which calculates `Price threshold`.
Answer: SELECT Product, MIN(Price) as min_price, ...
FROM table
GROUP BY Product

It is not clear how you are computing price threshold, but this is very simple to add a column for to compute.
Answer: SELECT t1.Product,
       t3.Treshold,
       SUM(t1.Price <= t3.Treshold) GroupA,
       SUM(t1.Price > t3.Treshold) GroupB
FROM test t1
JOIN ( SELECT Product, MIN(Price) * 1.1 Treshold
       FROM test t2
       GROUP BY 1 ) t3 USING (Product)
GROUP BY 1

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=be61a9a526477ae821fa38c9cb450e8d


Swift:"Unrecognized selector sent to instance", Xcode 9.4.1

Question: Can anyone help me with this?
override func viewDidLoad() {
    super.viewDidLoad()
    tableView.delegate=self
    tableView.dataSource=self
    searchBar.autocorrectionType = .yes
    searchBar.delegate=self
    searchBarView.translatesAutoresizingMaskIntoConstraints=false

    let tap:UIGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector(("tapCancel:")))

    searchBarView.addGestureRecognizer(tap)
    tableView.addGestureRecognizer(tap)
    tableView.isUserInteractionEnabled=true
}
...
func tapCancel(sender:UITapGestureRecognizer){
    hideSearchBarView()
    isSearchon=false
    print("Tap cancel!")
}

Every time I tap the View, it crash.
"unrecognized selector sent to instance 0x7feb85d109e0"
I will appreciate any help!
Thanks!
Comment: Use `#selector(tapCancel)` instead of creating it from a string
Answer: I believe the reason is due to how method names get mapped between Swift and Objective-C, which underlies the Cocoa implementation and the whole target/action mechanism.
In your case, the Swift method:
@objc func tapCancel(sender:UITapGestureRecognizer)

...corresponds to the Objective-C selector:
-tapCancelWithSender:

Note: In order to work with the target/action paradigm (i.e., called by means of a selector), the method needs to be declared as @objc. The alternative attribute @IBOutlet (for use in conjunction with Interface Builder) also supports this. (tip of the hat to @rmaddy)
In order to remove the "withSender" part and get a selector that matches tapCancel:, you need to tell Swift to remove the argument label sender, like this:
func tapCancel(_ sender:UITapGestureRecognizer) // Notice the underscore (_)

Also, in line with the comment by @dan, perhaps you can use:
#selector(self.tapCancel(_:))

or more succinctly, as pointed by (thanks again) @rmaddy, just:
#selector(tapCancel)

(Xcode will try to autocomplete it to #selector(tapCancel(_:)), but the shorter syntax works as well and the method name is highlighted)
I was not familiar with the Selector() syntax you used, so I tried playing a bit with it, and behold:

(Selector does not match any method the compiler can "see").

(After adding "withSender", the compiler can match the method, but it suggests using the better #selector(... syntax).
As @rmaddy also pointed out in the comments, using the shorter #selector(doSomething) syntax (no colons, no underscore, no self) also does away with the problem of whether "withSender" is needed or not.
Comment: You just need `#selector(tapCancel)`. You do not need to add the `_` before the `sender` parameter.. And you need to add `@objc` just before `func tapCancel...`
Comment: @rmaddy Thank you, I'll update the answer as soon as I get to my desk.
Answer: use
let tap:UIGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapCancel))
instead of
let tap:UIGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector(("tapCancel:")))

And add @objc before method tapCancel()