text:
Q: use keyword as identifier in typescript I'm trying to use the class keyword as a function identifier in a namespace like:
namespace X {
   export function class( ... ) { ... }
}

The namespace itself is extending a function (function X ( ... ) { ... }).
Is there any way this can be done?

A: There isn't a way to do this in TypeScript. You'd have to somehow declare a quoted name in a namespace, but there is no syntax for doing that. It's also impossible to declare a type named class, so you're blocked in two different ways.
You could write (<any>X)['class'] = class { ... } if you just needed this to be present at runtime and didn't need any type system features.

A: If what you're trying to do is name a method class this is a pretty big no no across programming languages.  class is what you would call a reserved word: https://en.wikipedia.org/wiki/Reserved_word
You could call the method "Class" instead and will have better results I think.

A: I found a workaround for this.
interface I {
   (foo: Bar): Baz
   class(foo: Bar): Baz
}

const X = (function (X: any) {
   X.class = function (foo: Bar) { ... }
   return <I>X
})(function (foo: Bar) { ... })


text:
Q: ActionSheetPicker Invalid target/action combination used for ActionSheetPicker' Hi I'm trying to use ActionSheetPicker to let the user select a time for a reminder but I get the error described in the title. Here is my Code:
SelectTime(sender: validCell) // called when tapping a date

// Time Picker
func SelectTime(sender: UIView){
    //let timePicker = ActionSheetDatePicker.show(withTitle: "Enter time for reminder", datePickerMode: .time, selectedDate: userDate, target: self, action: , origin: sender.superview!.superview)
    let timePicker = ActionSheetDatePicker.show(withTitle: "Enter time for reminder", datePickerMode: .time, selectedDate: userDate, target: self, action: Selector(("timePicked")), origin: sender.superview!.superview, cancelAction: Selector(("timeCanceled")))

    timePicker?.minuteInterval = 5

    timePicker?.locale = Calendar.current.locale
    timePicker?.show()

}
func timePicked(time: Date){
    dateSelected.text = formatter.string(for: time)
}
func timeCanceled(){
    print("Canceled")
    dismiss(animated: true, completion: nil)
}

The cancel code is never called and when I press cancel on the timePicker it shows another time picker underneath it without any buttons.
Gif when canceling
http://www.giphy.com/gifs/l1J3zMQWJ23GpHEaY
The dateSelected is also never called. I'm I doing the selectors wrong?

A: Change this code
func SelectTime(sender: UIView){
    let timePicker = ActionSheetDatePicker.show(withTitle: "Enter time for reminder", datePickerMode: .time, selectedDate: userDate, target: self, action: , origin: sender.superview!.superview)
    let timePicker = ActionSheetDatePicker.show(withTitle: "Enter time for reminder", datePickerMode: .time, selectedDate: userDate, target: self, action: Selector(("timePicked")), origin: sender.superview!.superview, cancelAction: Selector(("timeCanceled")))

     timePicker?.minuteInterval = 5

     timePicker?.locale = Calendar.current.locale
timePicker?.show()

}
 func timePicked(time: Date){
dateSelected.text = formatter.string(for: time)
}
func timeCanceled(){
print("Canceled")
dismiss(animated: true, completion: nil)
}

in this code....
 let timePicker = ActionSheetDatePicker(title: "Date:", datePickerMode: UIDatePickerMode.date, selectedDate: Date(), doneBlock: {
        picker, value, index in
 dateSelected.text = formatter.string(for: time)
        print("value = \(value)")
        print("index = \(index)")
        print("picker = \(picker)")
        return
    }, cancel: { ActionStringCancelBlock in
        print("cancel")
        return }, origin: sender.superview!.superview)
     timePicker?.minuteInterval = 5
     timePicker?.locale = Calendar.current.locale

redpajama_set_name: RedPajamaStackExchange


text:
Q: TypeError: $(...).timepicker is not a function I am getting problem with Jquery timepicker(); function
Here it is
<link href="js/jqueryTimepicker/jquery.timepicker.css" rel="stylesheet" />

This is HTML markup

                Monday
                Tuesday
                Wednesday
                Thursday
                Friday
                Saturday

                    <input type="text" id="txtMonday" />

                    <input type="text" id="txtTuesday" />

                    <input type="text" id="txtWednesday" />

                    <input type="text" id="txtThursday" />

                    <input type="text" id="txtFriday" />

                    <input type="text" id="txtSaturday" />

Jquery
All of the above jquery files are loading well enough but it throws one error TypeError: $(...).timepicker is not a function
Help!!! I am no where

A: One of your imports may not be working correctly since I got it working in a JSFiddle. Try redownloading the CSS/JS files and make sure they are in the correct locations. If that still doesn't work, you can use the CDN for referencing the CSS/JS files.
Put the following in your HTML code and it should be fixed

Also, in future, I might suggest using a CSS class instead of individual id's like so:
$(document).ready(function () {
        $('.txt').timepicker();
    });

A: You may have a problem importing the files.
Look: JSFiddle
Check the external resources that I used.
$(document).ready(function () {
        $("#txtMonday").timepicker();
        $("#txtTuesday").timepicker();
        $("#txtWednesday").timepicker();
        $("#txtThursday").timepicker();
        $("#txtFriday").timepicker();
        $("#txtSaturday").timepicker();
    });

A: you need to use 'jQuery' instead of the '$' symbol to handle the document as jquery variable so put your .timepicker() function inside this block of code:
 jQuery(document).ready(function($){
      // code goes here
    });

So your code should be like this:
   jQuery(document).ready(function($){
            $("#txtMonday").timepicker();
            $("#txtTuesday").timepicker();
            $("#txtWednesday").timepicker();
            $("#txtThursday").timepicker();
            $("#txtFriday").timepicker();
            $("#txtSaturday").timepicker();
        });

A: <!DOCTYPE html>

      <link rel="stylesheet" href="//code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">

      <link rel="stylesheet" href="//jonthornton.github.io/jquery-timepicker/jquery.timepicker.css">

      <form method="post" action="makecleaningappt">

        <input type="text" id="datepicker" name="date">

        <input type="text" id="timepicker1" name="time">

            <input type="text" id="datepicker1" name="date">

            <input type="text" id="timepicker2" name="time">
      </form>


text:
Q: Makefile working in Linux but not under Windows, can't find files in subdirectory I have a makefile (gnu make) working under linux, but when porting it to windows it does not work. The goal of the makefile is to make all the *.cpp file that reside in different subdirectories and compile them into *.obj files in a single BUILD_DIR.
Between linux and windows I only adjusted the SOURCES variable, the linux line is shown but commented. When I check all the names and directories they show the same (relative paths in their perspective notation) and what I expect.
The "error message" I get on windows is: make: *** No rule to make target 'DEM.cpp', needed by 'DEM.obj'.  Stop.
In debug mode it says: File 'DEM.cpp' does not exist. (which it obviously does)
On linux it finds the file via the VPATH, in debug mode it says: No need to remake target 'DEM.cpp'; using VPATH name './Code/DEM.cpp'.
The subdirectory structure in both linux and windows is the same and the makefile is run from the same location.
Question: What is going wrong here, I have the feeling it has something to do with VPATH being handled differently on windows but I am not certain.
My makefile is:
# MAKEFILE
# Some makefile settings
SHELL = /bin/sh     #Make sure the shell is the standard shell
.SUFFIXES:      #Clear al implicit suffixes
.SUFFIXES: .cpp .obj    #Set used suffixes

# Variable Declaration
CXX := g++
BUILD_DIR = .\bin\Release
PROGRAM_NAME := DEM.exe

#SOURCES := $(shell find . -name '*.cpp')                   #All *.cpp files with directory (LINUX style)
SOURCES := $(shell FORFILES /S /M *.cpp /C "CMD /C ECHO @relpath")  #All *.cpp files with directory
NAMES := $(notdir $(basename $(SOURCES)))                   #Get all files names of the *.cpp files without extensions
OBJECTS := $(addsuffix .obj, $(NAMES))                      #Get the to be generate *.o files without directory
SRC_DIRS := $(dir $(SOURCES))                               #All the directory in which the sources are found
VPATH := $(SRC_DIRS) $(BUILD_DIR)

.PHONY: all
all: build                                  #Standard entry point, run release
    @echo "BUILD DONE"

.PHONY: build
    build: $(PROGRAM_NAME)
    @echo "BUILD DONE"

$(PROGRAM_NAME): $(OBJECTS)
    @echo "Link executable"
    $(CXX) -o $(BUILD_DIR)/$(PROGRAM_NAME) $(addprefix $(BUILD_DIR)/,$(OBJECTS))

$(OBJECTS): %.obj: %.cpp
    @echo "Compile into object code: $<"
    ${CXX} $(CXXFLAGS)  -c $< -o $(BUILD_DIR)/$@    #Compiles object code and places it in the $(BUILD_DIR)

Update 1: Based on the comment of some programmer dude, I ran it with -p, and got the following interesting result:
# Not a target:
DEM.cpp:
#  Implicit rule search has been done.
#  File does not exist.
#  File has not been updated.

# Not a target:
World.cpp:
#  Implicit rule search has not been done.
#  Modification time never checked.
#  File has not been updated.

# Lot more targets below

It seems only to not find DEM.cpp but it finds everything else.
DEM.cpp resides in C:\Users\dklomp\Documents\Programming\C++ Source\DEM\DEM\Code, but should resolve to .\Code\
Most other files reside in subdirectories in Code.
But stdafx.cpp also resides in .\Code\ and there is no problem finding it.
Can it be a name clash with the directory name DEM being similar to DEM.cpp
Update 2: For information and closure.
I had already check the VPATH by reading the variable by printing it this seemed to give the correct information. However if i read it with @(info $(VPATH)) it seemet empty:
@echo "VPATH print variable: "
@echo "$(VPATH)"
@echo "VPATH print info: "
$(info VPATH)

gave:
"VPATH print variable: "
"./Code/InputOutput/ ./Code/InputOutput/ ./Code/InputOutput/
./Code/InputOutput/ ./Code/ ./Code/ ./Code/Models/ ./Code/Models/
./Code/Forces/ ./Code/Forces/ ./Code/Forces/ ./Code/Forces/ ./Code/Forces/
./Code/Forces/ ./Code/Forces/ ./Code/Forces/ ./Code/Forces/ ./Code/Tools/
./Code/Tools/ ./Code/Tools/ ./Code/Tools/ ./Code/Solvers/ ./Code/Solvers/
./Code/Solvers/ ./Code/World/ ./Code/World/ ./Code/World/ ./Code/World/
./Code/World/ ./Code/Interactions/ ./Code/Interactions/ ./Code/Interactions/
./Code/Interactions/ ./Code/Interactions/ ./Code/Interactions/
bin\Release"
"VPATH print info: "

Indeed with a lot of repetitions (will use the sort suggestion of hardcoreHenry)  but it seemed oke. However the VPATH info is empty for some reason.
However implementing the proposed solution by code_fodder and removing all the inline code comments works. The inline code comments on the variable declaration do not seem to matter, those in the rules section do for windows, linux seems to handle inline code comments fine everywhere.
As usually thanks for the help and suggestions.

