text:
Q: Continuous mapping theorem, multivariate case, joint distribution. I came across the following problem.
Convergence in the following always means weak convergence, i.e. $X_n \rightarrow X$ if and only if $Ef(X_n) \rightarrow Ef(X)$ for all $f$ bounded, continuous and real functions.
Assume $(X_n, Y_n)$ converges jointly to $(X, Y)$.
1) Does it hold, that $f(X_n, Y_n)$ converges to $f(X, Y)$ for all continuous $f$?
I.e. does the continuous mapping theorem hold in the multivariate case?
And if it does not, is it sufficient to additionally assume independence of $X$ and $Y$?
2) Furthermore, f still continuous, is it true, that $(X_n, Y_n, f(X_n, Y_n))$ converges jointly to $(X, Y, f(X, Y))$? Again if not, does it hold for $X$ and $Y$ independent? Respectively what does $f$ have to fulfill?
I came across a paper, where the author is implicitly using both statements. But the only thing I can find is the continuous mapping theorem in the univariate case.
And obviously I know, that if $X_n$ and $Y_n$ are independent and converge to $X$ and $Y$, then they also converge jointly.
I'd appreciate any help or maybe also some keywords to google myself.
Thanks a lot!

A: For (1), you need to verify that for each continuous and bounded $h$, the sequence $Eh(f(X_n,Y_n)))$ converges to $Eh(f(X,Y))$.  But  the composition $g(x,y)=h(f(x,y))$ is continuous and bounded if $h$ is c&b and if $f$ is continuous.
So the weak convergence of $(X_n,Y_n)$ implies the weak convergence of $f(X_n,Y_n)$.
Similarly for (2), except now you need to check that for each continuous and bounded $h(x,y,z)$ that $Eh(X_n,Y_n,f(X_n,Y_n))$ converges to $Eh(X,Y,f(X,Y))$.  In this case you mentioned no hypothesis on $f$, but continuity will allow the above argument to go through.
As follows.  For given bounded continuous $h$ define the function $g$ of two variables  by $g(x,y)=h(x,y,f(x,y))$.  Assuming $f$ is continuous, so is $g$; clearly $g$ is also bounded.   By assumption $(X_n,Y_n)$ converge in distribution to $(X,Y)$, so $ Eg(X_n,Y_n)\to Eg(X,Y)$.  But this means $ Eh(X_n,Y_n,f(X_n,Y_n)) \to E h(X,Y,f(X,Y))$, by the way $g$ is defined in terms of $h$.
Since this holds for all continuous and bounded $h$  we see  that  $(X_n,Y_n,f(X_n,Y_n))$ converges in distribution to $(X,Y,f(X,Y))$.