A: I tested this in a path that had spaces before the current location (e.g. like d:\path with spaces\myfolder\sub_folder1\sub_folder2\).
I think there is some issue with the FORFILES syntax/output - at least I could not get it to work. As soon as I used the more generic rwildcard from second answer from here it started to work quite well. Then I added rules to create/clean your output folder.
Also I removed any inline comments, since I am not 100% sure they are valid because they leave space characters everywhere and makefile is not very tolerant of that... I.E. make-sure you don't leave any trailing white space on any lines.
Also - this all assumes its gnu-make and not nmake
# MAKEFILE
# Some makefile settings
SHELL = /bin/sh
.SUFFIXES:
.SUFFIXES: .cpp .obj

# Variable Declaration
CXX := g++
BUILD_DIR = .\bin\Release
PROGRAM_NAME := DEM.exe

# Define a recursive wild card function that is portable.
rwildcard=$(foreach d,$(wildcard $1*),$(call rwildcard,$d/,$2) $(filter $(subst *,%,$2),$d))

#SOURCES := $(shell FORFILES /S /M *.cpp /C "CMD /C ECHO @relpath")
SOURCES := $(call rwildcard, ./, *.cpp)
$(info SOURCES: $(SOURCES))
NAMES := $(notdir $(basename $(SOURCES)))
OBJECTS := $(addsuffix .obj, $(NAMES))
SRC_DIRS := $(dir $(SOURCES))
VPATH := $(SRC_DIRS) $(BUILD_DIR)

.PHONY: all
all: create_dirs build
    @echo "BUILD DONE"

# Has an order dependency on create_dirs to ensure that happens first, and so
# it works with parallel build (e.g. `make -j4`)
.PHONY: build
build: $(PROGRAM_NAME) | create_dirs
    @echo "BUILD DONE"

$(PROGRAM_NAME): $(OBJECTS)
    @echo "Link executable"
    $(CXX) -o $(BUILD_DIR)/$(PROGRAM_NAME) $(addprefix $(BUILD_DIR)/,$(OBJECTS))

$(OBJECTS): %.obj: %.cpp
    @echo "Compile into object code: $<"
    ${CXX} $(CXXFLAGS)  -c $< -o $(BUILD_DIR)/$@

.PHONY: create_dirs
create_dirs:
    @echo "creating dirs"
    mkdir -p $(BUILD_DIR)

.PHONY: clean
clean:
    @echo "cleaning"
    rm -rf $(BUILD_DIR)


text:
Q: loading DOM using phantomjs My html webpage has javascript that loads and applies stylesheets dynamically. All the content and rendering happens inside a div tag. This is not loading the contents of the div tag, which has the id = 'tagid'. Do you know what is wrong here? I am using jquery function to ensure that the page is loaded. But is seems page.evaluate is not even called.
I am writing unit tests using phantomjs. New to the phantomjs. Refer to the code snippet below.
page.open(address, function(status){
    console.log('status '+status)
    if(status=='success'){
        console.log('inside status if ')
        page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js", function() {
            console.log('after include js ')
            page.evaluate(function(){
                console.log('inside evlaute ')
                $(window).load(function(){
                    console.log(document.getElementById("tagid").innerHTML)

                });
            });

            setTimeout(function(){phantom.exit()},18000)
        })
    }
})

A: Your code is correct, but the console.log call does not have any effect by default as it happens in the PhantomJS page's context.
You can either use the return value of the evaluate call as follows:
page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js", function() {
  console.log('after include js ')
  var tagid = page.evaluate(function(){
    console.log('inside evlaute ')
    return document.getElementById("tagid").innerHTML;
  });

  console.log('Got tag ID: ' + tagId)
  setTimeout(function(){phantom.exit()},18000)
})

Or you can choose to display messages that are logged in the page by using onConsoleMessage (more complicated setup):
page.onConsoleMessage = function(msg, lineNum, sourceId) {
  console.log('PAGE CONSOLE: ' + msg + ' (from line #' + lineNum + ' in "' + sourceId + '")');
};

An important note is that PhantomJS and page's context are separate: inside evaluate calls, you can't access variables from outside. In fact, under the hood, the callback given to evaluate is converted to a string before being given to the page. This is a very confusing part of PhantomJS that must be considered.

A: You could try by giving some timeout before you call evaluate.
window.setTimeout(function () {
    page.evaluate(function() {
         console.log(document.getElementById("tagid").innerHTML)
    });
}, 1000 // adjust the time here

To check what content is being rendered in phantomjs, you can use page.content and check there if your "tagid" element is indeed present.


text:
Q: Inject class object based on generic type using Spring I have a question related to Spring injection.
I have a class defined with a generic type parameter. I want to know whether it is possible to inject the class object of the type T ( I mean T.class) ?
Like this:
@Component
public class MyExecutor<T> {
    @Autowired
    public MyExecutor(<Inject class object of T>) {
         ....
    }
}

Thank you very much.

A: That concrete example would not work, but there is another way to create beans using generics and keep the type when injecting the bean in other beans.
Spring 4 has extended the support for generics in Java configuration. It is now possible to define two beans that differ only in the generic parameter used, and inject them by type in another bean, see this JIRA:
@Configuration
public class Config {

    @Bean("beanA")
    public MyExecutor<A> beanA() {
         return new MyExecutor<A>(A.class);
    }

    @Bean("beanB")
    public MyExecutor<B> beanB() {
         return new MyExecutor<B>(B.class);
    }
}

Then beanA or beanB can be injected by type:
@Component
public class OtherClass {

    @Autowired
    private  MyExecutor<A> beanA;

}


text:
Q: Rollback a wrong push to master I am new to Git and wanted to first create a branch and push my changes to it, but accidentally I just pushed my changes to the whole master. Now how can I rollback those changes?
Can I use any of these buttons in the picture below?
Image in here,  I am new to SO so I can't upload directly:
http://i49.tinypic.com/1zyu250.png

A: Since you have already sent the commit to the remote repository, you should use revert. It will create a new commit reverting the changes that you did. To use it, you need to pass the hash of the commit that you want to revert the changes:
git revert commit-hash

If you want to delete the commit from the repository, you can use git reset to return your repository to a state before the wrong commit. To do this, you need the hash of the commit before the wrong commit:
git reset --hard commit-hash

This will delete all changes that were done after the wrong commit too. And to delete the commits from the remote repository, you need to pass the option -f to git push because you are changind the repository history:
git push -f


text:
Q: Searching users with WP_List_Table plugin I am trying to devlope a plugin that will search and return my users so I can edit some other metatdata that belongs to them. I have been using the plug-in listed on the Codex as my starting point.
I have my table appearing with the the users from a WP_User_Query. But I am having issues with filtering the query with the search input.
Wildcard search mysearch will return the table correctly, but going to the second page returns back to a blank search. The search variable is not being placed in the url. How do I pass this to the url? (the pagination is passed only)
Also is there a way to change it so that I do not have to physically at "*" before and after the search parameters and have it done in the code?
Here is my query:
function prepare_items() {
    global $wpdb;

    $searchcol= array(
    'ID',
    'user_email',
    'user_login',
    'user_nicename',
    'user_url',
    'display_name'
    );

    $orderby = !empty($_GET["orderby"]) ? mysql_real_escape_string($_GET["orderby"]) : 'email';
    $order = !empty($_GET["order"]) ? mysql_real_escape_string($_GET["order"]) : 'ASC';

    $args  = array(
    'fields' => 'all_with_meta',
    'orderby' => $orderby ,
    'order' => $order ,
    'search' =>$_REQUEST["s"] ,
    'search_columns' => $searchcol
    );

    $my_query = new WP_User_Query( $args );
}

and here is my search field:
    function my_render_list_table_page(){
    global $my_list_table_sample_page, $wpdb;

    $my_list_table_sample_page->prepare_items();
    <form action="" method="post" >
<?php
   $my_list_table_sample_page->search_box( __( 'Search Users' ), 'user' );
   $my_list_table_sample_page->display();
   $my_list_table_sample_page->display();
   echo '</form>';
}

A: Brian is correct. By changing the form to use get instead of post and then using $_REQUEST to fetch it should work, and is for me.
// Fetch, prepare, sort, and filter our data.
if( isset( $_REQUEST ["s"] ) ){

// Form that displays the table and also contains the search_box()
<form id="table-class-filter" method="get" class="table-class-admin-form">

A: As Brian noted, your form sends the data via POST, and you are fetching via GET.  Change for method to "GET" or else use the $_POST variable.  (But note that your search term is passed along using your current code, because both POST and GET populate the $_REQUEST variable).
You can make the search more flexible by ensuring that it is surrounded by wildcard (asterisk) characters.  Something like this should do the trick:
$search = preg_replace( "^$\**(.*)\**$?#", "*$1*", $_REQUEST["s"] );
This will allow the search input was submitted with zero or more leading/trailing asterisks, and ensure that your search string is preceded and followed by a single asterisk.


text:
Q: Position selectize option I am using angular-selectize ,
on the onInitialize method I am adding an empty option.
onInitialize: function(selectize) {
  selectize.addOption({id: '', name: 'None'});
}

I am also using a sortField value in order to sort the options
sortField: [{field: 'name',direction: 'asc'}],

Problem is that None option is been sorted too, I want to have that in the top of my options.
How can I achieve this ?


text:
Q: Difference between two consecutive mongodb documents fields I have a time-series collection in mongodb. Which looks like this:
{ _id: 1, time: 2021-01-03T06:26:20.000+00:00 }
{ _id: 2, time: 2021-01-03T06:26:21.000+00:00 }
{ _id: 3, time: 2021-01-03T06:26:22.000+00:00 }

I want to accumulate all document based on time field and all documents are sorted based on time field. And output should be look like (t3-t2) + (t2-t1). So for this output will be 2 seconds.
For postgresql we can use window function or joins to calculated. How to calculate this in mongodb?

A: You an use this one:
db.collection.aggregate([
   { $match: { _id: { $ne: 3 } } },
   { $group: { _id: null, max_time: { $max: "$time" }, min_time: { $min: "$time" } } },
   { $set: { difference: { $divide: [{ $subtract: ["$max_time", "$min_time"] }, 1000] } } }
])


text:
Q: RecyclerView.ViewHolder unable to bind view with ButterKnife I'm using ButterKnife to bind my views on my ViewHolder. My code is below:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

    private List<DataObject> data;

    public MyAdapter(List<DataObject> data) {
        this.data = data;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_layout, parent, false);
        return new ViewHolder(view);
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.row_header_view) View rowHeaderView;
        @BindView(R.id.row_header_view_text) TextView headerTextView;

        @BindView(R.id.row_data_view) View rowDataView;
        @BindView(R.id.row_data_view_text) TextView rowDataTextView;
        @BindView(R.id.row_data_view_detail_text) TextView rowDataDetailTextView;

        public ViewHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
        }
    }
}

For some reason in my ViewHolder all of the BindView's do nothing. They are all null. I can confirm with certainty they are in my layout. What is wrong with my above code? I have used it as per the documentation listed here:
http://jakewharton.github.io/butterknife/#reset
Is there anything else required? I'm using ButterKnife version:
compile 'com.jakewharton:butterknife:8.2.1'

If I add the below line:
rowHeaderView = view.findViewById(R.id.row_header_view);

It's able to get the view properly. But how does this make sense? Isn't ButterKnife usable where findViewById is usable?

A: Update for October 2016: You probably don't need apt and the android-apt plugin anymore. Version 2.2 of the Android Gradle plugin has an annotationProcessor configuration that you should be using instead.
In Android studio 2.2 onward, just add these on your build.gradle module :
compile 'com.jakewharton:butterknife:8.4.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'

A: Make sure that if you have use ButterKnife library to use this way
build.gradle file of Project
buildscript {
  repositories {
    mavenCentral()
   }
  dependencies {
    classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
  }
}

Then, apply the 'android-apt' plugin in your module-level build.gradle and add the Butter Knife dependencies:
apply plugin: 'android-apt'

android {
  ...
}

dependencies {
  compile 'com.jakewharton:butterknife:8.2.1'
  apt 'com.jakewharton:butterknife-compiler:8.2.1'
}


text:
Q: How to test RESTful CRUD api with Mocha Chai on Node.js server side if login needed? I want to test a web app server side CRUD logics. But only login user can visit the web app.
if (res.locals.user){
  //CRUD functions here
}

I know how to use Mocha and Chai to test these CRUD functions without the login check there, but how can I mock login user to test them? Use cookie?

A: I generally do something along the lines of:
var request = require('supertest');

describe('My tests', function(){

    var agent = request.agent(app);

    //before all the tests run, log in
    before(function(done){
        request(app)
        .post('/login')
        .send({
            username: 'a@b.com',
            password: 'password123'
        })
        .end(function (err, res) {
            if (err) { return done(err); }

            agent.saveCookies(res);

            done();
        });

    });

    it('Does something when logged in', function (done){
        var req = request(app).get('/account/something')
        .expect(200);

        //attach the logged in cookies to the agent
        agent.attachCookies(req);

        req.end(done);

        //assertions here
    });
})

Fire off a login request first, save the cookies to the agent
Then, in requests I want to use the authenticated request. attach the cookies to it.
app is the instance of the Express app

A: @Russj, assuming that:

*

*you're using passport-local as your passport authentication strategy

*you're using supertest to simulate your api calls

*you already have an file that exports your Express app

Then this is how I would go about testing authenticated end-points:
var request = require('supertest'),
    agent = request.agent();
    mongoose = require('mongoose'),
    // this examples assumes /path/to/your/app exports your Express app
    app = require('/path/to/your/app'),
    // replace this with the model you use for authentication
    UserModel = mongoose.model('UserModel');
    // this example assumes your user model looks something like the following:
    //
    //     UserModel = new mongoose.Schema({
    //       username:  String,
    //       password: String
    //     });

describe('testing authenticated end-point', function () {
    var UserModel, testuser;

    before(function (done) {

        // this is just to ensure we have a user to log in for your tests
        UserModel.findOneAndUpdate({
            { username: 'testuser' },
            { username: 'testuser', password: 'testpassword' },
            { upsert: true }, // this will create the user if it doesn't already exist
            function(err, doc) {
                testuser = doc
            }
        });

        // I assume /simulate-login is not an existing route in your app
        app.get('/simulate-login', function(req, res) {
            req.login(testuser); // .login is exposed in req by passport
        });

        // now we simulate login of our testuser and save  the cookies
        request(app)
            .get('/simulate-login')
            .end(function (err, res) {
                    if (err) { return done(err); }

                    // save cookies
                    agent.saveCookies(res);

                    done();
            });
    });

    // clean up after ourselves
    after(function () {
        UserModel.remove({ username: 'testuser' }).exec();
    });

    // now we can test an authenticated end-point as long as we attach the saved cookies
    it('should do whatever...', function (done) {
        var req;

        req = request(app)
            .get('/path/to/route/to/test')
            .expect(200);

        // attach cookies
        agent.attachCookies(req);

        // do your reqeust
        req.end(done);
    });

});


text:
Q: Getting Rid Of Error Log When Unauthenticated Redirect Fires If a user is not registered and tries to reach a page that needs authentication, I redirect the visitor to login with Bolierplate Laravel AuthCode.
However, when I check error log I receive and error. ( It works on client-side without any problems)
Error Log:
Illuminate\Auth\AuthenticationException: Unauthenticated. in /home/forge/xyz.com/vendor/laravel/framework/src/Illuminate/Auth/GuardHelpers.php:40 Stack trace: #0 /home/forge/xyz.com/vendor/laravel/framework/src/Illuminate/Auth/AuthManager.php(292): Illuminate\Auth\SessionGuard->authenticate() #1 /home/forge/xyz.com/vendor/laravel/framework/src/Illuminate/Auth/Middleware/Authenticate.php(57): Illuminate\Auth\AuthManager->__call('authenticate', Array) #2 /home/forge/xyz.com/vendor/laravel/framework/src/Illuminate/Auth/Middleware/Authenticate.php(41): Illuminate\Auth\Middleware\Authenticate->authenticate(Array) #3 /home/forge/xyz.com/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(151): Illuminate\Auth\Middleware\Authenticate->handle(Object(Illuminate\Http\Request), Object(Closure)) #4 /home/forge/xyz.com/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request)) #5 /home/forge/xyz.com/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php(67): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request)) #6 /home/forge/xyz.com/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(151): Illuminate\Foundation\Http\Middleware\VerifyCsrfToken->handle(Object(Illuminate\Http\Request), Object(Closure)) #7 /home/forge/xyz.com/

Code:
namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/login';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    public function logout()
    {
        $this->guard()->logout();

        return redirect()->route('login');
    }

}

A: Inside your Exception Handler (app/Exceptions/Handler.php), there's a property named $dontReport which contains the list of exceptions to not report.
/**
 * A list of the exception types that are not reported.
 *
 * @var array
 */
protected $dontReport = [
    //
];

Simply add the exception class to the array.
protected $dontReport = [
    \Illuminate\Auth\AuthenticationException::class
];


text:
Q: Error does not get caught I wrote a script that upload a xml file, look at the following code snippet:
open System.Xml
open System.IO
open System

type XmlErrorLoad =
    | Success of XmlDocument
    | FileNotFound of FileNotFoundException
    | OtherException of Exception

let doc (filename:string) =
    try
        let file = XmlDocument()
        file.Load(filename)
        Success file
    with
    | :? FileNotFoundException as ex -> FileNotFound ex
    | :? Exception as ex -> OtherException ex

let fileNotExists = doc("C:\Temp\ip2.xml")
match fileNotExists with
| Success s -> ()
| FileNotFound ex -> printfn "File not found: %s" ex.Message
| OtherException ex -> printfn "Exception: %s" ex.Message

In this case, ip2.xml file does not exist and it should throw an error FileNotFound and print on the screen.
"File not found: %s" ex.Message

But I've got the message
val fileNotExists : XmlErrorLoad =
  FileNotFound
    System.IO.FileNotFoundException: Could not find file 'C:\Temp\ip2.xml'.
File name: 'C:\Temp\ip2.xml'
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize)
   at System.Xml.XmlDownloadManager.GetStream(Uri uri, ICredentials credentials, IWebProxy proxy, RequestCachePolicy cachePolicy)
   at System.Xml.XmlUrlResolver.GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn)
   at System.Xml.XmlTextReaderImpl.OpenUrlDelegate(Object xmlResolver)
   at System.Threading.CompressedStack.runTryCode(Object userData)
   at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
   at System.Threading.CompressedStack.Run(CompressedStack compressedStack, ContextCallback callback, Object state)
   at System.Xml.XmlTextReaderImpl.OpenUrl()
   at System.Xml.XmlTextReaderImpl.Read()
   at System.Xml.XmlLoader.Load(XmlDocument doc, XmlReader reader, Boolean preserveWhitespace)
   at System.Xml.XmlDocument.Load(XmlReader reader)
   at System.Xml.XmlDocument.Load(String filename)
   at FSI_0004.doc(String filename) in D:\f#\samples\ip.fsx:line 20

A: I've tried your code as input on F# Interactive and got the desired message
File not found: Could not find file 'C:\Temp\ip2.xml'.

Besides the output F# Interactive lists all the values defined in the code, so I also got following printed:
type XmlErrorLoad =
  | Success of XmlDocument
  | FileNotFound of FileNotFoundException
  | OtherException of Exception
val doc : filename:string -> XmlErrorLoad
val fileNotExists : XmlErrorLoad =
  FileNotFound
    System.IO.FileNotFoundException: Could not find file 'C:\Temp\ip2.xml'.
File name: 'C:\Temp\ip2.xml'
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize)
   at System.Xml.XmlDownloadManager.GetStream(Uri uri, ICredentials credentials, IWebProxy proxy, RequestCachePolicy cachePolicy)
   at System.Xml.XmlUrlResolver.GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn)
   at System.Xml.XmlTextReaderImpl.OpenUrlDelegate(Object xmlResolver)
   at System.Threading.CompressedStack.runTryCode(Object userData)
   at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
   at System.Threading.CompressedStack.Run(CompressedStack compressedStack, ContextCallback callback, Object state)
   at System.Xml.XmlTextReaderImpl.OpenUrl()
   at System.Xml.XmlTextReaderImpl.Read()
   at System.Xml.XmlLoader.Load(XmlDocument doc, XmlReader reader, Boolean preserveWhitespace)
   at System.Xml.XmlDocument.Load(XmlReader reader)
   at System.Xml.XmlDocument.Load(String filename)
   at FSI_0003.doc(String filename)
val it : unit = ()

You get this output only in F# Interactive as part of REPL feedback. In a normal program this output wouldn't be produced.


text:
Q: logback value from web.xml I'm trying to take a value from spring profile set in web.xml. I've already encountered a question that solves my problem but the implementation of the solution to the problem does not seem to be working. That's are my source code:
web.xml:
<context-param>
    <param-name>spring.profiles.default</param-name>
    <param-value>local-jboss</param-value>
</context-param>

logback.xml:
<insertFromJNDI env-entry-name="java:comp/env/spring.profiles.default" as="spring.profiles.default" />

<appender name="STASH" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
    <destination>x.x.x.x:yyyy</destination>
    <encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">
        <providers>
            <mdc /> <!-- MDC variables on the Thread will be written as JSON fields -->
            <context /> <!-- Outputs entries from logback's context -->
            <version /> <!-- Logstash json format version, the @version field in the output -->
            <logLevel />
            <loggerName />
            <pattern>
                <pattern>
                {
                    "APP": "MyApp",
                    "PROFILE": "${spring.profiles.default}"
                }
                </pattern>
            </pattern>
            <threadName />
            <message />
            <logstashMarkers /> <!-- Useful so we can add extra information for specific log lines as Markers -->
            <arguments /> <!-- or through StructuredArguments -->
            <stackTrace />
        </providers>
    </encoder>
</appender>

Does anyone know how I get the value from my web.xml and put in logback.xml?

A: 1st Solution :
If you are on spring 3.1+ then those context params will available as env variable and in logback you can easily refer them like below :
<springProperty scope="context" name="fluentHost" source="myapp.fluentd.host"
        defaultValue="localhost"/>