text:
Q: Breeze js Paging with expand properties Breeze js paging gives wrong number of entities as the result when querying with expand properties, without expanding it works fine with .take and .skip. Can someone plz tell me why that is and what can I do to get the top 10 entries correctly.
My Query :
 var query = new breeze.EntityQuery().from('Student')
                            .where(profile.firstName', 'eq', 'Kate')
                            .skip(10)
                            .take(10)
                            .inlineCount()
                            .expand(['enrollments.batch, profile']);

A: Your expand looks wrong.  I think it should be either
  .expand(['enrollments.batch', 'profile']);   // as an array with 2 elements

or
  .expand('enrollments.batch, profile'); // as a single ',' delimited string

redpajama_set_name: RedPajamaStackExchange


text:
Q: Three.js - change face size on planeGeometry I'm trying to change faces coordinates by modify the vertices.
The values of the variables are correct, but no change on the screen.
This is the plain
And this is my code :
    var geometry = editor.selected.geometry;
    var vertices = geometry.vertices;

    vertices[1] = new THREE.Vector3(-100 / 3, 50, 0);
    vertices[5] = new THREE.Vector3(-100 / 3, 0, 0);

    var uvs = geometry.faceVertexUvs[0];

    uvs[0] = [new THREE.Vector2(0, 1), new THREE.Vector2(0, 0.5), new THREE.Vector2(1 / 6, 1)];
    uvs[1] = [new THREE.Vector2(0, 0.5), new THREE.Vector2(1 / 6, 0.5), new THREE.Vector2(1 / 6, 1)];
    uvs[2] = [new THREE.Vector2(1 / 6, 1), new THREE.Vector2(1 / 6, 0.5), new THREE.Vector2(2 / 3, 1)];
    uvs[3] = [new THREE.Vector2(1/ 6, 0.5), new THREE.Vector2(2 / 3, 0.5), new THREE.Vector2(2 / 3, 1)];

    geometry.computeVertexNormals();
    geometry.computeFaceNormals();

    geometry.__dirtyVertices = true;
    geometry.__dirtyNormals = true;

    geometry.verticesNeedUpdate = true;
    geometry.normalsNeedUpdate = true;
    geometry.uvsNeedUpdate = true;

Any suggestions?

A: You are changing vertices that lie inside the border of the shape. Thats why you dont see a change. If you turn on wireframe on your material you will see that the vertices do change. Take a look at this fiddle:
http://jsfiddle.net/g6pzvjxj/
Also for your uvs it should be:
var uvs = geometry.faceVertexUvs[0];


text:
Q: sendKeys not working and giving java.lang.charsequence error The below is the code snippet and here when i try to execute sendKeys it is throwing error.
public class Revision {

    public static void main(String[] args) {

        WebDriver dr = new FirefoxDriver();

        dr.get("https://www.youtube.com/");

        dr.manage().window().maximize();

        dr.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

        WebElement you=dr.findElement(By.id("masthead-search-term"));

        you.sendKeys("lean on");


text:
Q: Is it possible to pass arguments to a decorator while calling a function in Python? Does anyone know if it's possible to pass arguments to a decorator while calling a function in Python ?
Until now, I only saw that at function definition :
@decorator("This is a decorator", 66)
def func(a: int, b: int) -> None:
    pass

But I was wondering if it was possible to do it while calling a function.
For those who are wondering why I want to do this, it's because I'm proceeding someone else's work who used decorators a lot in his code. But until now he only had to pass arguments at function definition because the function was only called once. The decorators are used to print information logs about the context the function is used but in my case, since the function can be called at different places, the context can be different in function of where the function is called.

A: As others wrote here, a decorator is a syntactic sugar (i.e., makes programs easier to read, write, or understand) of a function that receives another function as a parameter and activates it from inside.
So, calling this "Add()" function with the decorator, like this:
@wrapper()
def Add(x: int, y: int):
    return x + y

It is just like calling the "wrapper" function with the "Add" function as a variable. Like this:
 wrapper(Add)(x,y) # pass x,y to wrapper that pass it to Add function.
|wrapper|
|----Add----|()

The best way (I think) to add parameters to a decorator, is by nesting it all under another function that holds a child decorator. For example:
@deco_maker(msg: str)
def Add(x: int, y: int):
    return x + y

will be this:
 deco_maker(msg)(Add)(x,y)
|--wrapper-|
|-wrapper_func-|
|---------Add-------|

Here is a simple wrapper decorator that log's function calls, without parameters, which can look like this:
def wrapper(func: Callable):
    def wrapper_func(*args, **kwargs):
        logging.DEBUG f"Function '{func.__name__}' called with args: {[str(arg) for arg in args]}."
        value = func(*args, **kwargs)
        return value
    return wrapper_func

and here is the extended decorator with relevant logging parameters (log name and level for more flexibility):
def log_func_calls(logger_name: str, log_level: int):
    def wrapper(func: Callable):
        def wrapper_func(*args, **kwargs):
            logger = logging.getLogger(logger_name)
            logger.log(
                    level=log_level,
                    msg=f"Function '{func.__name__}' called with args: {[str(arg) for arg in args]}."
                    )
            value = func(*args, **kwargs)
            return value
        return wrapper_func
    return wrapper

Here is a full code example for a parameterized decorator for logging function calls, and the log file output print after it.
Example:
import logging
from typing import Callable

# define app logger with file and console handlers
def setup_logging():
    logger = logging.getLogger('test_app')
    logger.setLevel(logging.DEBUG)
    # create file handler which logs even debug messages
    fh = logging.FileHandler('test.log')
    fh.setLevel(logging.DEBUG)
    # create formatter and add it to the file handler
    formatter = logging.Formatter('{asctime} | {name} | {levelname:^8s} | {message}', style='{')
    fh.setFormatter(formatter)
    # add the handler to the logger
    logger.addHandler(fh)
    return logger

# define a log decorator to trace function calls
def log_func_calls(logger_name: str, log_level: int):
    def wrapper(func: Callable):
        def wrapper_func(*args, **kwargs):
            logger = logging.getLogger(logger_name)
            logger.log(
                    level=log_level,
                    msg=f"Function '{func.__name__}' called with args: {[str(arg) for arg in args]}."
                    )
            value = func(*args, **kwargs)
            return value
        return wrapper_func
    return wrapper

# sample usage 1
@log_func_calls(logger_name='test_app', log_level=logging.DEBUG)
def Add(x: int, y: int):
    return x + y

# sample usage 2
@log_func_calls(logger_name='test_app', log_level=logging.DEBUG)
def Sub(x: int, y: int):
    return x - y

# a test run
def main():
    logger = setup_logging()
    logger.info("<<< App started ! >>>")
    print(Add(50,7))
    print(Sub(10,7))
    print(Add(50,70))
    logger.info("<<< App Ended ! >>>")

if __name__ == "__main__":
    main()

And the log output:
...
2022-06-19 23:34:52,656 | test_app |  DEBUG   | Function 'Add' called with args: ['50', '7'].
2022-06-19 23:34:52,656 | test_app |  DEBUG   | Function 'Sub' called with args: ['10', '7'].
2022-06-19 23:34:52,657 | test_app |  DEBUG   | Function 'Add' called with args: ['50', '70'].
...

A: the short answer is no but you can modify the code of the decorator function; for example:
def decorator(func):
    def inner(*args,**kwargs):
        return func(*args,**kwargs)
    return inner

this is a standard decorator function, let's change it a little.
you could do something like this:
def decorator(func,defaultdescription,defaultnum):
    def inner(description=defaultdescription,num=defaultnum,*args,**kwargs):
        print("function",func.__code__.co_name,"with description",description,"with number",num)
        return func(*args,**kwargs)

    return inner

so you can change the description of the function

A: Basically a decorator is a function inside another which calls your function after it's completion. if you are planning to use your own decorator, you must have a inner function which does it's desired task and calls the function which used the decorator function. you can use *args and **kwargs
below code is a basic implementation of the python decorator
# Python code to illustrate
# Decorators basic in Python

def decorator_fun(func):

def inner(*args, **kwargs):
    """
    do your actual task here
    """
    for argv in args:
        print(argv)

    for key in kwargs:
        print(key)
    #returning to  function which used the decorator at last
    func()

return inner

@decorator_fun
def func_to():
    print("Inside actual function")

func_to("hello",{"test": "value 1"})


text:
Q: How do I put text as a background instead of an image? I need to know how i can set text to the background of the scratchcard game i am building. I will put an example of the code i have tried.
    <script type="text/javascript">

    $('#krasvak').wScratchPad({
      scratchMove: function (e, percent) {
        console.log(percent);
        if (percent > 70)
        {
            this.clear();
            window.alert("U heeft uw code gekrast");
            window.location.href='compleet.php';
        }
      }
    });
    $('#krasvak').wScratchPad('bg', 'images/slide1.png');
    $('#krasvak').wScratchPad('fg', 'images/overlay.png');
    $('#krasvak').wScratchPad('size', 15);
    $('#krasvak').wScratchPad('cursor', 'url("./images/coin.png") 5 5, default');

  </script>

If anybody could help me out i would really appriciate it.


text:
Q: How do I create a slider that changes the main page content as well as the slider content and animates the transitions? As the title says, i'm trying to achieve the following effect but unfortunately I have no idea where to start. Any advice or would be appreciated. Here's a crude paint image to illustrate what I want to achieve.
http://i.stack.imgur.com/PssGA.png
A page that has the closest effect of this is found here:
http://www.squarespace.com/tour/weddings
as you can see the slider has a small animation based on which slide is transitioning to which and the main page content changes.

A: i would recommend u to find a open source slider, download, read its documentation and build ur slider on it.
dont forget to read the license, before you decide to work with that slider
i have found one:
https://github.com/gilbitron/Lean-Slider

A: Here we can use jQuery and CSS to have that effect, I have used code I previously used, so the effect is vertical, scrolling down. You can edit it to do your bidding. Sorry I had no time to comment on the code! To change the slider, you can change the buttons (or links) on each slide!

HTML:

Header One

    One -
    Two -
    Three -
    Four -
    Five

Header Two

    One -
    Two -
    Three -
    Four -
    Five

Header Three

    One -
    Two -
    Three -
    Four -
    Five

Header Four

    One -
    Two -
    Three -
    Four -
    Five

Header Five

    One -
    Two -
    Three -
    Four -
    Five

jQuery:
$('a').on('click', function (event) {
    event.preventDefault();//stop the browser from jumping to the anchor
    var href  = $(this).attr('href'),
        oset  = $(href).offset().top;
    $('html, body').stop().animate({
        scrollTop : oset
    }, 1000, function () {
        location.hash = href;
    });
});

Note that the CSS below is  NOT essential!

CSS:
div {
    height : 500px;
    border : 1px solid #000;
}


text:
Q: Как проверить является ли введенная строка числом? Есть ли какой-то булевый метод в java, который принимает строку и проверяет является ли она числом?Например имеем переменную String var="2";. И надо проверить можно ли ее перегнать в переменную числового типа(Например так Integer.parseInt(var);)

A: public static boolean isInteger(String s) {
    try {
        Integer.parseInt(s);
    } catch(NumberFormatException e) {
        return false;
    } catch(NullPointerException e) {
        return false;
    }
    // only got here if we didn't return false
    return true;
}

(c) from


text:
Q: How to check for disposed objects and throw ObjectDisposedException in methods if already disposed I have a disposable class which implements IDisposalbe interface with disposable pattern. To maintain the constrains, I need to make sure that when the object has been disposed, any subsequent call to any public method throws ObjectDisposedException. The obvious solution is to check a bool value isDisposed and throw an exception. But how can I use some reflection based solution (if any or some other approach) to automatically apply this constrain to every public method. What I don't want to do is to do this check in every method I have (i.e. prior to every call I do NOT want to call IsObjectDisposed() method)
Apart from the practical application as I have described earlier I need to know a way to automatically call a method let's say Foo() for every call of a method of a class say MyClass

A: Imo, you have 2 solutions here:

*

*or call them manually, so code actually, that for every public method the check is executed.

*or can use Aspect Oriented Programming to inject the function call into the begining of every method marked by some attribute.

A: Have you thought about simply performing a null check prior to using the code?
ie. if(null!=object)
{
 do operations
}
Or are you looking for some kind of object wrapper instead using the virtual keyword? ie use Aspects using unity for example or spring. These allow you to Dependency Inject code into your application and allow you to apply "cross cutting concerns" through your code base ie security, logging, printing and boundary checking.


text:
Q: How to make enemies follow me using arcade module? I'm working on this game for an assesment in school, but I keep getting the error below. I've done everything I can to fix it, but I'm not very experienced in python so it's hard to figure out what's wrong.
File "//<redacted>/Python/Assessment/Assesment 16 june.py", line 49,
  in follow_sprite
    if self.center_y < player_sprite.center_y:
AttributeError: 'SpriteList' object has no attribute 'center_y'

Code:
import arcade
import random
import math

SPRITE_SCALING = 0.5
SPRITE_SCALING_LASER = 0.8

SCREEN_WIDTH = 1280
SCREEN_HEIGHT = 720
SCREEN_TITLE = "zombier shooter"
ENEMY_COUNT = 50

BULLET_SPEED = 30
MOVEMENT_SPEED = 5
SPRITE_SPEED = 2

class Player(arcade.Sprite):

    def update(self):
        """ moves the player """
        # move player.
        self.center_x += self.change_x
        self.center_y += self.change_y

        # check for out of bounds
        if self.left < 0:
            self.left = 0
        elif self.right > SCREEN_WIDTH - 1:
            self.right = SCREEN_WIDTH - 1

        if self.bottom < 0:
            self.bottom = 0
        elif self.top > SCREEN_HEIGHT - 1:
            self.top = SCREEN_HEIGHT - 1

class Enemy(arcade.Sprite):
    """
    This class represents the enemies on our screen.
    """

    def follow_sprite(self, player_sprite):
        """
        This function will move the current sprite towards whatever
        other sprite is specified as a parameter.
        """

        if self.center_y < player_sprite.center_y:
            self.center_y += min(SPRITE_SPEED, player_sprite.center_y - self.center_y)
        elif self.center_y > player_sprite.center_y:
            self.center_y -= min(SPRITE_SPEED, self.center_y - player_sprite.center_y)

        if self.center_x < player_sprite.center_x:
            self.center_x += min(SPRITE_SPEED, player_sprite.center_x - self.center_x)
        elif self.center_x > player_sprite.center_x:
            self.center_x -= min(SPRITE_SPEED, self.center_x - player_sprite.center_x)

class MyGame(arcade.Window):
    """
    main game class
    """

    def __init__(self, width, height, title):
        """
        initialises stuff
        """

        #call the parent class initializer
        super().__init__(width, height, title)

        #variables that will hold sprite lists
        self.player_list = None

        #set up the player info
        self.player_sprite = None

        #track the current state of what key is pressed

        self.left_pressed = False

        self.right_pressed = False

        self.up_pressed = False

        self.down_pressed = False

        #set the background color
        arcade.set_background_color(arcade.color.AMAZON)

    def setup(self):
        """ Set up the game and initialize the variables. """

        #sprite lists
        self.player_list = arcade.SpriteList()
        self.enemy_list = arcade.SpriteList()
        self.bullet_list = arcade.SpriteList()

        #setup score
        self.score = 0
        self.score_text = None

        #add sounds for shooting and hitting enemy
        self.gun_sound = arcade.sound.load_sound(":resources:sounds/laser1.wav")
        self.hit_sound = arcade.sound.load_sound(":resources:sounds/phaseJump1.wav")

        #set up the player
        self.player_sprite = Player(":resources:images/animated_characters/female_person/femalePerson_idle.png", SPRITE_SCALING)
        self.player_sprite.center_x = 50
        self.player_sprite.center_y = 50
        self.player_list.append(self.player_sprite)

        self.score = 0

        for i in range(ENEMY_COUNT):

            #enemy texture
            enemy = arcade.Sprite(":resources:images/animated_characters/zombie/zombie_idle.png", SPRITE_SCALING)

            enemy.center_x = random.randrange(SCREEN_WIDTH)
            enemy.center_y = random.randrange(SCREEN_HEIGHT)

            self.enemy_list.append(enemy)

    def on_draw(self):
        """ render the screen. """

        #clear the screen
        self.clear()

        #draw all the sprites.
        self.player_list.draw()
        self.enemy_list.draw()
        self.bullet_list.draw()

        #put score text on the sscsre
        output = f"Score: {self.score}"
        arcade.draw_text(output, 10, 20, arcade.color.WHITE, 14)

    def on_mouse_press(self, x, y, button, modifiers):
        """ Called whenever the mouse button is clicked. """

        # Create a bullet
        bullet = arcade.Sprite(":resources:images/space_shooter/laserBlue01.png", SPRITE_SCALING_LASER)

        # Position the bullet at the player's current location
        start_x = self.player_sprite.center_x
        start_y = self.player_sprite.center_y
        bullet.center_x = start_x
        bullet.center_y = start_y

        # Get from the mouse the destination location for the bullet
        # IMPORTANT! If you have a scrolling screen, you will also need
        # to add in self.view_bottom and self.view_left.
        dest_x = x
        dest_y = y

        # Do math to calculate how to get the bullet to the destination.
        # Calculation the angle in radians between the start points
        # and end points. This is the angle the bullet will travel.
        x_diff = dest_x - start_x
        y_diff = dest_y - start_y
        angle = math.atan2(y_diff, x_diff)

        # Angle the bullet sprite so it doesn't look like it is flying
        # sideways.
        bullet.angle = math.degrees(angle)
        print(f"Bullet angle: {bullet.angle:.2f}")

        # Taking into account the angle, calculate our change_x
        # and change_y. Velocity is how fast the bullet travels.
        bullet.change_x = math.cos(angle) * BULLET_SPEED
        bullet.change_y = math.sin(angle) * BULLET_SPEED

        # Add the bullet to the appropriate lists
        self.bullet_list.append(bullet)

    def update_player_speed(self):

        #calculate speed based on the keys pressed

        self.player_sprite.change_x = 0

        self.player_sprite.change_y = 0

        if self.up_pressed and not self.down_pressed:

            self.player_sprite.change_y = MOVEMENT_SPEED

        elif self.down_pressed and not self.up_pressed:

            self.player_sprite.change_y = -MOVEMENT_SPEED

        if self.left_pressed and not self.right_pressed:

            self.player_sprite.change_x = -MOVEMENT_SPEED

        elif self.right_pressed and not self.left_pressed:

            self.player_sprite.change_x = MOVEMENT_SPEED

    def on_update(self, delta_time):
        """ Movement and game logic """

        #call update to move the sprite
        self.player_list.update()

         # Call update on all sprites
        self.bullet_list.update()

        # Loop through each bullet
        for bullet in self.bullet_list:

            # Check this bullet to see if it hit a enemy
            hit_list = arcade.check_for_collision_with_list(bullet, self.enemy_list)

            # If it did, get rid of the bullet
            if len(hit_list) > 0:
                bullet.remove_from_sprite_lists()

            # For every enemy we hit, add to the score and remove the enemy
            for enemy in hit_list:
                enemy.remove_from_sprite_lists()
                self.score += 1

            # If the bullet flies off-screen, remove it.
            if bullet.bottom > self.width or bullet.top < 0 or bullet.right < 0 or bullet.left > self.width:
                bullet.remove_from_sprite_lists()

        for enemy in self.enemy_list:
            Enemy.follow_sprite(self.enemy_list, self.player_sprite)

        # Generate a list of all sprites that collided with the player.
        hit_list = arcade.check_for_collision_with_list(self.player_sprite, self.enemy_list)

        # Loop through each colliding sprite, remove it, and add to the score.
        for enemy in hit_list:
            enemy.remove_from_sprite_lists()
            self.score -= 1

    def on_key_press(self, key, modifiers):

        """called when user presses a key. """

        if key == arcade.key.UP:

            self.up_pressed = True

            self.update_player_speed()

        elif key == arcade.key.DOWN:

            self.down_pressed = True

            self.update_player_speed()

        elif key == arcade.key.LEFT:

            self.left_pressed = True

            self.update_player_speed()

        elif key == arcade.key.RIGHT:

            self.right_pressed = True

            self.update_player_speed()

    def on_key_release(self, key, modifiers):

        """called when user releases a key. """

        if key == arcade.key.UP:

            self.up_pressed = False

            self.update_player_speed()

        elif key == arcade.key.DOWN:

            self.down_pressed = False

            self.update_player_speed()

        elif key == arcade.key.LEFT:

            self.left_pressed = False

            self.update_player_speed()

        elif key == arcade.key.RIGHT:

            self.right_pressed = False

            self.update_player_speed()

def main():
    """ Main function """
    window = MyGame(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
    window.setup()
    arcade.run()

if __name__ == "__main__":
    main()

A: Replace
Enemy.follow_sprite(self.enemy_list, self.player_sprite)

with
Enemy.follow_sprite(enemy, self.player_sprite)

and you'll see following:


text:
Q: How to make the content of list (tree view data in list ul and li tags) expanded by default? I have an angular component with tree view data in list (ul and li tags).
I want the content of tree view expanded by default [at least first level should be expanded by default].
I have the following code:
In Html

            {{ !!contentNode.toggle ? '▼' : '▶' }} {{ contentNode.locationname }}
          <content-list *ngIf="contentNode.toggle" [startingNode]="contentNode.pk_location_id"  [myData]="rows"></content-list>

In component.ts
export class ContentListComponent implements OnInit {

constructor (private _contentService: LocationService) {}

errorMessage: string;

@Input('startingNode')
private _startNodeId: string;

@Input('myData')
private _myData = [];

rows=[];

contentNodes: Location[];
bookFilteredList : Location[];

ngOnInit() {
    this.rows=this._myData;
    this.contentNodes=this.rows;
    //console.dir(this.contentNodes);
    //this.getContentNodes();
    this.filter();
}

filter(){
    //console.log('Excecute filter');
    let storageId = this._startNodeId;

    this.bookFilteredList = this.contentNodes.filter((book: Location) => book.parent_location_id === storageId);
    this.contentNodes = this.bookFilteredList;
    console.log(this.bookFilteredList);
    return this.contentNodes;
}

// getContentNodes() {
//  this._contentService.getChildLocations(this._startNodeId)
//      .subscribe(
//          contentNodes => this.contentNodes = contentNodes,
//          error =>  this.errorMessage = <any>error

//      );
//      console.dir(this.contentNodes)
// }

toggleBranch(branchId:number){
    console.log('branchId: ' + branchId);
}

}
If I remove  *ngIf="contentNode.toggle" from the following line, I am getting tree view in uncollapsible format, but then the toggle is not working.
<content-list *ngIf="contentNode.toggle" [startingNode]="contentNode.pk_location_id"  [myData]="rows"></content-list>

Can any one give me the solution?
Thanks & Regards
Shilpa Kulkarni

A: I got the solution for my issue.
The value of contentNode.toggle is false and hence  is not generated and I was getting list in collapsible format. I made it true by using (!) sign as *ngIf="!contentNode.toggle".
Tried as follows and getting the content of tree view expanded by default:
 <content-list *ngIf="!contentNode.toggle" [startingNode]="contentNode.pk_location_id"  [myData]="rows"></content-list>


text:
Q: How to cache HashMap data for "n" number of iteration I got this question from one of my friends.
Problem) I want to write a class which can cache data for "n" iterations for each key and after which it will fetch data from database.
After fetching the data from database again for that key it should fetch data only after "n" iteration. For each fetch might be from database or cache the iteration count should be reduced.
Question 1) Which is the best approach extending HashMap or writing a class which holds a HashMap
Question 2) Write the code for the above problem.
I have written the below code. Please suggest me with any better approach for doing this.
    public class CacheHashMap {

    private int iterationValue = 3;
    static Map<String, String> dbSimulator = new HashMap<String, String>();
    private Map<String, String> cacheMap;
    private Map<String, Integer> iterationMap;

    static{
        dbSimulator.put("Vijay","VJ");
        dbSimulator.put("Smith","SM");
        dbSimulator.put("Raj","RJ");
    }

    public CacheHashMap(Map valueMap, int n) {
        this.iterationValue = n;
        if(null != valueMap){
            this.cacheMap = valueMap;
            this.iterationMap = new HashMap<String, Integer>();
            for(Map.Entry<String, String> entry:cacheMap.entrySet()){
                iterationMap.put(entry.getKey(), iterationValue);
            }
        }
    }

    public String getValue(String key){
        if(null != cacheMap && null != iterationMap){
            if(cacheMap.containsKey(key)){
                if(0 == iterationMap.get(key)){
                    cacheMap.put(key, dbSimulator.get(key));
                    iterationMap.put(key, (iterationValue-1));
                    return cacheMap.get(key);
                }else{
                    iterationMap.put(key, (iterationMap.get(key)-1));
                    return cacheMap.get(key);
                }
            }else{
                cacheMap.put(key, dbSimulator.get(key));
                iterationMap.put(key, (iterationValue-1));
                return cacheMap.get(key);
            }
        }
        return "No data found. Please enter a valid key";
    }

    public void printCacheMap(){
        System.out.println("==================================================================");
        for(Map.Entry<String, String> entry:cacheMap.entrySet()){
            System.out.println("Cache Map Data\tKey:: " + entry.getKey() + "\tValue:: " + entry.getValue());
        }
    }

    public void printIterationMap(){
        System.out.println("==================================================================");
        for(Map.Entry<String, Integer> entry:iterationMap.entrySet()){
            System.out.println("Iteration Map Data\tKey:: " + entry.getKey() + "\tValue:: " + entry.getValue());
        }
    }
}

public class CacheHashMapExecutor {

    public static void main(String[] args) {
        Map<String, String> myMap = new HashMap<String, String>();
        CacheHashMap cacheHashMap = new CacheHashMap(myMap, 3);
        cacheHashMap.getValue("Vijay");cacheHashMap.printCacheMap();cacheHashMap.printIterationMap();
        cacheHashMap.getValue("Raj");cacheHashMap.printCacheMap();cacheHashMap.printIterationMap();
        cacheHashMap.getValue("Smith");cacheHashMap.printCacheMap();cacheHashMap.printIterationMap();
        cacheHashMap.getValue("Vijay");cacheHashMap.printCacheMap();cacheHashMap.printIterationMap();
        cacheHashMap.getValue("Raj");cacheHashMap.printCacheMap();cacheHashMap.printIterationMap();
        cacheHashMap.getValue("Vijay");cacheHashMap.printCacheMap();cacheHashMap.printIterationMap();
        cacheHashMap.getValue("Raj");cacheHashMap.printCacheMap();cacheHashMap.printIterationMap();
        cacheHashMap.getValue("Vijay");cacheHashMap.printCacheMap();cacheHashMap.printIterationMap();
        cacheHashMap.getValue("Raj");cacheHashMap.printCacheMap();cacheHashMap.printIterationMap();
    }

}

A: 1st question: I would also compose with HashMap, instead of extending it, because your Cache system ISN'T a HashMap ; it just HAS a HashMap.
2nd: I would do this way:
public class CacheHashMap {

    private int iterationValue = 3;
    static Map<String, String> dbSimulator = new HashMap<String, String>();

    private Map<String, CacheItem> cacheMap = new HashMap<>();

    static{
        dbSimulator.put("Vijay","VJ");
        dbSimulator.put("Smith","SM");
        dbSimulator.put("Raj","RJ");
    }

    public CacheHashMap(int n) {
        this.iterationValue = n;
    }

    public String getValue(String key) {
        CacheItem item = cacheMap.get(key);
        if (item == null || item.isExpired()) {
            // Load from DB
            String value = dbSimulator.get(key);
            cacheMap.put(key, new CacheItem(iterationValue, value));
            return value;
        } else {
            return item.getValue();
        }
    }

    private class CacheItem {
        private int iteration;
        private String value;

        public CacheItem(int iteration, String value) {
            this.iteration = iteration;
            this.value = value;
        }

        public boolean isExpired() {
            iteration--;
            return iteration < 0;
        }

        public String getValue() {
            return value;
        }
    }
}

The idea is to have a inner class "CacheItem" that prevent you from having to maintain 2 different maps, with the risk of having inconsistent keys. And in addition, there's some improvements, I think, in the algorithm of reading/writing the cache.


text: Q: How much does performance suffer when both reading and writing occurs simultaneously on a Redis slave? I want to build a system where a master periodically updates changes to its slave, the slave is read only. How much would my read operation suffer given that redis is single threaded. I would have to entertain multiple read requests and output the results in real time.


text:
Q: Is this the right code for tracking a button in a an app for Firebase I'm new to Firebase SDK, I have to create a custom event for downloading content and I can someone explain to me how I would go about changing the code to track the downloads?
Analytics.logEvent(AnalyticsEventSelectContent, parameters: [
  AnalyticsParameterItemID: "id-\title!",
  AnalyticsParameterItemName: "title",
  AnalyticsParameterContentType: "cont",
])

A: You could consider using the automatically collected event in Analytics called 'first_open' which is triggered when the user launches the app for the first time after installing or reinstalling it. You could check out this page to know more about automatically collected events in Firebase.


text:
Q: compress output tiff with g4 compression How to write a file as tiff with g4 compression??
imwrite(string("compressed.tif"), res);

update
image processing
This is the processing of the image data before the data is sent to write_fax() so further processing should not be necessary (have commented out the processing in write_fax).. But the output file is completely black..
res.convertTo(res, CV_32FC1, 1.0 / 255.0);
res = 1.0 - res;
res = Img + res;
threshold(res, res, 0.85, 1, THRESH_BINARY);
// sends data to `write_fax()`

complete code
/*
 *  Compile
 *  # g++ txtbin.cpp -o txtbin -ltiff `pkg-config opencv --cflags --libs`
 *
 *  Run
 *  # ./txtbin input.jpg output.png
 */

#include "string"
#include "fstream"
#include "/usr/include/opencv2/opencv.hpp"
#include "/usr/include/boost/tuple/tuple.hpp"

#include "/usr/include/x86_64-linux-gnu/tiff.h"
#include "/usr/include/x86_64-linux-gnu/tiffio.h"
#include <stdint.h>
#include <vector>
#include <stdexcept>
#include <cstdio>
#include <cassert>

using namespace std;
using namespace cv;
using namespace boost;

void CalcBlockMeanVariance(Mat& Img, Mat& Res, float blockSide=21, float contrast=0.01){
    /*
     *  blockSide: set greater for larger fonts in image
     *  contrast: set smaller for lower contrast image
     */

    Mat I;
    Img.convertTo(I, CV_32FC1);
    Res = Mat::zeros(Img.rows / blockSide, Img.cols / blockSide, CV_32FC1);
    Mat inpaintmask;
    Mat patch;
    Mat smallImg;
    Scalar m, s;

    for(int i = 0; i < Img.rows - blockSide; i += blockSide){
        for(int j = 0; j < Img.cols - blockSide; j += blockSide){
            patch = I(Range(i, i + blockSide + 1), Range(j, j + blockSide + 1));
            meanStdDev(patch, m, s);

            if(s[0] > contrast){
                Res.at<float>(i / blockSide, j / blockSide) = m[0];
            }
            else{
                Res.at<float>(i / blockSide, j / blockSide) = 0;
            }
        }
    }

    resize(I, smallImg, Res.size());

    threshold(Res, inpaintmask, 0.02, 1.0, THRESH_BINARY);

    Mat inpainted;
    smallImg.convertTo(smallImg, CV_8UC1, 255);

    inpaintmask.convertTo(inpaintmask, CV_8UC1);
    inpaint(smallImg, inpaintmask, inpainted, 5, INPAINT_TELEA);

    resize(inpainted, Res, Img.size());
    Res.convertTo(Res, CV_32FC1, 1.0 / 255.0);
}

tuple<int, int, int, int> detect_text_box(string input, Mat& res, bool draw_contours=false){
    Mat large = imread(input);

    bool test_output = false;

    int
        top = large.rows,
        bottom = 0,
        left = large.cols,
        right = 0;

    int
        rect_bottom,
        rect_right;

    Mat rgb;
    // downsample and use it for processing
    pyrDown(large, rgb);
    Mat small;
    cvtColor(rgb, small, CV_BGR2GRAY);
    // morphological gradient
    Mat grad;
    Mat morphKernel = getStructuringElement(MORPH_ELLIPSE, Size(3, 3));
    morphologyEx(small, grad, MORPH_GRADIENT, morphKernel);
    // binarize
    Mat bw;
    threshold(grad, bw, 0.0, 255.0, THRESH_BINARY | THRESH_OTSU);
    // connect horizontally oriented regions
    Mat connected;
    morphKernel = getStructuringElement(MORPH_RECT, Size(9, 1));
    morphologyEx(bw, connected, MORPH_CLOSE, morphKernel);
    // find contours
    Mat mask = Mat::zeros(bw.size(), CV_8UC1);
    vector<vector<Point> > contours;
    vector<Vec4i> hierarchy;
    findContours(connected, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
    // filter contours
    for(int idx = 0; idx >= 0; idx = hierarchy[idx][0]){
        Rect rect = boundingRect(contours[idx]);
        Mat maskROI(mask, rect);
        maskROI = Scalar(0, 0, 0);
        // fill the contour
        drawContours(mask, contours, idx, Scalar(255, 255, 255), CV_FILLED);
        // ratio of non-zero pixels in the filled region
        double r = (double)countNonZero(maskROI) / (rect.width * rect.height);

        // assume at least 45% of the area is filled if it contains text
        if (r > 0.45 &&
        (rect.height > 8 && rect.width > 8) // constraints on region size
        // these two conditions alone are not very robust. better to use something
        //like the number of significant peaks in a horizontal projection as a third condition
        ){
            if(draw_contours){
                rectangle(res, Rect(rect.x * 2, rect.y * 2, rect.width * 2, rect.height * 2), Scalar(0, 255, 0), 2);
            }

            if(test_output){
                rectangle(rgb, rect, Scalar(0, 255, 0), 2);
            }

            if(rect.y < top){
                top = rect.y;
            }
            rect_bottom = rect.y + rect.height;
            if(rect_bottom > bottom){
                bottom = rect_bottom;
            }
            if(rect.x < left){
                left = rect.x;
            }
            rect_right = rect.x + rect.width;
            if(rect_right > right){
                right = rect_right;
            }
        }
    }

    if(draw_contours){
        rectangle(res, Point(left * 2, top * 2), Point(right * 2, bottom * 2), Scalar(0, 0, 255), 2);
    }

    if(test_output){
        rectangle(rgb, Point(left, top), Point(right, bottom), Scalar(0, 0, 255), 2);
        imwrite(string("test_text_contours.jpg"), rgb);
    }

    return make_tuple(left * 2, top * 2, (right - left) * 2, (bottom - top) * 2);
}

// just tiny exception generator
void except(bool condition, const std::string &message = "")
{
    if (!condition)
        throw std::runtime_error("Error: " + message);
}

bool write_fax(
    const std::string &name, const cv::Mat &src, uint8_t threshold = 150)
{
    cv::Mat image;
    /*if (src.channels() == 3)
        cv::cvtColor(src, image, CV_BGR2GRAY);
    else if (src.channels() == 4)
        cv::cvtColor(src, image, CV_BGRA2GRAY);
    else*/
        src.copyTo(image);

    //assert(image.depth() == CV_8U && "working only with 8-bit images now");

    int width = image.cols;
    int height = image.rows;

    // do NOT put "wb" as the mode, because the b means "big endian" mode, not "binary" mode.
    // http://www.remotesensing.org/libtiff/man/TIFFOpen.3tiff.html
    TIFF* pTiffHandle = TIFFOpen(name.c_str(), "w");
    if (!pTiffHandle)
    {
        printf("can't open TIFF descriptor\n");
        return false;
    }

    try
    {
    except(TIFFSetField(pTiffHandle, TIFFTAG_IMAGEWIDTH, width), "width");
    except(TIFFSetField(pTiffHandle, TIFFTAG_IMAGELENGTH, height), "length");
    except(TIFFSetField(pTiffHandle, TIFFTAG_BITSPERSAMPLE, 1), "bits per sample");
    except(TIFFSetField(pTiffHandle, TIFFTAG_SAMPLESPERPIXEL, 1), "samples per pixel");
    except(TIFFSetField(pTiffHandle, TIFFTAG_ROWSPERSTRIP, 1), "rows per strip");

    except(TIFFSetField(pTiffHandle, TIFFTAG_COMPRESSION, COMPRESSION_CCITTFAX4), "compression");
    except(TIFFSetField(pTiffHandle, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISWHITE), "photometric");
    except(TIFFSetField(pTiffHandle, TIFFTAG_FILLORDER, FILLORDER_MSB2LSB), "photometric");
    except(TIFFSetField(pTiffHandle, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG), "planar config");
    //except(TIFFSetField(pTiffHandle, TIFFTAG_PREDICTOR, predictor), "predictor");
    //except(TIFFSetField(pTiffHandle, TIFFTAG_STRIPOFFSETS, strip_offsets), "strip offsets");

    // not necessary
    except(TIFFSetField(pTiffHandle, TIFFTAG_XRESOLUTION, 200.0), "res x");
    except(TIFFSetField(pTiffHandle, TIFFTAG_YRESOLUTION, 200.0), "res y");
    except(TIFFSetField(pTiffHandle, TIFFTAG_RESOLUTIONUNIT, RESUNIT_INCH), "res unit");

    std::vector<uchar> _buffer(width / 8 + 8, 0);
    uchar* buffer = &_buffer[0];
    int bytes = int(width / 8.0 + 0.5);
    for (int y = 0; y < height; ++y)
    {
        uint8_t *src_row = image.ptr(y);
        for (int x = 0; x < width; ++x, ++src_row)
        {
            uint8_t eight_pixels = buffer[x / 8];
            eight_pixels = eight_pixels << 1;
            if (*src_row < threshold)
                eight_pixels = eight_pixels | 1;  //
            buffer[x / 8] = eight_pixels;
        }

        // for the some reason writeEncodedStrip doesn't work
//      except(TIFFWriteEncodedStrip(pTiffHandle, y, buffer, bytes) != -1, "write scanline");
        except(TIFFWriteScanline(pTiffHandle, buffer, y,  bytes) != -1, "write scanline");
    }

    }
    catch (const std::runtime_error &e)
    {
        printf("TIFF writing: %s\n", e.what());
        TIFFClose(pTiffHandle);
        return false;
    }

    TIFFClose(pTiffHandle);
    return true;
}

int main(int argc, char* argv[]){
    string input;
    string output = "output.png";

    int
        width = 0,
        height = 0;

    bool
        crop = false,
        draw = false;

    float margin = 0;

    //  Return error if arguments are missing
    if(argc < 3){
        cerr << "\nUsage: txtbin input [options] output\n\n"
            "Options:\n"
            "\t-w <number>          -- set max width (keeps aspect ratio)\n"
            "\t-h <number>          -- set max height (keeps aspect ratio)\n"
            "\t-c                   -- crop text content contour\n"
            "\t-m <number>          -- add margins (number in %)\n"
            "\t-d                   -- draw text content contours (debugging)\n" << endl;
        return 1;
    }

    //  Parse arguments
    for(int i = 1; i < argc; i++){
        if(i == 1){
            input = string(argv[i]);

            //  Return error if input file is invalid
            ifstream stream(input.c_str());
            if(!stream.good()){
                cerr << "Error: Input file is invalid!" << endl;
                return 1;
            }
        }
        else if(string(argv[i]) == "-w"){
            width = atoi(argv[++i]);
        }
        else if(string(argv[i]) == "-h"){
            height = atoi(argv[++i]);
        }
        else if(string(argv[i]) == "-c"){
            crop = true;
        }
        else if(string(argv[i]) == "-m"){
            margin = atoi(argv[++i]);
        }
        else if(string(argv[i]) == "-d"){
            draw = true;
        }
        else if(i == argc - 1){
            output = string(argv[i]);
        }
    }

    Mat Img = imread(input, CV_LOAD_IMAGE_GRAYSCALE);
    Mat res;
    Img.convertTo(Img, CV_32FC1, 1.0 / 255.0);
    CalcBlockMeanVariance(Img, res);
    res = 1.0 - res;
    res = Img + res;
    threshold(res, res, 0.85, 1, THRESH_BINARY);

    int
        txt_x,
        txt_y,
        txt_width,
        txt_height;

    if(crop || draw){
        tie(txt_x, txt_y, txt_width, txt_height) = detect_text_box(input, res, draw);
    }

    if(crop){
        res = res(Rect(txt_x, txt_y, txt_width, txt_height));
    }

    if(margin){
        int border = res.cols * margin / 100;
        copyMakeBorder(res, res, border, border, border, border, BORDER_CONSTANT, Scalar(255, 255, 255));
    }

    float
        width_input = res.cols,
        height_input = res.rows;

    bool resized = false;

    //  Downscale image
    if(width > 0 && width_input > width){
        float scale = width_input / width;
        width_input /= scale;
        height_input /= scale;
        resized = true;
    }
    if(height > 0 && height_input > height){
        float scale = height_input / height;
        width_input /= scale;
        height_input /= scale;
        resized = true;
    }
    if(resized){
        resize(res, res, Size(round(width_input), round(height_input)));
    }

    //imwrite(output, res * 255);
    write_fax(output+".tif", res * 255);

    return 0;
}

A: Simple C++ function for writing g4 TIFFS with libtiff:
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>

#include <tiff.h>
#include <tiffio.h>

#include <stdint.h>
#include <string>
#include <vector>
#include <stdexcept>
#include <cstdio>
#include <cassert>

// just tiny exception generator
void except(bool condition, const std::string &message = "")
{
    if (!condition)
        throw std::runtime_error("Error: " + message);
}

bool write_fax(
    const std::string &name, const cv::Mat &src, uint8_t threshold = 150)
{
    cv::Mat image;
    if (src.channels() == 3)
        cv::cvtColor(src, image, CV_BGR2GRAY);
    else if (src.channels() == 4)
        cv::cvtColor(src, image, CV_BGRA2GRAY);
    else
        src.copyTo(image);

    if (image.depth() != CV_8U)
    {
        cv::Mat tmp;
        image.convertTo(tmp, CV_8U);
        std::swap(image, tmp);
    }

    int width = image.cols;
    int height = image.rows;

    // do NOT put "wb" as the mode, because the b means "big endian" mode, not "binary" mode.
    // http://www.remotesensing.org/libtiff/man/TIFFOpen.3tiff.html
    TIFF* pTiffHandle = TIFFOpen(name.c_str(), "w");
    if (!pTiffHandle)
    {
        printf("can't open TIFF descriptor\n");
        return false;
    }

    try
    {
    except(TIFFSetField(pTiffHandle, TIFFTAG_IMAGEWIDTH, width), "width");
    except(TIFFSetField(pTiffHandle, TIFFTAG_IMAGELENGTH, height), "length");
    except(TIFFSetField(pTiffHandle, TIFFTAG_BITSPERSAMPLE, 1), "bits per sample");
    except(TIFFSetField(pTiffHandle, TIFFTAG_SAMPLESPERPIXEL, 1), "samples per pixel");
    except(TIFFSetField(pTiffHandle, TIFFTAG_ROWSPERSTRIP, 1), "rows per strip");

    except(TIFFSetField(pTiffHandle, TIFFTAG_COMPRESSION, COMPRESSION_CCITTFAX4), "compression");
    except(TIFFSetField(pTiffHandle, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISWHITE), "photometric");
    except(TIFFSetField(pTiffHandle, TIFFTAG_FILLORDER, FILLORDER_MSB2LSB), "photometric");
    except(TIFFSetField(pTiffHandle, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG), "planar config");
    //except(TIFFSetField(pTiffHandle, TIFFTAG_PREDICTOR, predictor), "predictor");
    //except(TIFFSetField(pTiffHandle, TIFFTAG_STRIPOFFSETS, strip_offsets), "strip offsets");

    // not necessary
    except(TIFFSetField(pTiffHandle, TIFFTAG_XRESOLUTION, 200.0), "res x");
    except(TIFFSetField(pTiffHandle, TIFFTAG_YRESOLUTION, 200.0), "res y");
    except(TIFFSetField(pTiffHandle, TIFFTAG_RESOLUTIONUNIT, RESUNIT_INCH), "res unit");

    std::vector<uchar> _buffer(width / 8 + 8, 0);
    uchar* buffer = &_buffer[0];
    int bytes = int(width / 8.0 + 0.5);
    for (int y = 0; y < height; ++y)
    {
        uint8_t *src_row = image.ptr(y);
        for (int x = 0; x < width; ++x, ++src_row)
        {
            uint8_t eight_pixels = buffer[x / 8];
            eight_pixels = eight_pixels << 1;
            if (*src_row < threshold)
                eight_pixels = eight_pixels | 1;  //
            buffer[x / 8] = eight_pixels;
        }

        // for the some reason writeEncodedStrip doesn't work
//      except(TIFFWriteEncodedStrip(pTiffHandle, y, buffer, bytes) != -1, "write scanline");
        except(TIFFWriteScanline(pTiffHandle, buffer, y,  bytes) != -1, "write scanline");
    }

    }
    catch (const std::runtime_error &e)
    {
        printf("TIFF writing: %s\n", e.what());
        TIFFClose(pTiffHandle);
        return false;
    }

    TIFFClose(pTiffHandle);
    return true;
}

Threshold is value for consider color as black of white (because g4 uses only one bit for color).
Compilation command in linux:
g++ <source name> -o <output name> `pkg-config opencv --cflags --libs` -ltiff

Code is self-commented, hope there is no unclear places.


text:
Q: Combinatorics- distribute n objects to k bin with constraints Suppose I have n objects distributed to k bins and I want to know how many multisets satisfy the following condition: exactly j bins have at least m objects, where j $\leq$ k,m $\leq$ n, and j*m $\leq$ n. For example, if n = 5, k=4, j=2 and m = 2, there are 24 subsets:
[3, 2, 0, 0]
[3, 0, 2, 0]
[3, 0, 0, 2]
[2, 3, 0, 0]
[2, 2, 1, 0]
[2, 2, 0, 1]
[2, 1, 2, 0]
[2, 1, 0, 2]
[2, 0, 3, 0]
[2, 0, 2, 1]
[2, 0, 1, 2]
[2, 0, 0, 3]
[1, 2, 2, 0]
[1, 2, 0, 2]
[1, 0, 2, 2]
[0, 3, 2, 0]
[0, 3, 0, 2]
[0, 2, 3, 0]
[0, 2, 2, 1]
[0, 2, 1, 2]
[0, 2, 0, 3]
[0, 1, 2, 2]
[0, 0, 3, 2]
[0, 0, 2, 3]
I'm having difficulty finding a general formula for this problem. Any help would be appreciated.

A: Choose which of the $j$ bins have at least $m$ objects in $\binom{k}j$ ways. Let $x_1,x_2,\dots,x_j$ be number of objects minus $j$ in these $j$ bins. Let $y_1,y_2,\dots,y_{k-j}$ be the number of object in the other bins. Then
$$
\begin{align}
x_1+\dots+x_j+y_1+\dots+y_{k-j}&=n-jm,\\
0 &\le x_i,\\
0&\le y_i<m
\end{align}
$$
If we ignored the condition $y_i<m$, then we would have several non negative integers summing to $n-jm$; the number of ways to do this is $\binom{n-jm+k-1}{k-1}$, using stars and bars. In order to account for $y_i<m$, we use inclusion exclusion. Namely, subtract out the bad solutions where $y_i\ge m$ for each $i$, then add back in the doubly subtracted solutions where $y_i\ge m$ and $y_j\ge m$, then subtract out the triply bad solutions, etc. The result is
$$
\binom{k}j\sum_{\ell = 0}^{k-j}\binom{k-j}{\ell}(-1)^\ell \binom{n-(j+\ell)m+k-1}{k-1}
$$
Here, I am using the convention that $\binom{n}k=0$ when $n<k$.


text:
Q: Derivation of Sample Size formula using the Finite Population Correction Factor I have noticed in textbooks that the standard error of the proportion when using the Finite Population Correction Factor is as following:
$\sqrt {\frac {p(1-p)}n \frac {N-n}{n-1}}$
However, when determining the sample size when using the Finite Population Correction Factor, following formula is used:
${\frac {n_0 N}{n_0 + (N - 1)}}$ where $n_0 = {\frac {z^2 p(1-p)}{e^2}}$
How is the above formula derived? Rearranging the standard error equation gives a different result for n as opposed to the sample size formula.

A: I also encountered this, but I am unable to find any source that explains the derivation. From the construction of the term:
$$FPC = \frac{n_{0}N}{n_{0}+(N+1)}$$
In this webpage I found some mention, but no derivation: https://select-statistics.co.uk/calculators/sample-size-calculator-population-proportion/#:~:text=X%20%3D%20Z%CE%B1%2F22,N%20is%20the%20population%20size.


text:
Q: Looking for terminology for the relation of a subject and a predicate While writing some predicates for collection filtering I have stumbled over the choice of the right words for the relation of the subject and the predicate (English is a foreign language for me). What I ended up writing was "Subjects matching this predicate..."
This seems to be incorrect, since predicates are functions and not regular expressions. But saying "Subjects for which this predicate returns true..." sounds awkward to me as well..
So what would be the correct term?

A: I would use "Subjects satisfying this predicate".
Matches implies a pattern, rather than a condition. And "for which this predicate returns true," although the most accurate, sounds more technical than I think you intend.
Edit: Mike makes a good point that predicate is also very technical. Perhaps "Subjects satisfying this condition" is a better option.

A: I think the terminology really depends on your intended audience.
If we're talking about code comments and API documentation then I would say your suggestion would be very accurate and understandable.
"For which this predicate returns true."

If we're writing end user documentation I would avoid the word predicate all together and stick with "filter" and "match".
"Subjects matching your filter."


text:
Q: BigBlueButton and Greenlight - Invalid BigBlueButton Endpoint and Secret when configuring TURN server I had BBB with Greenlight working well.
After configuring the TURN server using the following docs: https://docs.bigbluebutton.org/2.2/setup-turn-server.html#setup-a-turn-server
I get the following error in Greenlight: Invalid BigBlueButton Endpoint and Secret
Note: My BBB secret is valid and is the same for Greenlight .env file.

A: One of the reason may be problem with container DNS
Run bash inside the container with "docker exec -it greenlight-v2 bash" and inside the container try ping google.com. If it return error then open dns file with "vi /etc/resolv.conf" and add extra line for 4.2.2.4 or any dns you like/

A: Same problem (the suggested DNS check passes OK).
Uncommenting turn server in turn-stun-servers.xml :
<bean id="turn1" class="org.bigbluebutton.web.services.turn.TurnServer">
        Secret:
        <constructor-arg index="0" value=" ... same as in turnserevr "/>
        TURN server URL, use turn: or turns:
        <constructor-arg index="1" value="turn:turn.my.domain:443?transport=tcp"/>
        TTL in seconds for shared secret
        <constructor-arg index="2" value="86400"/>
    </bean>

<property name="turnServers">
            <set>
                <ref bean="turn1" />

leads to "Invalid BigBlueButton Endpoint and Secret".
Restarting bbb gives:
# Potential problems described below
# Not running:  tomcat7 or grails LibreOffice
................................................................................
# Error: Could not connect to the configured hostname/IP address
#
#    https://bbb.my.domain/

Also, turnserver launched under turnserver user can't bind
0: Trying to bind fd 16 to <127.0.0.1:443>: errno=13
0: Cannot bind TLS/TCP listener socket to addr 127.0.0.1:443
0: Fatal final failure: cannot bind TLS/TCP listener socket to addr 127.0.0.1:443

A: First you need to check if bbb-conf --secret yield the same endpoint and secret key as in your .env file. If everything looks good then do the following to force renewal of certificate.

*

*apt-get install snapd

*apt-get remove -y certbot

*snap install certbot --classic

*certbot renew --force-renewal --preferred-chain "ISRG Root X1"

*bbb-conf --clean

*sudo systemctl restart ngnix


text:
Q: inject button click listener to loaded webpage in webview I am hoping to listen to click of a button of a webpage loaded via loadUrl method in webview component and listen to the button click. In react-native, we do something like the following with react-native-webview:
const injectScript = () => {
   return `
   let btn = document.getElementById("btn");
     if (btn){
       btn.addEventListener("click", (e) => {
         e.preventDefault();
         alert('clicked');
         });
     }
   `;
 };

//injects the script to  the webview element:
const injectJSToWebView = () => {
  webViewRef.current.injectJavaScript(injectScript());
 }

now the Webview control:
<WebView
     .....
     ref={webViewEleRef}
     javaScriptEnabled={true}
     source={{ uri: "www.eg.com" }}
     injectedJavaScriptForMainFrameOnly={true}
     onLoad={(syntheticEvent) => {
       injectJSToWebView()
     }}
   />

Now i want to do something similar with Kotlin webview but so far, I am not getting any feedback. When I do the following the whole page disappears:
webViewClient = object : WebViewClient() {

            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)

                view?.loadUrl("javascript:document.getElementById('btn').value='test'")
            }
        }

It does found the btn but the whole page is replaced with the value 'test'. I wanted to change just the value of the button but the rest of the page, with its JS to remain in tack.


text:
Q: how to get float as well as int from a python string for key in x:
    if(key=='data'):
        dd = dd.from_dict(x[key])
        dd = dd[:5]

for row in dd.iterrows():
    y = str(row)
    m = re.findall("\d+\.\d+|\d+",y)
    print(m)

I am trying to get some int and float from a string using this code. The problem what I am facing is m=re.findall("\d+\.\d+|\d+",y) is not working as I expected.
Input dataframe is :
0  [2019-10-14T09:15:00+0530, 232.55, 235.2, 231.7, 233, 80683, 0]
1  [2019-10-14T09:20:00+0530, 233, 233, 231.4, 231.8, 53296, 0]
2  [2019-10-14T09:25:00+0530, 231.8, 232.8, 231.1, 231.2, 41238, 0]
3  [2019-10-14T09:30:00+0530, 231.25, 231.4, 230.6, 231.4, 31558, 0]
4  [2019-10-14T09:35:00+0530, 231.4, 231.75, 230.95, 231.05, 29480, 0]

Output is:
['0', '2019', '10', '14', '09', '15', '00', '0530', '232.55', '235.2',
'231.7', '233', '80683', '0', '0']
['1', '2019', '10', '14', '09', '20', '00', '0530', '233', '233', '231.4',
'231.8', '53296', '0', '1']
['2', '2019', '-10', '-14', '09', '25', '00', '0530', '231.8', '232.8', '231.1', '231.2', '41238', '0', '2']