source is the name of your key. Further Documentation.
2nd Solution :
You can use this as well where we will define context-param as spring property then refer the same in logback as 1st solution above.
@SpringBootApplication
class DemoApp extends SpringBootServletInitializer {
    private ServletContext servletContext;
    public static void main(String[] args){SpringApplication.run(DemoApp.class,args);}
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        builder = builder.properties("test.property:" + servletContext.getInitParameter("test.property"));
        return builder.sources(DemoApp.class);
    }
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        this.servletContext = servletContext;
        super.onStartup(servletContext);
    }
}

Hope this helps.


text:
Q: .htaccess mode_rewrite match percent symbol problem So i want to know how can i make it that if someone asks for the page: www.mydomain.com/%D7%90%D7%91%D7%90.php
he would get to the page: www.mydomain.com/D790D791D790.php (without the percentages) but his browser url will show the first page he asked for (with no redirection).
I've found out that the URI is escaping the % symbol to it's hex value %25 and because i don't have access to the httpd file i'm not able to switch on "noescape|NE".
So now i need to use mode_rewrite to match %25 and replace it with nothing, or even replace it with a dash but i have no clue how to make the regex, can someone help?


text:
Q: how to add a wait in time in a for ..of? I am building a code that allows me to wait for a promise to be resolved to advance to the next, I am also adding a separate time for each wait, but only the first loop is printed, if I remove the wait in seconds this works well.
in play code I get this error, in other editors I simply print the first loop
error: Infinity loop on line 8, char 6. You can increase loop timeout in settings.

https://playcode.io/309050?tabs=console&script.js&output
in the stackoverflow code editor if the code works but in my project or in another code editor they do not work

 const urls = [
      'https://jsonplaceholder.typicode.com/todos/1',
      'https://jsonplaceholder.typicode.com/todos/2',
      'https://jsonplaceholder.typicode.com/todos/3'
    ];

    async function getTodos() {
      for (const [idx, url] of urls.entries()) {
        const todo = await fetch(url);
        console.log(`Received Todo ${idx+1}:`, todo);
         await wait(1000)
      }

      console.log('Finished!');
    }

    getTodos();

    function wait(ms) {
      return new Promise(r => setTimeout(r, ms));
    }

A: Some online code playgrounds, like CodePen, have built-in infinite-loop detection. This is to prevent the UI from freezing in the event that you accidentally write an infinite loop while scratch coding. This is usually achieved by statically analyzing your code. Because of this, it cannot tell what your code actually does at runtime (and it may not be infinite at all). The best they can do is guess based on structure.
In your case, your code editor thinks that you're doing an infinite loop. There's probably settings in your editor to disable that.


text:
Q: order records of table by id in erlang I have this table person
-record(person, {id, firstname, lastname, phone}).

and it contains this values :
12  alen     dumas        97888888
15  franco   mocci      55522225
13  ali      othmani    44444449

I want to order this table by id
and it should became like this :
 12  alen     dumas        97888888
  13  ali      othmani    44444449
  15  franco   mocci      55522225

A: To order tuples stored in mnesia you need to either:

*

*create a table with type ordered_set (see option type in: mnesia:create_table) and then use mnesia:last or mnesia:dirty_last
or

*

*read all records and sort them outside of mnesia,