Expected output is :
[ '232.55', '235.2', '231.7', '233', '80683','0']
[ '233', '233', '231.4', '231.8', '53296','0']
[ '231.8', '232.8', '231.1', '231.2', '41238','0']

A: If the date is always first in your list you could simply use the str built-in .split() method as well as list slicing.
In your case i believe replacing
m = re.findall("\d+\.\d+|\d+",y)

by
m = y.split(',')[1:] #splits 'y' str into list and takes elements from index 1 to end

should work if the element you wish to dispose of is always the first.


text:
Q: replace injected mock, with UTest local var mock My Unit-test class file has many tests that uses mock that injected using:
   @InjectMocks
    private Class1 c1 = new Class1();
    @Mock
    private Class2 c2;

(c2 is an attribute of c1)
I would like to test the case when c2 is null.

A: if c2 is attribute of c1 then you have below options
First use constructor based injection to inject c2 thats how u can customize your class object initialisation and pass c2 as null to test the behaviour.
Second you can use ReflectionTestUtils class method setField to set c2 as null for your specific test.
In your test just initialise new object of c1 and use that for your behaviour test.


text:
Q: How can I fetch JsonObjects that change according to user selection in JAVA? I am developing a Currency Converter app using The Free Currency Converter API, I managed to fetch the JSON into Logcat, but I need to get the value of the JSON object from it
This is the JSON:
{
  "USD_INR": 74.61395
}

The INR and USD will change according to user selection, so how can I get the data into my app like this:
example:
weatherData.mCity = jsonObject.getString("name");

This is my code:
package com.example.currencyconverter;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import cz.msebera.android.httpclient.Header;

import static com.loopj.android.http.AsyncHttpClient.log;

public class MainActivity extends AppCompatActivity {
//    https://free.currconv.com/api/v7/convert?q=USD_INR&compact=ultra&apiKey=38b9f7e70c1b1eb6089e

    private String URL = "https://free.currconv.com/api/v7/convert?q=";
    private final String URL_BALANCE = "&compact=ultra&apiKey=38b9f7e70c1b1eb6089e";
    private final String API_KEY = "38b9f7e70c1b1eb6089e";
    String result;
    String[] currency1;
    String[] currency2;
    String name;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Spinner spinner1 = findViewById(R.id.spinner1);
        Spinner spinner2 = findViewById(R.id.spinner2);
        Button myButton = findViewById(R.id.button);

        currency1 = new String[1];
        currency2 = new String[1];

        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.currency_array, R.layout.custom_spinner);

        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        spinner1.setAdapter(adapter);
        spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                currency1[0] = parent.getItemAtPosition(position).toString();
                Log.d("myApp", "currency:" + currency1[0]);
                name = '\u0022' + currency1[0] + "_" + currency2[0] + '\u0022';

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        spinner2.setAdapter(adapter);
        spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                currency2[0] = parent.getItemAtPosition(position).toString();
                Log.d("myApp", "currency:" + currency2[0]);
                name = '\u0022' + currency1[0] + "_" + currency2[0] + '\u0022';

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        myButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String finalURL = URL + currency1[0] + "_" + currency2[0] + URL_BALANCE;

                log.d("myApp", "url:" + finalURL);
                Log.d("myApp", "json:" + name);

                networking(finalURL);

            }
        });

    }

    private void networking(String url) {
        AsyncHttpClient client = new AsyncHttpClient();
        client.get(url, new JsonHttpResponseHandler() {

            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                Log.d("myApp", "JSON" + response.toString());
                try {

                    result = response.getString(name);
                    Log.d("myApp", "result" + result);

                } catch (JSONException e) {
                    e.printStackTrace();

                }

            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                Log.d("myApp", "Request Failed:" + statusCode);
                Log.d("myApp", "Response Fail:" + errorResponse);
                Log.d("myApp", "Error:" + throwable.toString());

            }
        });
    }

}