e.g.:
Select = [{#person{_ = '_'}, [], ['$_']}],
Sorted = lists:sort(mnesia:dirty_select(person, Select)),
erlang:hd(lists:reverse(Sorted)).

That will get all records, sort them as tuples (which should be enough considering the id is the first element in the record, if not use lists:sort/2 and specify the sorting function), then reverse the list and return the first element (in Erlang it's quicker to reverse and get the first element than return the last element of a list).


text:
Q: How to convert an image from 8-Bit to RGB in ImageJ2 using Java I'm trying to use ImageJ2 directly from Java to create a binarised image coming from an input image.
A somewhat working version of my code looks like this:
final File file = new File("input.png");

try {
    DefaultDataTypeService dataTypeService = new DefaultDataTypeService();
    Dataset dataset = imageJ.dataset().open(file.getAbsolutePath());
    Img inputImg = dataset.getImgPlus();

    PluginInfo pluginInfo = imageJ.plugin().getPlugin(Binarize.class);
    Binarize binarizeOp = (Binarize) pluginInfo.createInstance();
    binarizeOp.setContext(imageJ.getContext());
    binarizeOp.setChangeInput(true);
    binarizeOp.setFillMaskBackground(true);
    binarizeOp.setFillMaskForeground(true);
    binarizeOp.setInputData(dataset);
    binarizeOp.setInputMask(null);
    binarizeOp.setMaskColor(Binarize.WHITE);
    binarizeOp.setMaskPixels(Binarize.INSIDE);
    binarizeOp.setThresholdEachPlane(false);
    binarizeOp.setDefaultThresholdMethod();
    binarizeOp.run();

    dataset.rgbChange();
    DefaultDatasetService defaultDatasetService = new DefaultDatasetService();
    Img outputImg = dataset.getImgPlus();
    outputImg = outputImg.factory().imgFactory(new UnsignedByteType()).create(outputImg,new UnsignedByteType());
    Dataset outputDataset = defaultDatasetService.create(outputImg);
    imageJ.dataset().save(outputDataset,"input_binary.png");

} catch (IOException e) {
    e.printStackTrace();
} catch (InstantiableException e) {
    e.printStackTrace();
} catch (IncompatibleTypeException e) {
    e.printStackTrace();
}

Running this code I have the problem that "input_binary.png" will be completely black, a behaviour I can reproduce using the ImageJ client application.
What I need to do in the client is to change the image type from "8-bit Color" to "RGB-Color". But I can not figure out how to reproduce that in Java using the current version of the net.imagej library.
I know that it would be possible using the 1.x library but I would like to to it using the 2.x.
Any help would be greatly appreciated.

A: You're getting black images because of this:

outputImg = outputImg.factory().imgFactory(new UnsignedByteType()).create(outputImg,new UnsignedByteType());

Which is just copying the dimensionality of your source image, not its values.
A few other key points:

*

*It's best practice to have your Contextual objects (e.g. Services) derived from the Context instead of manually constructed.

*The Binarize command has a Dataset output so it's not necessary to go Dataset > ImgPlus > Dataset

*If you do want to write the dataset out you need to convert from the BitType output by Binarize to one that's supported.

See below for an example of running Binarize, getting the output, converting it and writing it out. Hope that helps!
public static void main(String... args) {
    final File file = new File("inpath.png");
    final File out = new File("outpath.png");

    // This is just sugar for the point of illustration.
    // The purpose here is just to have access to a Context
    ImageJ imagej = new ImageJ();

    // Cache the context for future use.
    Context context = imagej.getContext();

    try {
        // Use the context to get the services we want to ensure they are all
        // properly initialized.
        // If this was a Command these could all be @Parameters to be populated
        // automatically.
        DatasetService datasetService = context.getService(DatasetService.class);
        CommandService commandService = context.getService(CommandService.class);
        DatasetIOService datasetIOService =
            context.getService(DatasetIOService.class);

        Dataset input = datasetIOService.open(file.getAbsolutePath());

        // Start the command
        Future<CommandModule> future =
            commandService.run(Binarize.class, true, "inputData", input);

        // Get the command output
        Dataset binarized = (Dataset) future.get().getOutput("outputMask");

        // The output type is a binary image which, at the moment, needs to be
        // explicitly converted to something that can be written out.
        // Adapted from:
        // http://fiji.sc/ImgLib2_Examples#Example_2c_-_Generic_copying_of_image_data
        Img inputImg = input.getImgPlus().getImg();
        Img outputImg = binarized.getImgPlus().getImg();
        Img typedImg =
            inputImg.factory().create(inputImg, inputImg.firstElement());
        scale(outputImg, typedImg);

        Dataset output = datasetService.create(typedImg);

        // Save the output dataset
        datasetIOService.save(output, out.getAbsolutePath());
    }
    catch (IOException exc) {
        exc.printStackTrace();
    }
    catch (InterruptedException exc) {
        exc.printStackTrace();
    }
    catch (ExecutionException exc) {
        exc.printStackTrace();
    }
    finally {
        // Dispose of the context to shut down
        context.dispose();
    }

}

public static <T extends IntegerType<T>> void scale(
    final RandomAccessible<BitType> source, final IterableInterval<T> target)
{
    // create a cursor that automatically localizes itself on every move
    Cursor<T> targetCursor = target.localizingCursor();
    RandomAccess<BitType> sourceRandomAccess = source.randomAccess();
    // iterate over the input cursor
    while (targetCursor.hasNext()) {\
        // move input cursor forward
        targetCursor.fwd();
        // set the output cursor to the position of the input cursor
        sourceRandomAccess.setPosition(targetCursor);
        // set the value of this pixel of the output image
        BitType b = sourceRandomAccess.get();
        if (b.get()) {
            targetCursor.get().setOne();
        }
        else {
            targetCursor.get().setZero();
        }
    }
}


text:
Q: If $\sum_{k=1}^{\infty}x_k$ is conditionally convergent, prove that $\sum_{k=1}^{\infty}x_k^+ = \infty = \sum_{k=1}^{\infty}x_k^-$. If $\sum_{k=1}^{\infty}x_k$ is conditionally convergent, prove that $\sum_{k=1}^{\infty}x_k^+ = \infty = \sum_{k=1}^{\infty}x_k^-$ where $x_k^+$ are the positive terms and $x_k^-$ are the absolute values of negative terms of $x_k$.

Proof: Suppose $x_k$ is only conditionally summable, this means that
  the sequence $s_n = \sum\limits_{k=1}^{n}|x_k|$ is not convergent.
  Note that $s_n$ is a monotone increasing sequence that is not
  convergent, hence it must be unbounded. But $\sigma_n^+ =
 \sum\limits_{k=1}^{n}x_k^+$ and $\sigma_n^- =
 \sum\limits_{k=1}^{n}x_k^-$ are all subsequences of $s_n$, and they
  are monotone increasing as well.
Thus, they must me also unbounded and
   $\sum\limits_{k=1}^{\infty}x_k^+ = \infty =
 \sum\limits_{k=1}^{\infty}x_k^-$. $\blacksquare$

EDIT: Here's my another attempt at proving this:

Proof: Note that $s_n = \sum_{k=1}^{n}|x_k|$ is divergent to $\infty$.
  But $s_n' = \sum_{k=1}^{n}x_k$ converges to some finite number
   $L\in\mathbb{R}$. Let $\sigma_n^+ =  \sum\limits_{k=1}^{n}x_k^+$ and
   $\sigma_n^- =  \sum\limits_{k=1}^{n}x_k^-$. Then, $s_n = \sigma_n^+ +
 \sigma_n^- $ and $s_n' = \sigma_n^+ - \sigma_n^-$. Then, $s_n+s_n' =
 2\sigma_n^+$ must diverge to infinity as $n\to\infty$ because $s_n$
  diverges to $\infty$ and $s_n'$ converge to $L$. Any finite number
  added to infinity is also infinity. This implies that $2\sigma_n^+$
  must diverge as well as  $\sigma_n^+$.
Likewise, $s_n'-s_n = -2\sigma_n^-$ must diverge to $-\infty.$ And
  this implies $-2\sigma_n^-$ diverge to $-\infty$ and $\sigma_n^-$
  diverges to $\infty$. $\blacksquare$

A: Notice $x_k^{+} = x_k$ if $x_k \geq 0$, and $x_k^{+}=0$ otherwise. Notice $x_k^{-} = -x_k$ if $x_k \leq 0$, and $x_k^{-}=0$ otherwise.
Put
$$s_n = \sum_{k=1}^{n} |x_k|, \quad \sigma_n = \sum_{k=1}^{n} x_k, \quad \sigma_n^{+} = \sum_{k=1}^{n} x_k^{+}, \quad \sigma_n^{-} = \sum_{k=1}^{n} x_k^{-}.
$$
Note $$\sigma_n^{+} = \frac{1}{2}s_n + \frac{1}{2}\sigma_n.$$ Since $s_n$ diverges and $\sigma_n$ converges, we must have that $\sigma_n^{+}$ diverges. Moreover, as $\sigma_n^{+}$ is increasing, $\sigma_n^{+} \rightarrow \infty$.
Likewise, $\sigma_n^{-} = \frac{1}{2}s_n - \frac{1}{2}\sigma_n$ leads to $\sigma_n^{-} \rightarrow \infty$.


text:
Q: Kube-proxy pod not starting v1.21.3 I have delete kube-proxy pod from my master nodes to get the new kube-proxy configmap values, when I reboot the node still kube-proxy is not coming up ?
How to start the kube-proxy?
# crictl ps
CONTAINER ID        IMAGE               CREATED             STATE               NAME                ATTEMPT             POD ID
19376bdbc55eb       c4d75af7e098e       17 minutes ago      Running             calico-node         2                   b4fb351577dd4
24253bf076500       6be0dc1302e30       17 minutes ago      Running             kube-scheduler      4                   182f9024a6957
57c5c9dec4ad2       3d174f00aa39e       17 minutes ago      Running             kube-apiserver      3                   e549a2bad6a02

Cluster information:
Kubernetes version: v1.21.3
Cloud being used: (put bare-metal if not on a public cloud)
Installation method: bare-metal
Host OS: CentOS Stream 8
CNI and version: Calico
CRI and version: containerd

A: Due to ClusterCIDR IP change kube-controller-manager was in  CrashLoopBackOff  status. once I updated the old IP in ClusterCIDR,  kube-controller-manager pod started, then kube-proxy came up.


text:
Q: Eclipse: multiple monitors / positioning of dialogs I'm trying to setup Eclipse for two monitors (a 1600x1200). I have one big desktop spanning over both monitors. Eclipse places some dialogs (CTRL+3) exactly centered on my desktop, this means that one half of the dialog is on the left monitor, the other one on the right one.
When I move the dialog, close it, and open it again, the last position isn't remembered by Eclipse. Any way around this issue? Or is there a plugin, which helps to open all dialogs not centered, but placed with an offset to the left / right?
Thanks.

A: It depends on what exact dialogs you are talking about.
Dialogs can remember their last position since Eclipse3.2: bug 111530 and bug 33550.
Different dialogs now remember their positions: bug 108801:

*

*Bug #111650 - JDT dialogs

*Bug #111652 - Search dialog

*Bug #111653 - Text dialogs
If other dialogs don't work correctly, a new bug report is in order.

Regarding the "Quick Access" (CTRL+3) dialog the OP is actually referring to, he comments:

Finally found the simple solution:
In the upper right corner is a small triangle, which opens a a context menu, with the desired entry "remember position".

A: Read this question:
Any tips on how to organize Eclipse environment on multiple monitors?


text:
Q: tens of thousands meaning In this article, I saw the phrase tens of thousands. Normally, I understand tens of thousands means some number between 10.000 to 90.000. But in this situation, I don't really understand it:

Oganessian reported his discovery to Flerov on his return. At first his mentor appeared dismissive – the usual fate for a successful guerrilla. It was only when the president of the USSR Academy of Sciences visited Jinr that Flerov pointed to Oganessian and said 'He produces transuranes in their tens of thousands.' The president, realising what this meant, gave Oganessian a kiss on his cheek.

What does tens of thousands mean in this situation?
Please explain to me.
Thanks

A: The answer is actually in the article itself, and the meaning is just the ordinary one.
The fragment in the question of course begs the question whether tens of thousands refers to separate elements (in which case we would have a hyperbole, because there are not even a hundred transurane elements) or to the amount of transurane material that was produced.
The article says, in the paragraph before the one in the question (emphasis mine):

When Flerov went on an expedition to Siberia, Oganessian seized his chance. Testing his theory, he fired argon-40 at lead-208 to make fermium-244, predicting it would shed four neutrons and create an isotope with a half-life of only 4ms. The new technique produced fermium-246, losing only two neutrons, with a half-life of 1.1s. The resulting yield was 10,000 times greater than he imagined.

So Oganessian managed to produce 10,000 times more fermium than other techniques.
All said, the phrasing is certainly non-scientific and imprecise. Since it is a reported quote, we cannot put all the blame on the author. The reported reaction to the quote indicates that its meaning was well understood at the time, though, even if the wording is somewhat imprecise.

A: it means a lot TFD or even a bazillion!

a lot or lots Informal  A large extent, amount, or number

Vague numbers like tens of thousands, hundreds of thousands and tens of millions are not scientific. They typically are examples of hyperbole. Vague, intentionally vague, sensational or exaggerations, they make a generalized statement about the extent, amount or numbers. Word Counter Blog
As in:

There must be hundreds of thousands of bacteria living on that
  decaying food!

No more like a gazillion!

A:
Normally, I understand tens of thousands means some number between 10.000 to 90.000.

10s of 1000s can also include such quantities over 90.000 as 100.000, 110.000, 500.000, 1.100.000, and up--as long as they're divisible by 10.000.
As an analog, consider 1000s. You can raise 1000s of dollars, which can mean any quantity divisible by 1000, even $1.000.000.000.000. Such a high number is probably not in mind when someone uses the phrase 1000s but it is not excluded linguistically and it is also mathematically valid. The same parameters apply to 10s of 1000s except that the quantity must be divisible by 10.000, if we stick with numbers with no remainders (i.e., even numbers).


text:
Q: How to stop "Opto Host" taking over a port (Linux) I have added two rules in firewalld, using the following commands:
firewall-cmd --zone=public --add-port=22005/tcp --permanent
firewall-cmd --zone=public --add-port=22003/udp --permanent
After reloading firewalld, I took a look at iptables, with iptables -L
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:optohost005 ctstate NEW
ACCEPT     udp  --  anywhere             anywhere             udp dpt:optohost003 ctstate NEW

What is optohost, and why does it replace 22? I can't find much about this anywhere on Google. It only seems to happen for these two IPs (22005/22003)
I am running CentOS Linux release 7.3.1611, 3.10.0-514.26.2.el7.x86_64
firewalld 0.4.3.2
Update:
After some more searching, I found this:
http://sysconfcollect.sourceforge.net/examples/scc.docker_centos7.html
optohost003     22003/tcp               # Opto Host Port 3
optohost003     22003/udp               # Opto Host Port 3
optohost005     22005/tcp               # Opto Host Port 5
optohost005     22005/udp               # Opto Host Port 5

This is documentation for "docker", more specifically the contents of /etc/services which I checked manually on my machine and the lines exist. I'm not exactly sure what "docker" does but I know it's something to do with my network.. If I check ifconfig, sure enough it's there:
docker0: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
    inet 172.17.0.1  netmask 255.255.0.0  broadcast 0.0.0.0
    ether 02:42:d2:8b:6d:b6  txqueuelen 0  (Ethernet)
    RX packets 0  bytes 0 (0.0 B)
    RX errors 0  dropped 0  overruns 0  frame 0
    TX packets 0  bytes 0 (0.0 B)
    TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

What I gather from this is that docker has some services running on those ports (22005/22003) and it's taking over (?)
I need these ports for a game server that I run. Any idea on how to stop it from "taking over" those ports?
Update #2: Removing those lines from /etc/services makes optohost disappear when looking up the ports with iptables -L, and the ports are displayed correctly. However I am not entirely sure what effect removing those lines has, and if it has any actual effect at all apart from simply being a label or name.


text:
Q: Python 2.7: How to convert unicode escapes in a string into actual utf-8 characters I use python 2.7 and I'm receiving a string from a server (not in unicode!).
Inside that string I find text with unicode escape sequences. For example like this:
\u00b2<\a>

How do I convert those \uxxxx - back to utf-8? The answers I found were either dealing with &# or required eval() which is too slow for my purposes. I need a universal solution for any text containing such sequenes.
Edit:
<\a> is a typo but I want a tolerance against such typos as well. There should only be reaction to \u
The example text is meant in proper python syntax like this:
"\\u00b2<\\a>"

The desired output is in proper python syntax
"\xc2\xb2<\\a>"

A: Try
>>> s = "\\u00b2<\\a>"
>>> s.decode("raw_unicode_escape")
u'\xb2<\\a>'

And then you can encode to utf8 as usual.

A: Python does contain some special string codecs for cases like this.
In this case, if there are no other characters outside the 32-127 range, you can safely decode your byte-string using the "unicode_escape" codec to have a proper Unicode text object in Python.
(On which your program should be performing all textual operations) -
Whenever you are outputting that text again, you convert it to utf-8 as usual:
rawtext = r"""\u00b2<\a>"""
text = rawtext.decode("unicode_escape")
# Text operations go here
...
output_text = text.encode("utf-8")

If there are othe bytes outside the 32-127 range, the unicode_escape codec
assumes them to be in the latin1 encoding. So if your response mixes utf-8 and these \uXXXX sequences you have to:

*

*decode the original string using utf-8

*encode back to latin1

*decode using "unicode_escape"

*work on the text

*encode back to utf-8


text:
Q: Session variable value in jsp not getting changed <html>
<script type="text/javascript">
    function logged()
    {
        <% session.setAttribute("logtype", "hire"); %>
        var x=<%=session.getAttribute("loggedin")%>;
        if(x===true)
        {
            window.location="home.jsp";
            return false;
        }
        else if(x===false)
        {
            return true;
        }
    }
</script>
<body>
   <form method="post" action="login.jsp" onsubmit="return logged()">
      <input type="submit" value="HIRE"/>
   </form>
   <form method="post" action="displayTasks.jsp" onsubmit="<% session.setAttribute("logtype", "work"); %>">
      <input type="submit" value="WORK"/>
   </form>
</body>
</html>

My session variable "logtype" is creating a problem. It stays as "WORK" no matter whatever I click. What am I doing wrong?

A: The problem is that you're setting the session attribute twice in your page, so when the JSP generated the view, it will execute all your scriptlets. Basically, your JSP is doing this:
session.setAttribute("logtype", "hire");
//later...
session.setAttribute("logtype", "work");

Note that all the scriptlet code is executed when rendering the view (in simple words, when translating the JSP to HTML).
As stated by David Newton in comments the problem is Not "where", "when". Since it looks you want to change the session attribute in the form POST, this should be handled in your action POST request. And again, since you're doing all in JSP, this should be in your displayTasks.jsp page:
session.setAttribute("logtype", "work");

And remove this line from your current page (whatever name it has).

Not directly related to the current problem, but you have serious problems developing Java web applications. First thing to know, Java runs at server (as explained before, when rendering the view) while JavaScript runs at client browser, so it's not a good idea to make both interact at the same level directly. After realizing this, you must avoid scriptlets usage as is heavily explained here: How to avoid Java code in JSP files? and then move to EL and JSTL.
Now, you will realize that there are something else wrong with your current development approach. You're handling the GET and POST requests directly using JSPs. If you're in learning phase, I strongly discourage to do this and use Servlets instead for server side data processing. Know with all these tools, your development willbe accordingly to the MVC pattern, I provide you a basic login implementes in JSP + Servlet example: Creating a user object from login parameters.
Then after earning more experience in web development, you would want to try ajax. Here's a good tutorial on JSP, Servlets and Ajax: How to use Servlets and Ajax?


text:
Q: Load SVG's through image tag and be able to change it's color without fetching inline SVG with AJAX? For the company I work at, I am required to load in SVG's for a web application. The SVG's are in components that consist of HTML code. These components are loaded into a bigger HTML structure. Each component can have a different SVG icon and it must be easy to change. It's color must also be able to be changed through CSS.
I can not write down inline SVG, because administrators must be able to easily change the image (e.g.: from https://example.com/svg/potato.svg to https://example.com/svg/carrot.svg. I can also not use any AJAX/fetch related functions to fetch the inline SVG, as the component must be able to run perfectly on the test domain, which will trigger CORS errors. Changing the CORS settings is not an option for this application.
My only option left is to load all SVG's (10 at the moment, but could scale anytime) and to look for the right one, depending on the user inputted svg name. I could make the user call a JS function like this: showSVG('carrot');, but I'd rather not load all SVG's for the sake of loadtime.
Some answers tell you to use CSS filter, but that requires the user to probably look up the correct filters for the correct hex code. I'd just like the user to be able to write the CSS like this: fill: #eee;
I also checked out CSS mask, but that has ok-ish support, so I'd rather not use that right now.
Here is an example of what I'd like to achieve:
HTML

Test component

CSS
.img {
  fill: yellow;
}

I'm open for the hackiest Javascript solutions, as long as they are available for every browser.

A: Modern browsers can do this without JS by making use of the SVG <use> element. However, I recommend using a JS shim like svgxuse, for older browsers, including IE11.
<!DOCTYPE html>

<meta charset="utf-8">
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1">

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="720" height="90">
<image xlink:href="external-svg-example.svg" width="720" height="90"/>
</svg>

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="720" height="90" class="fill-blue">
<use xlink:href="external-svg-example.svg#g1"/>
</svg>

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="720" height="90" class="fill-green">
<use xlink:href="external-svg-example.svg#g1"/>
</svg>

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="720" height="90" class="fill-orange">
<use xlink:href="external-svg-example.svg#g1"/>
</svg>

<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 720 90" width="720" height="90">

<g id="g1">
<text y="70" x="28">This is Our Test Text</text>
</g>
</svg>


text:
Q: Where are Windows 10 privacy settings stored in the registry? Where are privacy settings stored in the registry? Windows 10 resets them after every update for me... I would like to make a registry file that turns them to my preferences.

A: According to the article
Registry Keys for Windows 10 Application Privacy Settings,
the registry keys below each contains a REG_SZ item named Value that is either
Allow or Deny.
Location:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\location
Webcam:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\webcam
Microphone:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\microphone
Notifications:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\userNotificationListener
Motion:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\activity
Account Info:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\userAccountInformation
Contacts:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\contacts
Calendar:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\appointments
Call History:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\phoneCallHistory
Email:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\email
Tasks:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\userDataTasks
Messaging:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\chat
Radios:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\radios
Other Devices:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\bluetoothSync
Background Apps:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Search
App Diagnostics:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\appDiagnostics
Documents:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\documentsLibrary
Pictures:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\picturesLibrary
Videos:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\videosLibrary
File Systems:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\broadFileSystemAccess
The article
Windows 10 privacy settings
adds these settings:
Sync info with wireless devices:
HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\DeviceAccess\Global\LooselyCoupled
Improve typing:
HKEY_CURRENT_USER\SOFTWARE\Microsoft\Input\TIPC
Value name: Enabled
Value data: 0 or 1

A: Based on a script by Chris Wellons, below is a cmd batch script lessmal.bat I put together (the latest version at https://gitlab.com/0mid/dotfiles/-/blob/master/lessmal.bat), which automates disabling a few of the numerous malicious features (and some nuisances) of Windows.
The aim of this script is NOT to promote/encourage the use of the proprietary (non-free) Windows operating system, which does not respect the users' freedoms (https://www.gnu.org/philosophy/free-sw.html). The hope is that this script makes Windows negligibly less malicious for those who cannot immediately move to a free/libre operating system (such as a GNU/Linux distribution) and are forced to use Windows.
Malicious features are objective; "misfeatures" (e.g., TaskbarAnimations) could be subjective, so feel free to pick and choose which one of the "misfeatures" you'd like disabled.
lessmal.bat as of now; run in a cmd console (no Admin needed):
rem A one-shot, first-time Windows configuration script that disables some
rem Windows mal/misfeatures [based on Chris Wellons'].

setlocal

set key=HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer
reg add "%key%" /f /v AltTabSettings              /t REG_DWORD /d 0
reg add "%key%" /f /v DisableSearchBoxSuggestions /t REG_DWORD /d 1
set key=HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced
reg add "%key%" /f /v TaskbarGlomLevel          /t REG_DWORD /d 2
reg add "%key%" /f /v HideFileExt               /t REG_DWORD /d 0
reg add "%key%" /f /v ShowCortanaButton         /t REG_DWORD /d 0
reg add "%key%" /f /v ShowTaskViewButton        /t REG_DWORD /d 0
reg add "%key%" /f /v StoreAppsOnTaskbar        /t REG_DWORD /d 0
reg add "%key%" /f /v MultiTaskingAltTabFilter  /t REG_DWORD /d 3
reg add "%key%" /f /v JointResize               /t REG_DWORD /d 0
reg add "%key%" /f /v SnapFill                  /t REG_DWORD /d 0
reg add "%key%" /f /v SnapAssist                /t REG_DWORD /d 0
reg add "%key%" /f /v TaskbarAnimations         /t REG_DWORD /d 0
set key=HKCU\Software\Microsoft\Windows\CurrentVersion\Feeds
reg add "%key%" /f /v ShellFeedsTaskbarViewMode /t REG_DWORD /d 2
set key=HKCU\Software\Microsoft\Windows\CurrentVersion\Search
reg add "%key%" /f /v SearchboxTaskbarMode      /t REG_DWORD /d 0
reg add "%key%" /f /v BingSearchEnabled         /t REG_DWORD /d 0
reg add "%key%" /f /v AllowSearchToUseLocation  /t REG_DWORD /d 0
reg add "%key%" /f /v CortanaConsent            /t REG_DWORD /d 0
set key=HKCU\Control Panel\Desktop
reg add "%key%" /f /v CursorBlinkRate           /t REG_SZ    /d -1
reg add "%key%" /f /v MenuShowDelay             /t REG_SZ    /d 0
reg add "%key%" /f /v UserPreferencesMask       /t REG_BINARY /d 9012078010000000
set key=HKCU\Control Panel\Desktop\WindowMetrics
reg add "%key%" /f /v MinAnimate                /t REG_SZ    /d 0
set key=HKCU\Control Panel\Accessibility
reg add "%key%" /f /v DynamicScrollbars         /t REG_DWORD /d 0
set key=HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Taskband
reg delete "%key%" /f /v Favorites
set key=HKCU\Software\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore
reg add "%key%"\location                 /f /v Value /t REG_SZ /d 0
reg add "%key%"\webcam                   /f /v Value /t REG_SZ /d 0
reg add "%key%"\microphone               /f /v Value /t REG_SZ /d 0
reg add "%key%"\userNotificationListener /f /v Value /t REG_SZ /d 0
reg add "%key%"\activity                 /f /v Value /t REG_SZ /d 0
reg add "%key%"\userAccountInformation   /f /v Value /t REG_SZ /d 0
reg add "%key%"\contacts                 /f /v Value /t REG_SZ /d 0
reg add "%key%"\appointments             /f /v Value /t REG_SZ /d 0
reg add "%key%"\phoneCallHistory         /f /v Value /t REG_SZ /d 0
reg add "%key%"\email                    /f /v Value /t REG_SZ /d 0
reg add "%key%"\userDataTasks            /f /v Value /t REG_SZ /d 0
reg add "%key%"\chat                     /f /v Value /t REG_SZ /d 0
reg add "%key%"\radios                   /f /v Value /t REG_SZ /d 0
reg add "%key%"\bluetoothSync            /f /v Value /t REG_SZ /d 0
reg add "%key%"\appDiagnostics           /f /v Value /t REG_SZ /d 0
reg add "%key%"\documentsLibrary         /f /v Value /t REG_SZ /d 0
reg add "%key%"\picturesLibrary          /f /v Value /t REG_SZ /d 0
reg add "%key%"\videosLibrary            /f /v Value /t REG_SZ /d 0
reg add "%key%"\broadFileSystemAccess    /f /v Value /t REG_SZ /d 0
set "key=HKCU\Control Panel\International\User Profile"
reg add "%key%"                          /f /v HttpAcceptLanguageOptOut /t REG_DWORD /d 1
set "key=HKCU\Software\Microsoft\Windows\CurrentVersion\AdvertisingInfo"
reg delete "%key%"                       /f /va
reg add "%key%"                          /f /v Enabled /t REG_DWORD /d 0
set "key=HKCU\SOFTWARE\Microsoft\Internet Explorer\International"
set "val=AcceptLanguage"
reg query "%key%" /v "%val%" 2>nul && (
reg delete "%key%"                       /f /v "%val%"
)

rem Reload
taskkill /f /im explorer.exe
start explorer.exe

And here is lessmal-more.bat, which needs to be run an Admin cmd, to disable a few more malicious features:
@echo off
setlocal

rem Hack to check if run by Admin [https://stackoverflow.com/a/16285248].
net session >nul 2>&1 || (echo This script requires Admin.&goto :eof)

rem Yes, this 'HKCU' key needs Admin!
set "key=HKCU\Software\Policies\Microsoft\Windows\DataCollection"
reg delete "%key%"                       /f /va

set "key=HKLM\Software\Policies\Microsoft\Windows\DataCollection"
reg add "%key%"\AllowDesktopAnalyticsProcessing             /f /v Value /t REG_DWORD /d 0
reg add "%key%"\LimitEnhancedDiagnosticDataWindowsAnalytics /f /v Value /t REG_DWORD /d 1
reg add "%key%"\AllowTelemetry                              /f /v Value /t REG_DWORD /d 0
reg add "%key%"\AllowDeviceNameInTelemetry                  /f /v Value /t REG_DWORD /d 0
reg add "%key%"\DisableTelemetryOptInChangeNotification     /f /v Value /t REG_DWORD /d 0
reg add "%key%"\AllowWUfBCloudProcessing                    /f /v Value /t REG_DWORD /d 0
reg add "%key%"\AllowUpdateComplianceProcessing             /f /v Value /t REG_DWORD /d 0
reg add "%key%"\DisableTelemetryOptInSettingsUx             /f /v Value /t REG_DWORD /d 0

set "key=HKLM\Software\Policies\Microsoft\Windows\Personalization"
reg add "%key%"\NoChangingLockScreen                        /f /v Value /t REG_DWORD /d 0


text:
Q: I want to join two data frames one with a year range and the other with a year I have two data frames that look like this
data1<-data.frame(name=c("Jessica_Smith","John_Smith","John_Smith") ,
max_year=c(2000,1989,2005),
min_year=c(1990,1989,2001))

data2<-data.frame(name=c("Jessica_Smith","John_Smith","John_Smith") ,
year_of_birth=c(1995,1989,2002),unique_id=c("aby37","nf93","fnd34"))

I would like to merge the data frames such that for each person in data1 I have a unique_id. If possible I would also like to get the nearest integer match for those for whom there is no overlap. To clarify I can't just left_join on name because some entries have the same name but different dates of birth.
I'm relatively new to R so I don't even really know where to begin.
Much appreciated!

A: With data.table you can to non-equal joins:
(added some extra columns and a name with no matches to example)
library(data.table)
data1<-data.table(name=c("Jessica_Smith","John_Smith","John_Smith", "Jackson_Brown") ,
                  max_year=c(2000,1989,2005,2020),
                  min_year=c(1990,1989,2001,1990),
                  extra_col1=c('a', 'b', 'c', 'd'))

data2<-data.table(name=c("Jessica_Smith","John_Smith","John_Smith") ,
                  year_of_birth=c(1995,1989,2002),
                  unique_id=c("aby37","nf93","fnd34"),
                  extra_col2=1:3)

data2[data1, .(name, year_of_birth = x.year_of_birth, unique_id,
               extra_col1, extra_col2),
      on = .(name, year_of_birth >= min_year, year_of_birth <= max_year)]

            name year_of_birth unique_id extra_col1 extra_col2
1: Jessica_Smith          1995     aby37          a          1
2:    John_Smith          1989      nf93          b          2
3:    John_Smith          2002     fnd34          c          3
4: Jackson_Brown            NA      <NA>          d         NA

I think it's better to list all the column names you want to include in the result.
One difficulty with with the non-equal joins is the default renaming of "matching" columns.  The columns match the non-equal criteria, but they are not the same.  This is why I specified x.year_of_birth (you can use x. or i. to pick which data.table the column comes from in x[i]).
Here is the result with no columns selected (which normally gives you all columns in a join):
data2[data1,
      on = .(name, year_of_birth >= min_year, year_of_birth <= max_year)]

            name year_of_birth unique_id extra_col2 year_of_birth.1 extra_col1
1: Jessica_Smith          1990     aby37          1            2000          a
2:    John_Smith          1989      nf93          2            1989          b
3:    John_Smith          2001     fnd34          3            2005          c
4: Jackson_Brown          1990      <NA>         NA            2020          d

Notice that year_of_birth here is really min_year, and year_of_birth.1 is really max_year.  So this is confusing and data2$year_of_birth is not included because it's considered a "matched" column that doesn't need to be kept.

A: You may try,
data1 %>%
  left_join(data2, by = "name") %>%
  rowwise %>%
  mutate(year_key = min_year <= year_of_birth && year_of_birth <= max_year) %>%
  filter(year_key == TRUE) %>%
  select(-year_key)

  name          max_year min_year year_of_birth unique_id
  <chr>            <dbl>    <dbl>         <dbl> <chr>
1 Jessica_Smith     2000     1990          1995 aby37
2 John_Smith        1989     1989          1989 nf93
3 John_Smith        2005     2001          2002 fnd34


text:
Q: Split table to small Python I need to split big table to small table and write it to csv.
used_at                                    4                  5                      6
address                          10ruslake.ru 1c.ru    vk.com  yandex.ru  youtube.com  facebook.com
ID
0025977ab2998580d4559af34cc66a4e          0.0   0.0      152      465          45           56
00c651e018cbcc8fe7aa57492445c7a2          0.0   0.0      23       213          354          44
0120bc30e78ba5582617a9f3d6dfd8ca          0.0   0.0      0        100          109          0

I need write to the first table all means, where used_at = 4, to second used_at = 5 etc.
I want to get the First table
used_at                                    4
address                          10ruslake.ru 1c.ru
ID
0025977ab2998580d4559af34cc66a4e          0.0   0.0
00c651e018cbcc8fe7aa57492445c7a2          0.0   0.0
0120bc30e78ba5582617a9f3d6dfd8ca          0.0   0.0

Second
used_at                                        5
address                                 vk.com    yandex.ru
ID
0025977ab2998580d4559af34cc66a4e          152      465
00c651e018cbcc8fe7aa57492445c7a2          23       213
0120bc30e78ba5582617a9f3d6dfd8ca          0        100

And also to used_at = 6

A: I think you can use groupby with dictionary comprehension:
dfs = {i: g for i,g in df.groupby(axis=1, level=0)}

print dfs['4']
                                            4
                                 10ruslake.ru 1c.ru
0025977ab2998580d4559af34cc66a4e          0.0   0.0
00c651e018cbcc8fe7aa57492445c7a2          0.0   0.0
0120bc30e78ba5582617a9f3d6dfd8ca          0.0   0.0

print dfs['5']
                                      5
                                 vk.com yandex.ru
0025977ab2998580d4559af34cc66a4e    152       465
00c651e018cbcc8fe7aa57492445c7a2     23       213
0120bc30e78ba5582617a9f3d6dfd8ca      0       100

print dfs['6']
                                           6
                                 youtube.com facebook.com
0025977ab2998580d4559af34cc66a4e          45           56
00c651e018cbcc8fe7aa57492445c7a2         354           44
0120bc30e78ba5582617a9f3d6dfd8ca         109            0

If 4, 5 and 6 are not strings, use print dfs[4]...
EDIT:
If you need store groups to list:
dfs = [g for i, g in df.groupby(axis=1, level=0)]

print dfs[0]
used_at                                     4
address                          10ruslake.ru 1c.ru
ID
0025977ab2998580d4559af34cc66a4e          0.0   0.0
00c651e018cbcc8fe7aa57492445c7a2          0.0   0.0
0120bc30e78ba5582617a9f3d6dfd8ca          0.0   0.0

print dfs[1]
used_at                               5
address                          vk.com yandex.ru
ID
0025977ab2998580d4559af34cc66a4e    152       465
00c651e018cbcc8fe7aa57492445c7a2     23       213
0120bc30e78ba5582617a9f3d6dfd8ca      0       100

print dfs[2]
used_at                                    6
address                          youtube.com facebook.com
ID
0025977ab2998580d4559af34cc66a4e          45           56
00c651e018cbcc8fe7aa57492445c7a2         354           44
0120bc30e78ba5582617a9f3d6dfd8ca         109            0


text:
Q: How to remove or hide Component Tray from End-User ? XtraReports Winforms Devexpress? I want to hide or remove this component tray from end-user. How to complete this task.

A: I agree with @DmitryG
Code from How to: Hide the Component Tray from End-Users in the Report Designer
should work
using System;
using System.Windows.Forms;
using DevExpress.XtraReports.Design;
using DevExpress.XtraReports.UserDesigner;
// ...

private void button1_Click(object sender, EventArgs e) {
    // Create an End-User Designer form.
    XRDesignForm designForm = new XRDesignForm();

    // Handle the DesignPanelLoaded event.
    designForm.DesignMdiController.DesignPanelLoaded +=
        new DesignerLoadedEventHandler(DesignMdiController_DesignPanelLoaded);

    // Load a report into the Designer.
    designForm.OpenReport(new XtraReport1());

    // Show the End-User Designer form, modally.
    designForm.ShowDialog();
}

// List the components in the Report Explorer, instead of the Component Tray.
void DesignMdiController_DesignPanelLoaded(object sender, DesignerLoadedEventArgs e) {
    ((XRDesignPanel)sender).ComponentVisibility = ComponentVisibility.ComponentTray;
}

A: Have you tried to read documentation or contact DevExpress Support?
Create an End-User Reporting Application - This document lists examples for creating and customizing end-user reporting applications on various platforms.
Example:
How to: Hide the Component Tray from End-Users in the Report Designer


text:
Q: .htaccess RewriteRule Problem this rewriterule only rewrite level.php and when try
localhost/a/b/115-aaa.html send all requests to level.php but
localhost/a/b/ is work
why ?
RewriteEngine On
RewriteRule ^(.*)\/(.*)-(.*).html$ page.php?page=$1&a=$2&b=$3 [QSA]
RewriteRule ^(.*)$ level.php?q=$1 [QSA]

A: If your first rule matches it goes to page.php?page=foo&a=bar&b=123 . This will match a second time against your rules and the second rule match. You can avoid this by adding following lines to your .htacces file.
RewriteEngine On
RewriteRule ^([a-zA-Z0-9]+)\/([a-zA-Z0-9]+)\/([0-9]+)\-([a-zA-Z0-9]+)\.html$ page.php?page=$1&a=$2&b=$3 [L]
#Prevent the last rule to be applied to page.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ level.php?q=$1 [L]


text:
Q: HTML video tag not working in iOS or iPadOS irrespective of any browser

  <video preload="auto" id="videoId-7" class="video-player" width="300" height="200" poster="">
    <source src="http://local-ub/media/sparsh/video_gallery/I_Am_Attindas_Revised_1_.mp4" type="video/mp4">
  </video>

I am using a html video tag in my project and the video is available in all the browsers but it is coming as white space in my iPhone and iPad device irrespective of the browser. When I try to use embed instead of source the video is not working in any of the desktop or mobile devices

A: playasinline, controls and the right mime-type definition in video tags on iOS devices are a must
If you got a video player showing but it doesn't play the video, check if the server is serving the content right, as iOS is very concious about how it is getting data over its data connection.


text:
Q: If you answer your own question, wait two days to accept, but if someone else answers it, wait only a few minutes I asked a question on SO that, with the help of others and my own tinkering, I was able to fix myself.  When I "answered my own question," I was told I had to wait two days before accepting it.
This didn't make much sense to me since you only have to wait a few minutes to accept someone else's answer.
I read this: Why must I wait 2 days before accepting my own answer?
I noticed this in Jeff Atwood's answer:

Wait 48 hours. You must wait 2 days from the time you originally asked
  your question before you can accept your own answer. This gives other
  users a chance to answer the question in good faith, and earn the
  accepted answer.

I don't understand why I would want other users to continue to answer my question "in good faith," seemingly only to gain reputation, when I have already found the answer myself.  Could someone please explain this?

A:
I don't understand why I would want other users to continue to answer my question "in good faith," seemingly only to gain reputation, when I have already found the answer myself. Could someone please explain this?

Although you may have solved your problem, we want to give a fair chance to other people to provide a better answer, one that will benefit the wider community, not just you. It's not uncommon for later great answers to get more up votes than the accepted one, a sign that they were more helpful to more people. And I've seen one instance where the accepted answer was heavily down voted, while every other answer was up voted.
Accepting an answer means that one person, you, found it helpful. Stack Overflow, and Stack Exchange in general, is more tuned towards the community at large than any individual. Wait a couple of days, it's not that long a wait, especially if a great answer appears.


text:
Q: Proof that $e^x$ is a transcendental function of $x$? Let a function $f(x)$ be algebraic if it satisfies an equation of the form $$c_n(x)(f(x))^n + c_{n-1}(x)(f(x))^{n-1} + \cdots + c_0(x)=0,$$ for $c_k(x)$ rational functions of $x$, and let $f$ be called transcendental if it is not algebraic. Is it possible to use this definition directly to show that $e^x$ is transcendental?
One way I have been considering for any complex number is this:
Let $x_0\in\mathbb{C}$ and $x_n=x_0+2\pi i n$, where $n\in\mathbb{Z}$. Hence $x_n\neq x_m$ for all $n\neq m$, but we do have $e^{x_n}=e^{x_m}$ for all $n,m\in\mathbb{Z}$ (since $e^{2\pi i n} = 1$ for all $n\in\mathbb{Z}$). But since the Implicit Function Theorem suggests there exists an exact algebraic formula for $x$ using the above definition of an algebraic function, then $e^x$ can not be algebraic since there are an infinite number of representations $x_n$ of $x$.

A: One could use the growth at infinity of the function $f:x\mapsto\mathrm e^x$.
Assume that that $f$ is algebraic and choose a real number $x\geqslant0$. Then $|f(x)|\geqslant1$ and
$$
|c_n(x)|\,|f(x)|^n\leqslant b(x)|f(x)|^{n-1},\qquad b(x)=\sum\limits_{k=0}^{n-1}|c_k(x)|.
$$
Hence, for every real number $x\geqslant0$ such that $c_n(x)\ne0$, $|f(x)|\leqslant b(x)/|c_n(x)|$. But indeed, $c_n(x)\ne0$ for every real number $x$ large enough and $b(x)/|c_n(x)|$ can grow at most polynomially when the real number $x$ goes to $+\infty$ while $|f(x)|=\mathrm e^x$ grows... well, exponentially. This is a contradiction.

A: Here is a purely algebraic proof using only the fact that if $y=e^x$, then $y'=y$, but no analytic facts about the exponential function. In other words it should hold in any differential field.
Let $K$ be a differential field, such that $K=k(x)$ where $k$ is the field of constants of $K$ (ie those numbers whose derivative is 0) and with $x'=1$ (think field of rational functions in $x$). And $K(y)$ is a differential extension with $y'=y.$
First observe that $y\notin K$. For elements of $K$ are of the form $c p/q$ with $p,q$ monic polynomials in $x$ over $k$ and $c$ a constant. If $(p/q)'=p/q,$ then $p'q-pq'=pq.$ But the polynomial on the right has degree $\deg p+\deg q$, while the polynomial on the left has degree $\deg p+\deg q-1,$ and both sides are monic, so they are not equal.
Now suppose $y$ were algebraic over $K$, then let the minimal polynomial of $y$ be $y^n+a_{n-1}y^{n-1}+\dotsb+a_0=0.$ Taking the derivative, we have $ny^n+(n-1)a_{n-1}y^{n-1}+a_{n-1}'y^{n-1}+\dotsb+a_0'=0.$ Subtracting from $n$ times the first equation gives $(a_{n-1}-a_{n-1}')y^{n-1}+\dotsb+na_0-a_0'=0.$ We already observed that $y'=y$ has no non-zero solutions in $K$, hence $a_{n-1}-a_{n-1}'\neq 0,$ so we have a monic polynomial of degree $n-1$ annihilating $y$, which contradicts the minimality of our polynomial.


text:
Q: How to Count sum of list by group in GroupedListView I want to show sum of amount in each list inside group in GroupedListView. Don't know how to do that i tried a code from stackoverflow and that doesn't also work.

the code that i used is shown below. It's inside GroupedListView
*elements: newexpense.values.toList(),
                groupBy: (element) =>
                    DateFormat.yMMMMd('en_US').parse(element.date),
                groupHeaderBuilder: (groupByValue) {
                  int totalAmount = 0;
                  newexpense.values.toList().map((ec) {
                    if (ec.date == groupByValue.date) {
                      totalAmount += int.parse(ec.amount);
                    }
                  });
                  return Container(
                    child: Row(
                      children: [
                        Text(groupByValue.date),
                        Text(totalAmount.toString())
                      ],
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    ),
                    padding: EdgeInsets.all(8.0),
                  );
                },*


text:
Q: How to query and expand polymorphic navigation collection properties in Breezejs We are using Breeze for the first time in a real world application and it is a fantastic framework. We are experiencing issues with inheritance in that when querying for an entity with a polymorphic navigation collection, we can see the data returned of derived types in JSON but then the collection is not populated in the Breeze entities on the client. We have C# classes on the server which Entity Framework persists to the database using the Table-Per-Type strategy. There is a base abstract class called Client and SpecialClient inherits from it:
    public abstract class Client
    {
        public int Id { get; set; }
        public int QuoteID { get; set; } //Foreign Key for navigation

        public string FirstName { get; set; }
        public string FamilyName { get; set; }
    }

    public class SpecialClient : Client
    {
        public decimal Income { get; set; }
        public string ClientType { get; set; }
    }

Then we have a parent class called Quote, with a collection navigation property of the base Client:
public class Quote
{
    public Quote()
    {
        Clients = new List<Client>();
    }

    public int Id { get; set; }
    public string Reference { get; set; }
    public string Comments { get; set; }
    public DateTime EffectiveDate { get; set; }

    public List<Client> Clients { get; set; }
}

(We have moved the primary/foreign key properties to partial classes but shown them in the same classes here for brevity, not sure if partials would cause an issue?)
We then tried a client-side Breeze query to retrieve a Quote and expand the Clients property (we have a Web API Breeze Controller with a normal Quotes Action using a repository that holds the EF  context and Breeze ContextProvider):
    [HttpGet]
    public IQueryable<Quote> Quotes()
    {
        return _repository.Quotes();
    }

and a Breeze query:
var query = breeze.EntityQuery.from('Quotes').expand('Clients');

When looking at the entities returned we have a Quote entity but the Clients array has not been populated with any Client entities. We have checked the metadata and it seems to look good, it knows about the base types and derived types and we have checked that we have a foreign key mapped between Quote and Client which is also reflected in the metadata. We also checked the JSON resulting from the query, and again, everything looks good, the Clients navigation collection is populated on the Quote entity. It appears Breeze just will not populate the entities when the query returns with the data.
We tried removing the SpecialClient class inheriting from Client, and this then worked in that we got a collection populated of the base client entities, so it does seem connected to the inheritance. We also tried to see if we could query the derived SpecialClient but we cannot seem to work out how to query derived types in a navigation property that specifies the base type with a predicate:
var pred = new breeze.Predicate("Clients", "any", "clientType", "==", 'Life1'));

We are not sure how to specify that we want to query on the SpecialClient derived type. When we tried the above, Breeze complains that Client does not have a clientType property.
Much appreciated if anyone could advise on how to handle this type of inheritance querying and expanding issue and where we are going wrong or if this is a bug (the not expanding part). We are using Web API 2 (5.0.1), Breeze (with EF6 context Provider) 1.4.11 and we have checked that all of our client and server packages are all 1.4.11.
How can we instruct Breeze that we have derived types in Navigation collections and we want to query and retrieve them?
Many Thanks for help!
EDIT 1: Should also mention that we are not using any special EF mapping other than basic convention.

A: By looking at the DocCode sample we seem to have resolved this issue. It turns out that we did not have a reference navigation from the base class Client back to the principle class Quote which holds the navigation collection of base Clients:
public abstract class Client
{
    public int Id { get; set; }
    public int QuoteId { get; set; } //Foreign Key for navigation

    public string FirstName { get; set; }
    public string FamilyName { get; set; }

    public Quote quote { get; set; }    //Added this nav property back to Quote principle!
}

Although we had a QuoteId property for the foreign key to the principle, it looks like we also needed a reference back to Quote from the base Client class. We now can query with expand and the Clients collection is filled with derived types. Is this the correct way of implementing this type of modeling in Breeze? Also, would it be an idea to add a section to the Breeze website docs on inheritance, or would that be too specific to particular backend ORM choices?
On an associated note, is it possible to do query restrictions (wheres or predicates) with properties on the derived types? We got round this by pushing the query to our server repository and doing a LINQ Where with OfType() to get properties we wanted to restrict on, and we were wondering if Breeze can do this in the client (we couldn't see anything clear in the docs).
Thanks for your help, and keep up the fantastic work with Breeze, we are loving the framework!

A: I haven't looked at this in detail yet but in our DocCode sample we have a similar relationship between Customers and Orders/InternationalOrders, where the Customer.Orders property can return either Orders or InternationalOrders.  Take a look a that sample and see how it differs from yours.


text:
Q: How to define Notation format in Coq using { I defined this notation:
Definition Id (n:nat):= n.

Notation "'ID' { n } ":= (Id n) (no associativity, at level 99).

Which works just fine. Now I want to add format to change the line breaks and alignment. Suppose I want to Print something like this:
ID
 { n }

So I tried the following notation:
Notation "'ID' { n } ":= (Id n) (no associativity, at level 99,
format "'ID' '//' { n } ").

In which case I get

Warning: Invalid character '{' at beginning of identifier "{".

So How am I supposed to define a format using {?

A: Simply remove the curly braces from the format:
Definition Id (n : nat) := n.

Notation "'ID' { n } " := (Id n)
                            (no associativity, at level 99,
                             format "'ID' '//'  n  " ).

Check (ID { 4 }).

I'm not sure this is intentional or a bug. However, as the Coq user's manual says, curly braces { } have a special status in notations and are treated differently from other kinds braces. Thus, if you want to do the same with, say, [ ], you need to include the brackets in the format:
Definition Id (n : nat) := n.

Notation "'ID' [ n ] " := (Id n)
                            (no associativity, at level 99,
                             format "'ID' '//'  [ n ] " ).

Check (ID [ 4 ]).


text:
Q: Runtime class override with ByteBuddy I created a custom File based on java.io.File as such I have:
class CloudFile extends java.io.File {}
Is it possible with ByteBuddy to (at runtime) be able to replace all calls to the class java.io.File and masquerade it with the new CloudFile
So, for example I created an app that uses a library that extensively uses java.io.File what I want is any call of that library to the File class in my application would be a call to CloudFile
Or otherwise, a much more plausible solution, to use ByteBuddy to create a Classloader that will override the java.io.File -- and the question is what is the right take on this?

A: You can redefine classes using a Java agent which Byte Buddy allows building with an AgentBuilder. You can then instruct it to redefine all your library code where you replace constructor calls to File with your CloudFile which I assume has virtual overrides for the methods in question.
In order to replace a constructor, create a transformer that registers a MemberSubstitution where the constructor is switched out.