This is the output I getting:
2021-04-19 08:17:00.803 16457-16457/com.example.currencyconverter D/myApp: currency:USD
2021-04-19 08:17:03.877 16457-16457/com.example.currencyconverter D/myApp: currency:INR
2021-04-19 08:17:04.962 16457-16457/com.example.currencyconverter V/myApp: url:https://free.currconv.com/api/v7/convert?q=USD_INR&compact=ultra&apiKey=38b9f7e70c1b1eb6089e
2021-04-19 08:17:04.962 16457-16457/com.example.currencyconverter D/myApp: json:"USD_INR"
2021-04-19 08:17:06.287 16457-16457/com.example.currencyconverter D/myApp: JSON{"USD_INR":74.61395}

A: Use jsonObject.keys() to get all the keys of the JSON object.  Then you can loop over the return value and request the value associated with that key.

A: I found the solution:
     Iterator<String> keys = response.keys();
     while (keys.hasNext()) {
            String keyValue = keys.next();
            String valueString = response.getString(keyValue);
}


text:
Q: Deciding on version numbers DUPLICATE
How to do version numbers?

Hello,
So I recently saw that Groovy was released to version 1.6 and while listening to the Java Posse Podcast they were commenting how there was so much packed into this release it should have been a 2.0 release.
That got me thinking.  Are version numbers just arbitrary?  I used to think they had a meaning but I guess not.  Is it all just milestone based and set project to project?
How does your team control your version numbers and releases?
Thanks in advance

A: Distinguish between versioning for marketing and versioning for technical use.
For marketing, the answer is: "Whatever you want your customers to think."  In that case, a "major new version" should probably be accompanied by a major version number.
Also be aware that careful customers will be hesitant to use "major" new releases until time has passed and they've tried it in a test environment.  A "build change" release is perceived as having bug fixes and other minor things that don't require much process to install.
For technical use, the answer is: "Whatever information you want to encode for developers."  There's no one correct way to do this; it depends on your goals.
Perhaps a "major" version means "significant changes that might mean lots of new bugs."  Perhaps a new "build" number happens on every single compile.  Perhaps nightly build tags by date are your version.  You can base it on time, Scrum cycles, milestones, features, whatever!

A: They're very much arbitrary. A lot of people like to have something like
[major].[minor].[release].[revision]

as their versioning scheme, but I've also been in companies that refused to release a 1.0 branded product because one of the VPs didn't want to. Marketing also can influence this.
A good question to ask for increasing the major version can be:
If this were a paid product, would customers pay to upgrade to this newer version?
If so, it might be good increase the major number.

A: MajorRelease.MinorRelease.Hotfix

A: Version numbers are arbitary, but there are some rules fo thumb (I think).  Very minor changes or bugfixes usualy increase by 0.0.1, ie V1 becomes V1.0.1.  Minor changes to functionality increases by 0.1.0 i.e V1.0.1 becomes V1.1.0.  Major changes or re-writes get an increase of 1.0.0, i.e to V2.
That said, lot's of companies seem to try to convince customers something is major by going up by 1.0.0 when similar changes have been 0.1.0.  Also, some companies who rely on support contracts will give out 0.1.0 updates for free, but charge for 1.0.0 updates.
Also, IIRC, some projects tend to signify experimental builds with odd versions and stable builds as even ones, (so V3 is dangerous, V4 is stable).

A: In the case of a library, the version number tells you about the level of compatibility between two releases, and thus how difficult an upgrade will be.
A bug fix release needs to preserve binary, source, and serialization compatibility.
Minor releases mean different things to different projects, but usually they don't need to preserve source compatibility.
Major version numbers can break all three forms.
I wrote more about the rationale here.


text:
Q: Jquery to search as user types and have the option to select multiple values I am trying to build this search feature where as user types in a text box i query the server and bring suggestions and show it as a list of options to chose from.
Also multiple selections is expected. Like when we type in the to box of gmail it gives us multiple options we select one than we can start typing again and it will show more options related to the new entry.
The server responds in a json format as
{
"success": "true",
"suggestions": [
    "abc",
    "abd"
]}

I tried using this plugin but the response from server is expected here in a complicated format (which includes image link etc). so it didn't work out.
https://github.com/guille/TextboxList
I tried using some other plugins also but most of them dont have the feature to query the database.
I know that almost all major websites have this feature so there has be a good optimized way to do this. Can you please tell me how to get this done.

A: Check Select2 Api demo with Loading Remote Data  heading at
 http://ivaynberg.github.io/select2/
just change normal <select> to <select multiple="multiple">

A: Please see this jquery UI component this may serve your purpose
Jquery AutoComplete Remote


text:
Q: Could `if-then-else` (always) be replaced by a function call? This question is out of curiousity about how PLs work, more than anything else. (It actually came to me while looking at SML which differs from Haskell in that the former uses call-by-value - but my question is about Haskell.)
Haskell (as I understand) has "call-by-need" semantics.
Does this imply that if I define a function as follows:
cond True thenExp elseExp = thenExp
cond _ thenExp elseExp = elseExp

that this will always behave exactly like an if-then-else expression?
Or, in another sense, can if-then-else be regarded as syntactic sugar for something that could've been defined as a function?

Edit:
Just to contrast the behaviour of Haskell with Standard ML, define (in SML)
cond p t f = if p then t else f;
and then the factorial function
fun factc n = cond (n=0) 1 (n * factc (n-1));
evaluating factc 1 (say) never finishes, because the recursion in the last argument of cond never terminates.
However, defining
fun fact n = if n=0 then 1 else fact (n-1);
works as we expect because the then branch is only evaluated as needed.
Maybe there are clever ways to defer argument evaluation in SML (don't know as I'm not that familiar with it yet) but the point is that in a call-by-value type language, if-then-else often behaves differently.
My question was whether this (call-by-need vs call-by-value) was the principle reason behind this difference (and the consensus seems to be "yes").

A: Like the Haskell Wikipedia on if-then-else says:
For processing conditions, the `if-then-else` **syntax was defined in Haskell98**. However it could be simply replaced by the function `if'`
with

if' :: Bool -> a -> a -> a
if' True  x _ = x
if' False _ y = y
So if we use the above if' function, and we need to evaluate it (since Haskell is lazy, we do not necessary need to evaluate an if-then-else expression at all), Haskell will first evaluate the first operand to decide if it is True or False. In case it is True, it will return the first expression, if it is False it will return the second expression. Note that this does not per se means that we (fully) evaluate these expressions. Only when we need the result, we will evaluate the expressions.
But in case the condition is True, there is no reason at all to ever evaluate the second expression, since we ignore it.
In case we share an expression over multiple parts of the expression tree, it is of course possible that another call will (partially) evaluate the other expression.
ghci even has an option to override the if <expr> then <expr> else <expr> syntax: the -XRebindable flag. It will, besides other things also:

Conditionals (e.g. if e1 then e2 else e3) means ifThenElse e1 e2 e3. However case expressions are unaffected.

A: Yes, a lazy language will evaluate an expression only when it needs to. Therefore it is no problem to convert the then/else parts of the expression into function arguments.
This is unlike strict languages like Idris or OCaml, where arguments for a function call are evaluated before the called function is executed.

A: Yes, you can regard if/then/else as syntactic sugar. In fact, a programming language doesn't even need Boolean primitives, so you can also consider True and False as syntactic sugar.
The lambda calculus defines Boolean values as a set of functions that take two arguments:
true = λt.λf.t
false = λt.λf.f

Both functions are functions that takes two values, t for true, and f for false. The function true always returns the t value, whereas the function false always returns the f value.
In Haskell, you can define similar functions like this:
true  = \t f -> t
false = \t f -> f

You could then write your cond function like:
cond = \b t f -> b t f

Examples:
Prelude> cond true "foo" "bar"
"foo"
Prelude> cond false "foo" "bar"
"bar"

Read more in Travis Whitaker's article Scrap Your Constructors: Church Encoding Algebraic Types.


text:
Q: Compilation error when deploying IIS project in server error -2146232576 I made an MVC project using VS 2017
I was using IIS Server v10 on my local machine for testing, now that Im uploading my project to the server w/Windows server 2008 and IIS Server v6 I get the following compilation error code -2146232576
I already tried the following solution Compilation error -2146232576 removing the packages with nuget PM - > Microsoft.CodeDom.Providers.DotNetCompilerPlatform
and Microsoft.Net.Compilers from my project, but it didn't work.
Im also not deploying the project from VS2017 using web deployment tool, Im accessing from a remote desktop to the server, and "Adding a new website" from the IIS Server Admin tool, the project folder is in a "Cloud folder", so I attach the new website to that folder.
Any help will be really appreciated, thanks!
BTW, If I click "See compiler results" I get the following :

c:\windows\system32\inetsrv>D:\Intranet\Intranet
  Nueva\InventariosBodega\InventoryMVC\bin\roslyn\csc.exe /t:library
  /utf8output /nostdlib+
  /R:"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\mscorlib.dll"
  /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Runtime\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Runtime.dll"
  /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel\v4.0_4.0.0.0__b77a5c561934e089\System.ServiceModel.dll"
  /R:"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET
  Files\root\e9dba4d1\4d6ed61a\assembly\dl3\28c4dd2b\0074b766_899bd301\System.Web.Helpers.dll"
  /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Xml\v4.0_4.0.0.0__b77a5c561934e089\System.Xml.dll"
  /R:"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET
  Files\root\e9dba4d1\4d6ed61a\assembly\dl3\f76361e7\0074b766_899bd301\System.Web.WebPages.Razor.dll"
  /R:"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET
  Files\root\e9dba4d1\4d6ed61a\assembly\dl3\dd2c8dcd\00405cc9_889bd301\System.Web.Mvc.dll"
  /R:"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET
  Files\root\e9dba4d1\4d6ed61a\assembly\dl3\ee1ff4a7\00fb1244_1dacd301\Microsoft.AI.ServerTelemetryChannel.dll"
  /R:"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET
  Files\root\e9dba4d1\4d6ed61a\assembly\dl3\0c5caa47\0074b766_899bd301\System.Web.WebPages.Deployment.dll"
  /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System\v4.0_4.0.0.0__b77a5c561934e089\System.dll"
  /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Activities\v4.0_4.0.0.0__31bf3856ad364e35\System.Activities.dll"
  /R:"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET
  Files\root\e9dba4d1\4d6ed61a\assembly\dl3\4652d562\00f41bc5_6e64d301\ExcelNumberFormat.dll"
  /R:"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET
  Files\root\e9dba4d1\4d6ed61a\assembly\dl3\21ff0145\006fa443_52f0d201\Microsoft.AspNet.TelemetryCorrelation.dll"
  /R:"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET
  Files\root\e9dba4d1\4d6ed61a\assembly\dl3\387466b6\80ac78b8_cf60d401\InventoryMVC.dll"
  /R:"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET
  Files\root\e9dba4d1\4d6ed61a\assembly\dl3\bed44328\0084c160_bb46d301\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.dll"
  /R:"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET
  Files\root\e9dba4d1\4d6ed61a\assembly\dl3\8fad2587\00fa1531_3eb5d301\FastMember.Signed.dll"
  /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Activities\v4.0_4.0.0.0__31bf3856ad364e35\System.ServiceModel.Activities.dll"
  /R:"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET
  Files\root\e9dba4d1\4d6ed61a\assembly\dl3\554cddff\00048ad2_4adfd201\DocumentFormat.OpenXml.dll"
  /R:"C:\Windows\Microsoft.Net\assembly\GAC_64\System.Web\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Web.dll"
  /R:"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET
  Files\root\e9dba4d1\4d6ed61a\assembly\dl3\627ae2bf\0026839d_2dacd301\Microsoft.AI.PerfCounterCollector.dll"
  /R:"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET
  Files\root\e9dba4d1\4d6ed61a\assembly\dl3\85ea1a5f\00dd11c0_9fc7d301\EntityFramework.dll"
  /R:"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET
  Files\root\e9dba4d1\4d6ed61a\assembly\dl3\4b71c96c\008b5b5b_7518cf01\WebGrease.dll"
  /R:"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET
  Files\root\e9dba4d1\4d6ed61a\assembly\dl3\d1c7755a\007e36de_6f27cf01\System.Web.Optimization.dll"
  /R:"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET
  Files\root\e9dba4d1\4d6ed61a\assembly\dl3\c290801e\00d0aa3b_992ad401\ClosedXML.dll"
  /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Xml.Linq\v4.0_4.0.0.0__b77a5c561934e089\System.Xml.Linq.dll"
  /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Activation\v4.0_4.0.0.0__31bf3856ad364e35\System.ServiceModel.Activation.dll"
  /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.Services\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Web.Services.dll"
  /R:"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET
  Files\root\e9dba4d1\4d6ed61a\assembly\dl3\6c38dd12\00b64a64_2dacd301\Microsoft.AI.Web.dll"
  /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Configuration\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Configuration.dll"
  /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.Extensions\v4.0_4.0.0.0__31bf3856ad364e35\System.Web.Extensions.dll"
  /R:"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET
  Files\root\e9dba4d1\4d6ed61a\assembly\dl3\8a8f3694\00dd11c0_9fc7d301\EntityFramework.SqlServer.dll"
  /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.ApplicationServices\v4.0_4.0.0.0__31bf3856ad364e35\System.Web.ApplicationServices.dll"
  /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Runtime.Serialization\v4.0_4.0.0.0__b77a5c561934e089\System.Runtime.Serialization.dll"
  /R:"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET
  Files\root\e9dba4d1\4d6ed61a\assembly\dl3\17fb612d\00f9519c_2dacd301\Microsoft.AI.WindowsServer.dll"
  /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.CSharp\v4.0_4.0.0.0__b03f5f7f11d50a3a\Microsoft.CSharp.dll"
  /R:"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET
  Files\root\e9dba4d1\4d6ed61a\assembly\dl3\a2f7474a\005caad7_889bd301\System.Web.Razor.dll"
  /R:"C:\Windows\Microsoft.Net\assembly\GAC_64\System.Data\v4.0_4.0.0.0__b77a5c561934e089\System.Data.dll"
  /R:"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\mscorlib.dll"
  /R:"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET
  Files\root\e9dba4d1\4d6ed61a\assembly\dl3\40d8bd40\00a03031_75aece01\Antlr3.Runtime.dll"
  /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Web\v4.0_4.0.0.0__31bf3856ad364e35\System.ServiceModel.Web.dll"
  /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Core\v4.0_4.0.0.0__b77a5c561934e089\System.Core.dll"
  /R:"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET
  Files\root\e9dba4d1\4d6ed61a\assembly\dl3\4338dd4e\00f41cc3_8d6acd01\Microsoft.Web.Infrastructure.dll"
  /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Data.DataSetExtensions\v4.0_4.0.0.0__b77a5c561934e089\System.Data.DataSetExtensions.dll"
  /R:"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET
  Files\root\e9dba4d1\4d6ed61a\assembly\dl3\21d2e02d\00efe283_77efd201\Microsoft.AI.Agent.Intercept.dll"
  /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.WorkflowServices\v4.0_4.0.0.0__31bf3856ad364e35\System.WorkflowServices.dll"
  /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Drawing\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Drawing.dll"
  /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.ComponentModel.DataAnnotations\v4.0_4.0.0.0__31bf3856ad364e35\System.ComponentModel.DataAnnotations.dll"
  /R:"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET
  Files\root\e9dba4d1\4d6ed61a\assembly\dl3\d123d09e\000abfde_1cacd301\Microsoft.ApplicationInsights.dll"
  /R:"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET
  Files\root\e9dba4d1\4d6ed61a\assembly\dl3\3bf86b34\0074b766_899bd301\System.Web.WebPages.dll"
  /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.DynamicData\v4.0_4.0.0.0__31bf3856ad364e35\System.Web.DynamicData.dll"
  /R:"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET
  Files\root\e9dba4d1\4d6ed61a\assembly\dl3\890412f9\00db9f04_2cacd301\Microsoft.AI.DependencyCollector.dll"
  /R:"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET
  Files\root\e9dba4d1\4d6ed61a\assembly\dl3\5ef1cd79\0069d048_a800d301\System.Diagnostics.DiagnosticSource.dll"
  /R:"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET
  Files\root\e9dba4d1\4d6ed61a\assembly\dl3\ecd0c0d7\005f8d6b_cfa8d301\Newtonsoft.Json.dll"
  /R:"C:\Windows\Microsoft.Net\assembly\GAC_64\System.EnterpriseServices\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.EnterpriseServices.dll"
  /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.IdentityModel\v4.0_4.0.0.0__b77a5c561934e089\System.IdentityModel.dll"
  /out:"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary
  ASP.NET Files\root\e9dba4d1\4d6ed61a\App_global.asax.sntr_4gi.dll"
  /D:DEBUG /debug+ /optimize- /warnaserror- /w:4
  /nowarn:1659;1699;1701;612;618 /langversion:6 /nowarn:1659;1699;1701
  "C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET
  Files\root\e9dba4d1\4d6ed61a\App_global.asax.sntr_4gi.0.cs"
  "C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET
  Files\root\e9dba4d1\4

A: The compiler error relates to a "Desktop Heap exhaustion", the compiler is effectively encountering a (a very specific type of) memory limit when attempting to compile your application.
Bottom line, this is a very old server and i strongly advice you upgrade to a more modern version of Windows.  If you cant, the following may help:

*

*It may be possible to build the site locally and deploy the binaries - this should prevent the need to compile your code server side and work-around your immediate issue - but the "age gap" between your OS and your chosen technologies to build your app could cause further issues down the road - this is a legacy operating system after all.

*Another option is to change the user your app pool is running under - assuming you have more than 1 app pool using the same identity this will be eating into the various per user memory limits (which are now 10 years old!) - again this might side-step your issue.

*Your final option is a registry edit to increase the Desktop Heap size of csrss (Client server runtime sub-system) - DISCLAIMER: editing the registry is fine if done correctly, but does include the possibility of rendering your server unbootable - make sure you understand the process and have a viable backup etc etc etc before proceeding.
Under the registry path: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\SubSystems the Windows key has a command starting %SystemRoot%\system32\csrss.exe and includes an argument SharedSection= followed by 3 comma separated numbers. The 3rd value needs to be increased to change the desktop heap size. Ive seen guidance vary, so i would suggest start small - take the current value, add 1024 or 2048 at a time until the error goes away - dont go crazy with this setting - values are in KiloBytes so 1024KB = 1 Megabyte - you shouldnt need more than a few MB for this value. A Reboot will be required to make the change active after editing the registry.
Below article applies to Server 2008 (but i dont have access to a machine to test!!!) and give more detailed instructions:
https://blogs.msdn.microsoft.com/friis/2012/09/19/c-compiler-or-visual-basic-net-compilers-fail-with-error-code-1073741502-when-generating-assemblies-for-your-asp-net-site/
Last thing... Server 2008/2008R2 will reach end of life January 14, 2020 - no more patches - make sure this server is turned off before then...  https://www.microsoft.com/en-us/cloud-platform/windows-server-2008


text:
Q: Javascript Object Prototype 'this' empty in Promise I'm not sure why in this code snippet the last 'this' in the open method is returning an empty object. Outside of the arrow function 'this' returns the correct information. Using an arrow function should essentially bind it to the same 'this' I thought, but it's just returning undefined...
'wrap' is a wrapper function for my async code.
let Client = wrap(async function (host, opts) {
    if (!(this instanceof Client)) {
        return new Client(host, opts);
    }

    this.host = host;
    this.opts = opts;

    await this.open();

    return this;
});

Client.prototype.open = wrap(async function () {
    // Omitted most code here as it doesn't influence the problem at all.

    console.log(this); // Works

    (function (test) {
        console.log(test); // Works
    })(this);

    await new Promise(function (resolve, reject) {
        console.log(this); // Obviously Undefined
    });

    await new Promise(function (resolve, reject) {
        console.log(this); // Works, but is ugly.
    }.bind(this));

    await new Promise((resolve, reject) => {
        console.log(this); // Returns empty object {}. Why?
    });
});

If I put the logic in the main Client code, or don't use prototype everything works fine. But the second I prototype it, it breaks.


text:
Q: Selenium not working with opera I'm creating a program to go into my router and adjust settings, and to do it from different browsers, I've got FF, Chrome, and IE to work. Everything I try with Opera won't work. It only opens up two tabs, one with 127.0.0.1:some_crazy_port# and file:///C:/Users/EETEST~1/AppData/Local/Temp/opera4672404649060883314profile/
When I'm trying to get to, 192.168.0.1
System: Windows 7: Eclipse Kepler & Selenium 2.37.0
Here's my code:
import com.opera.core.systems.OperaDriver;
import com.thoughtworks.selenium.*;

import org.junit.Test;
import org.openqa.selenium.*;
import org.openqa.selenium.support.ui.Select;

public class NewTest extends SeleneseTestCase {

private WebDriver cDriver;
private String baseUrl;

    public void setUp() throws Exception{
        baseUrl = "192.168.0.1";//Heres the destination
        System.setProperty("webdriver.opera.driver", "C:\\Program Files (x86)\\Opera");
        cDriver = new OperaDriver();//Setting up the OperaDriver
    }

    @Test
    public void test() throws Exception{
        try{
            cDriver.navigate().to(baseUrl);//Go!
            //Thread.sleep(5000);//Everything below is just doing stuff on the page
            cDriver.findElement(By.id("radioButtonssBasic")).click();
            Select selector = new Select(cDriver.findElement(By.id("ap")));
            selector.selectByValue("0SSIDisNAMED"+router);
            cDriver.findElement(By.name("passphrase1")).sendKeys(routerPass);
            cDriver.findElement(By.name("passphrase2")).sendKeys(routerPass);
            cDriver.findElement(By.id("user")).sendKeys(user);
            cDriver.findElement(By.name("password1")).sendKeys(userPass);
            cDriver.findElement(By.name("password2")).sendKeys(userPass);
            cDriver.findElement(By.id("submitButton")).click();
        }finally{
        Thread.sleep(2000);
        cDriver.quit();
        }

A: For Opera versions below 12, use OperaPrestoDriver
https://github.com/operasoftware/operaprestodriver
For Opera versions above 12, use operachromiumdriver
https://github.com/operasoftware/operachromiumdriver/releases

A: Which version of Opera are you using? As far as I understand the OperaDriver won't support any Opera versions > 12.x.

Current implementation of OperaDriver supports only 12.x and older versions of Opera browser (based on Presto engine) and does not support newer versions (based on Blink engine).

Since Opera dropped the WebKit engine and started using Google's Blink engine, I assume there has to be another driver to support Opera.
I'm currently searching for a solution myself, so I don't really know if there is one yet.


text:
Q: Visual Studio can't 'see' my included header files I created an empty 'Demo' project in Visual Studio 2008 and added some existing projects to my solution. Included "MyHeader.h" (other project's header) in main.cpp file which is in 'Demo'. Also added header files' path in "Tools/Option/VC++ Directories/Include files" section. But intellisense says: "File MyHeader.h not found in current source file's directory or in build system paths..."
How the problem can be fixed?

A: This happened to me just now, after shutting down and restarting the computer. Eventually I realised that the architecture had somehow been changed to ARM from x64.

A: In Visual Studio 2019 in my case I copied a header file into the project directory, just near the other files. Intellisense could see it, but the build failed. Fair enough, it wasn't actually added to the project. I added it as existing item but this is the point that Visual Studio still didn't account for it.
Solution:

*

*Close the project.

*Delete the .vs directory.

*Reopen the project.
Now Visual Studio recreates the directory with everything in it and it can now see the included file.

A: If it is the case that only the IDE indicates that it cannot find included files, but compiling is successful, the issue is simply that IntelliSense is not fully up to date with recent changes. This can happen specifically when including existing projects, in my own experience.
Deleting the .sdf file (= IntelliSense database) that is generated in your solution directory forces Visual Studio to regenerate it, so that it is up to date again. Just doing a "clean" will probably do the same thing, but takes more time since everything will be generated again then.

A: I know this is an older question, but none of the above answers worked for me. In my case, the issue turned out to be that I had absolute include paths but without drive letters. Compilation was fine, but Visual Studio couldn't find an include file when I right-clicked and tried to open it. Adding the drive letters to my include paths corrected the problem.
I would never recommend hard-coding drive letters in any aspect of your project files; either use relative paths, macros, environment variables, or some mix of the tree for any permanent situation. However, in this case, I'm working in some temporary projects where absolute paths were necessary in the short term. Not being able to right-click to open the files was extremely frustrating, and hopefully this will help others.

A: Delete the .sdf file that is in your solution directory. It's just the Intellisense database, and Visual Studio will recreate it the next time you open that solution. This db can get corrupted and cause the IDE to not be able to find things, and since the compiler generates this information for itself on the fly, it wouldn't be affected.

A: If you choose Project and then All Files in the menu, all files should be displayed in the Solution Explorer that are physically in your project map, but not (yet) included in your project. If you right click on the file you want to add in the Solution Explorer, you can include it.

A: Had the same problem. Double check if you added the include files to Debug or Release Version of your project. If you only added it for one of them and compile for the other VS will just play dumb and not find them.

A: Try adding the header file to your project's files. (right click on project -> add existing file).

A: In my experience, with VS2010, when include files can't be found at compile time, doing a clean, then build usually fixes the problem. It's not that rare for the editor to be able to open an include file and then the compiler to announce that it can't find that very file, even when it is open on the screen!

A: If the visual studio says that you miss some file in the current source file folder, there is one solution that i used. Just right click the file you want to add and choose Open Document, if it really doesn't exist, then you should see something like cannot find file in the source file path = "somewhere in your computer", then what you could do is the add your source file into that path first and see if it works.

A: I had this issue after upgrading to Visual Studio 2019 from 2015. It would compile the project fine but Intellisense and the IDE couldn't find any header files.
The project only had valid configuration for Win32/Debug. Include paths were not setup correctly for other environments. Even though Visual Studio displayed the current environment as Win32/Debug, Intellisense must have been using something else.
Changing the current environment to x64/Release, and then back to Win32/Debug fixed it.

A: In Visual Studio, click on Project > Rescan Solution as shown below to rebuild the project database.

A: Here's how I solved this problem.

*

*Go to Project --> Show All Files.

*

*Right click all the files in Solutions Explorer and Click on Include in Project in all the files you want to include.

Done :)

A: I encountered this issue, but the solutions provided didn't directly help me, so I'm sharing how I got myself into a similar situation and temporarily resolved it.
I created a new project within an existing solution and copy & pasted the Header and CPP file from another project within that solution that I needed to include in my new project through the IDE. Intellisense displayed an error suggesting it could not resolve the reference to the header file and compiling the code failed with the same error too.
After reading the posts here, I checked the project folder with Windows File Explorer and only the main.cpp file was found. For some reason, my copy and paste of the header file and CPP file were just a reference? (I assume) and did not physically copy the file into the new project file.
I deleted the files from the Project view within Visual Studio and I used File Explorer to copy the files that I needed to the project folder/directory. I then referenced the other solutions posted here to "include files in project" by showing all files and this resolved the problem.
It boiled down to the files not being physically in the Project folder/directory even though they were shown correctly within the IDE.
Please Note I understand duplicating code is not best practice and my situation is purely a learning/hobby project.  It's probably in my best interest and anyone else who ended up in a similar situation to use the IDE/project/Solution setup correctly when reusing code from other projects - I'm still learning and I'll figure this out one day!

A: If some soul has scrolled down to this bottom, what worked for me was disabling the Disable Database option i.e. set it to False under Tools|Options|Text Editor|C/C++|Advanced. For some reason, it was set to True for me.

As per docs, if it's set to True

All use of the code browsing database (SDF), all other
Browsing/Navigation options, and all IntelliSense features except for
#include Auto Complete are disabled.

A: None of the solutions worked for me. Here is what was the issue for me:
(Note discrepancy in build configuration and VC++ Directories (x86 vs x64)

To fix, just changed the build configuration to 'x86':


text:
Q: How can I code-behind use Font Awesome in Xamarin Forms? I'm having difficulty creating a form with Font Awesome text. Everything works fine when I'm doing it in .xaml file, like this:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
             x:Name="contentPage"
             xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="myappname.Main">
   <Label Text=""
          FontFamily="Font Awesome 5 Free-Solid-900.otf#Regular"
          FontSize="40" />
</ContentPage>

The result is:

Assets catalog:

I'm not creating my app for iOS so I haven't added any additional configuration, i.e. configuring ResourceDictionary. This is what I've tried in Main.xaml.cs (I'll show three ways of doing it because I'm not sure how exactly it should work):
protected override async void OnAppearing()
{
    Label newLabel = new Label()
    {
        Text = "",
        FontFamily = "Font Awesome 5 Free-Solid-900.otf#Regular",
        FontSize = 40
    };

    contentPage.Content = newLabel;
}

protected override async void OnAppearing()
{
    Label newLabel = new Label()
    {
        Text = "",
        FontFamily = "Font Awesome 5 Free-Solid-900.otf#Font Awesome 5 Free-Solid-900.otf",
        FontSize = 40
    };

    contentPage.Content = newLabel;
}

protected override async void OnAppearing()
{
    Label newLabel = new Label()
    {
        Text = "",
        FontFamily = "Font Awesome 5 Free-Solid-900.otf#Font Awesome 5 Free-Solid-900",
        FontSize = 40
    };

    contentPage.Content = newLabel;
}

The result in every of them is:

What am I doing wrong?

A: Try using \u instead of &#x
so it should look like this:
Text = "\uf00c",