text:
Q: Incorrect margins with Res.cls trying to improve spacing I know the res class is now considered obsolete, but I can't help myself. I don't like ModernCV's aesthetic, and I couldn't find any comparable alternatives. Michael DeCorte's design is simplistic and traditional. A quick search shows there are still some people that agree.
So, I have made all the proper adjustments, added some custom lists, and specified my paper width and height, but I can't help but notice that there is still some white space at the bottom of the document. The margins don't appear evenly spaced. I have reduced my CV to only the essentials. I cannot remove any more information, but I want more space between everything. I feel the lists need more spacing as well as the labels on the left margin. Is there room in the margins that I can utilize? What can I do to get better spacing? Thank you!!
Here is the res.cls file I'm using:
https://gist.github.com/89sundown/a2ca5aa0e480f45216872a30aabf970f
Here is the LaTeX:
\documentclass[margin,line]{res}

\topmargin=-.5in
\oddsidemargin -.5in
\evensidemargin -.5in
\textwidth=6.0in
\itemsep=1in
\parsep=0in
%if using pdflatex:
\setlength{\pdfpagewidth}{\paperwidth}
\setlength{\pdfpageheight}{\paperheight}

\newenvironment{list1}{
  \begin{list}{\ding{113}}{%
      \setlength{\itemsep}{0in}
      \setlength{\parsep}{0in} \setlength{\parskip}{0in}
      \setlength{\topsep}{0in} \setlength{\partopsep}{0in}
      \setlength{\leftmargin}{0.15in}}}{\end{list}}
\newenvironment{list2}{
  \begin{list}{$\bullet$}{%
      \setlength{\itemsep}{0in}
      \setlength{\parsep}{0in} \setlength{\parskip}{0in}
      \setlength{\topsep}{0in} \setlength{\partopsep}{0in}
      \setlength{\leftmargin}{0.2in}}}{\end{list}}
\newenvironment{list3}{
  \begin{list}{$\bullet$}{%
      \setlength{\itemsep}{0.02in}
      \setlength{\parsep}{0in} \setlength{\parskip}{0in}
      \setlength{\topsep}{0in} \setlength{\partopsep}{0in}
      \setlength{\leftmargin}{0in}}}{\end{list}}

\pagenumbering{gobble}
\begin{document}

\name{Xxx x. Xxxxx \vspace*{.05in}}

\begin{resume}
\vspace{-.2cm}
\section{\sc {\bf Contact Information}}
\begin{tabular}{@{}p{2in}p{4in}}
Address xxxxxx             & {\it Voice:}  (xxx) xxx-xxxx \\
Xxxxxxx, XX  XXXXX US   & {\it E-mail:}  x@email $\vert$ xxxx@xxx.edu\\
\end{tabular}

\vspace{-.35cm}
\section{\sc {\bf Professional Aspirations}}
Obtain a Ph.D. in Computational Mathematics, develop specialized knowledge, contribute to ongoing research, and be well-regarded within the scientific community.
\vspace{-.35cm}
\section{\sc {\bf Education}}
\begin{list3}
\item[]{\bf A University}, State, Country USA
\item[]Associates of Science in Mathematics \hfill May Xxxx
\item[]G.P.A 4.0 $\vert$ Xxxxxx College $\vert$ Xxxxx Scholar
\item[]President's List: Xxxxx - Xxxxxx
\item[]Bachelors of Science in Mathematics \hfill May Xxxx
\end{list3}

%\begin{list1}
%\item[] Associate of Science in Mathematics
%\end{list1}
%\begin{list2}
%\vspace*{.05in}
%\item[] Pending Fall 2023 applications of acceptance to Georgia Tech
%\end{list2}
%\vspace*{.05in}
%\item[] Enrolled in BA in mathematics at Georgia State University Graduation May 2025
%\end{list1}
\vspace{-.35cm}
\section{\sc {\bf Honors and Awards}}

\begin{list3}
\item[] {\it X.X.X.X. Award: Mathematics} \hfill  Spring 2022
\item[] {\it A wonderful Scholarship} \hfill Spring 2023
\item[] {\it A wonderful Scholarship} \hfill Spring 2023
\item[] {\it A very wonderful Scholarship Nominee} \hfill  Pending award Mar 2023
\end{list3}
\vspace{-.35cm}
\section{\sc {\bf Research Experience}}

{\em {\bf Xxxxxx xxxxxx xxxxxx xxxxxx xxxxx (R.E.U.)}} \hfill  Aug 2022 - present\\
One of seven students selected to participate in a paid R.E.U. program over a two-semester period funded by a grant.
% When I entered the program, I came with a question in mind that I wanted to explore in game theory.
\vspace*{.04in}
\begin{list1}
\item[] {\bf Presentations}
\begin{list2}
\item XXXXX, Xxx. 2022. ``XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'' Talk presented at the X. XXXXXXXXX, XXXXXX XXXX XXXXX, November 29
\item XXXXX, Xxx. 2023. ``XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'' Talk presented at the XXXXXXXXXXXXXXXXXXXX on Undergraduate Mathematics and Statistics Research, II. XXXXXXX XXXXXXXX of XXXXXX, XXXXXXX, XXXX
\end{list2}
\end{list1}
\vspace*{.04in}
\begin{list1}
\item[] {\bf Skills Acquired}: Zotero, Obsidian, Visio, data management \& visaulization, independent study, mathematical communication, manuscript writing.
\end{list1}

\vspace{-.35cm}

{\em {\bf XXXXXXXXXXXXXXXXXXXX}} \hfill  Jun 2022 - Aug 2022\\ %italizize the header
One of 14 students participating in the Math Path program, a paid six-week summer research program funded by the XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.
\vspace*{.04in}
\begin{list1}
\item[] {\bf Presentations} %remove the first person pronouns
\begin{list2}
\item Xxxxx, Xxx, Xxxxx Xxxxx, Xxxxx Xxxxx, and Xxxx Xxxx. 2022. ``XXxxxXXXXXXXXXXX'' Poster xxxx Presentation presented at the most wonderful xxxx  symposium ever at sometime during xxxx the summer.
\end{list2}
\vspace*{.04in}
\end{list1}
\begin{list1}
\item[] {\bf Skills Acquired}: Mathematica, Python, programming logic, graph \& game theory, induction, poster creation, team research \& communication, \LaTeX \, \& Beamer.
\end{list1}
\vspace{-.35cm}

{\em {\bf XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX}} \hfill May 2022\\
This program was a paid three-week program funded by a XXXX XXXXX XXXXX XXXX XXX. The focus of the program was to teach students the fundamentals of research.
\vspace*{.04in}
\begin{list1}
\item[] {\bf Skills Acquired}: Research methodology, data analysis, literature review, presentation design.
\end{list1}
\vspace{-.35cm}

\section{\sc {\bf Academic Experience \& Other Activies}}

{\em {\bf XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX}} \hfill Jan 2022 - present\\
Hold weekly sessions to support students in Calculus 2 and Discrete Mathematics, develop lesson plans based on the professor's weekly material, and participate in classes to build relationships.
\vspace{-.35cm}

{\em {\bf XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX}} \hfill Aug 2022 - Present\\
Xxxxx is a monthly undergrad math research seminar, led by students. Duties involve organizing presenters, reaching out to partner universities, and promoting community growth.
\vspace{-.35cm}

\section{\sc {\bf Professional Experience}}

\begin{list3}
\item[] {\em {\bf Project Manager}, {\it Xxxx Xxxxx Xxxx Xxx.}} \hfill  Xxxxx, XX – 2018 – 2020
\item[] {\em {\bf Operations Manager}, {\it Xxxxxxxx, Xxx}} \hfill  Xxxxx, XX – 2018 – 2020
\item[] {\em {\bf Project Manager}, {\it Xxx Xxx Xxxxxx, Xxxx}} \hfill Xxxxxx, XX – 2015 – 2018
\item[] {\em {\bf Project Manager}, {\it Xxxxx Xxxx. Xx. Xxx}} \hfill Xxxxxx, XX – 2010 – 2015
\end{list3}

\vspace{-.3cm}

\end{resume}
\end{document}


text:
Q: Format json array in required format this is the json format
[ { baseurl: 'http://localhost:5051/springbootdemo/getServerData',
    server: '1' },
  { baseurl: 'http://localhost:5052/springbootdemo/getServerData',
    server: '1' },
  { baseurl: 'http://localhost:5053/springbootdemo/getServerData',
    server: '2' },
  { baseurl: 'http://localhost:5054/springbootdemo/getServerData',
    server: '2' } ]

i want to re arrange it in this form
[
  {server:1 , urls: [
    "http://localhost:5051/springbootdemo/getServerData",
    "http://localhost:5052/springbootdemo/getServerData"
  ]},
  {server:2 , urls: [
    "http://localhost:5053/springbootdemo/getServerData",
    "http://localhost:5054/springbootdemo/getServerData"
  ]}`enter code here`
]

I want the re arrangement in above format.

A: Firstly, that's not JSON - it's an ordinary array. Secondly, you can use reduce like so:

const arr = [{baseurl:'http://localhost:5051/springbootdemo/getServerData',server:'1'},{baseurl:'http://localhost:5052/springbootdemo/getServerData',server:'1'},{baseurl:'http://localhost:5053/springbootdemo/getServerData',server:'2'},{baseurl:'http://localhost:5054/springbootdemo/getServerData',server:'2'}];
const res = Object.values(arr.reduce((a, { baseurl, server }) => {
  (a[server] = a[server] || { server: +server, urls: [] }).urls.push(baseurl);
  return a;
}, {}));

console.log(res);
.as-console-wrapper { max-height: 100% !important; top: auto; }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Files in Lua program not able to reference each other's variables I'm hoping somebody experienced can point out where/if I am missing some crucial syntax.
My program works fine (because 95% of it was created by a CS50 professor), with one exception - I cannot seem to get the player and flag files/classes to reference each other to show that my Mario character has reached the final flag.
Specifically, the function "Flag:victory(player)" does not appear to be pulling information from the player file/class, while player has a similar function that is able to access Flag, although I don't see any difference between the two files as to why Flag is not behaving properly.
Flag = Class{}

function Flag:init(map)
    -- reference to map for checking tiles

    self.texture = map.spritesheet

    -- animation frames
    self.frames = {}

    -- current animation frame
    self.currentFrame = nil
    self.player = Player(map)

    -- used to determine behavior and animations
    self.state = 'waving'

    -- x and y velocity
    self.dy = 0

    -- position on top of map tiles
    self.y = map.tileHeight * ((map.mapHeight / 2) - 4)
    self.x = (map.mapWidth - 3) * map.tileWidth

    -- initialize all player animations
    self.animations = {
        ['waving'] = Animation({
            texture = self.texture,
            frames = {
                love.graphics.newQuad(0, 48, 16, 16, self.texture:getDimensions()),
                love.graphics.newQuad(16, 48, 16, 16, self.texture:getDimensions()),
                love.graphics.newQuad(0, 48, 16, 16, self.texture:getDimensions()),
            },
            interval = 0.30
        }),
        ['falling'] = Animation({
            texture = self.texture,
            frames = {
                love.graphics.newQuad(32, 48, 16, 16, self.texture:getDimensions())
            }
        })
    }

    -- initialize animation and current frame we should render
    self.animation = self.animations['waving']
    self.currentFrame = self.animation:getCurrentFrame()
end

function Flag:update(dt)
    self.animation:update(dt)
    self.currentFrame = self.animation:getCurrentFrame()
    self:victory()
end

function Flag:render()
    local scaleX = - 1

    -- draw sprite with scale factor and offsets
    love.graphics.draw(self.texture, self.currentFrame, math.floor(self.x + 8 / 2),
        math.floor(self.y + 8 / 2), 0, scaleX, 1, 8 / 2, 8 / 2)
end

function Flag:victory(player)
    if self.player.victory == true then -- when player reaches flag
        self.state = 'falling' -- change flag animation to down sprite
        self.animation = self.animations['falling']
        self.y = self.y + 2 -- descend the flag
    end
end

--[[
    Represents our player in the game, with its own sprite.
]]

Player = Class{}

local WALKING_SPEED = 140
local JUMP_VELOCITY = 400

function Player:init(map)

    self.x = 0
    self.y = 0
    self.width = 16
    self.height = 20

    -- offset from top left to center to support sprite flipping
    self.xOffset = 8
    self.yOffset = 10

    -- reference to map for checking tiles
    self.map = map -- just a convenience because map comes in as a param/arg so the self should be dropped
    self.texture = love.graphics.newImage('graphics/blue_alien.png')

    -- sound effects
    self.sounds = {
        ['jump'] = love.audio.newSource('sounds/jump.wav', 'static'),
        ['hit'] = love.audio.newSource('sounds/hit.wav', 'static'),
        ['coin'] = love.audio.newSource('sounds/coin.wav', 'static'),
    }

    -- variable for playing sound just once when game ends
    self.musicplayed = false
    -- animation frames
    self.frames = {}

    -- current animation frame
    self.currentFrame = nil

    -- used to determine behavior and animations
    self.state = 'idle'

    -- determines sprite flipping
    self.direction = 'left'

    -- x and y velocity
    self.dx = 0
    self.dy = 0

    -- position on top of map tiles
    self.y = map.tileHeight * ((map.mapHeight - 2) / 2) - self.height
    self.x = map.tileWidth * 10
    self.xmax = self.x -- farthest that mario has ever gone to the right
    self.xmin = 1 -- farthest mario may go to the left, based on xmax and left border of map

    -- initialize all player animations
    self.animations = {
        ['idle'] = Animation({
            texture = self.texture,
            frames = {
                love.graphics.newQuad(0, 0, 16, 20, self.texture:getDimensions())
            }
        }),
        ['walking'] = Animation({
            texture = self.texture,
            frames = {
                love.graphics.newQuad(128, 0, 16, 20, self.texture:getDimensions()),
                love.graphics.newQuad(144, 0, 16, 20, self.texture:getDimensions()),
                love.graphics.newQuad(160, 0, 16, 20, self.texture:getDimensions()),
                love.graphics.newQuad(144, 0, 16, 20, self.texture:getDimensions()),
            },
            interval = 0.15
        }),
        ['jumping'] = Animation({
            texture = self.texture,
            frames = {
                love.graphics.newQuad(32, 0, 16, 20, self.texture:getDimensions())
            }
        }),
        ['victory'] = Animation({
            texture = self.texture,
            frames = {
                love.graphics.newQuad(0, 0, 16, 20, self.texture:getDimensions()),
                love.graphics.newQuad(48, 0, 16, 20, self.texture:getDimensions()),
                love.graphics.newQuad(0, 0, 16, 20, self.texture:getDimensions()),
                love.graphics.newQuad(160, 0, 16, 20, self.texture:getDimensions()),
                love.graphics.newQuad(0, 0, 16, 20, self.texture:getDimensions()),
            },
            interval = .25
        })
    }

    -- initialize animation and current frame we should render
    self.animation = self.animations['idle']
    self.currentFrame = self.animation:getCurrentFrame()

    -- behavior map we can call based on player state
    self.behaviors = {
        ['idle'] = function(dt)

            -- add spacebar functionality to trigger jump state
            if love.keyboard.wasPressed('space') then
                self.dy = -JUMP_VELOCITY
                self.state = 'jumping'
                self.animation = self.animations['jumping']
                self.sounds['jump']:play()
            elseif love.keyboard.isDown('left') then
                self.direction = 'left'
                self.dx = -WALKING_SPEED
                self.state = 'walking'
                self.animations['walking']:restart()
                self.animation = self.animations['walking']
                self:checkLeftBoundary()
            elseif love.keyboard.isDown('right') then
                self.direction = 'right'
                self.dx = WALKING_SPEED
                self.state = 'walking'
                self.animations['walking']:restart()
                self.animation = self.animations['walking']
            else
                self.dx = 0
            end

            self:checkLeftBoundary()
            self:checkRightBoundary()

        end,
        ['walking'] = function(dt)

            -- keep track of input to switch movement while walking, or reset
            -- to idle if we're not moving
            if love.keyboard.wasPressed('space') then
                self.dy = -JUMP_VELOCITY
                self.state = 'jumping'
                self.animation = self.animations['jumping']
                self.sounds['jump']:play()
            elseif love.keyboard.isDown('left') then
                self.direction = 'left'
                self.dx = -WALKING_SPEED
            elseif love.keyboard.isDown('right') then
                self.direction = 'right'
                self.dx = WALKING_SPEED
            else
                self.dx = 0
                self.state = 'idle'
                self.animation = self.animations['idle']
            end

            self:checkLeftBoundary()
            self:checkRightBoundary()

            -- check for collisions moving left and right
            self:checkRightCollision()
            self:checkLeftCollision()

            -- check if there's a tile directly beneath us
            if not self.map:collides(self.map:tileAt(self.x, self.y + self.height)) and
                not self.map:collides(self.map:tileAt(self.x + self.width - 1, self.y + self.height)) then

                -- if so, reset velocity and position and change state
                self.state = 'jumping'
                self.animation = self.animations['jumping']

            end
        end,
        ['jumping'] = function(dt)
            if love.keyboard.isDown('left') then
                self.direction = 'left'
                self.dx = -WALKING_SPEED
            elseif love.keyboard.isDown('right') then
                self.direction = 'right'
                self.dx = WALKING_SPEED
            end

            -- apply map's gravity before y velocity
            self.dy = self.dy + self.map.gravity

            -- check if there's a tile directly beneath us
            if self.map:collides(self.map:tileAt(self.x, self.y + self.height)) or
                self.map:collides(self.map:tileAt(self.x + self.width - 1, self.y + self.height)) then

                -- if so, reset velocity and position and change state
                self.dy = 0
                self.state = 'idle'
                self.animation = self.animations['idle']
                self.y = (self.map:tileAt(self.x, self.y + self.height).y - 1) * self.map.tileHeight - self.height
            end

            self:checkLeftBoundary()
            self:checkRightBoundary()

            -- check for collisions moving left and right
            self:checkRightCollision()
            self:checkLeftCollision()
        end,
        ['victory'] = function(dt)
            self.dx = 0
            -- check if there's a tile directly beneath us
            if self.map:collides(self.map:tileAt(self.x, self.y + self.height)) or
                self.map:collides(self.map:tileAt(self.x + self.width - 1, self.y + self.height)) then

                -- if so, reset velocity and position and change state
                self.dy = 0
                self.y = (self.map:tileAt(self.x, self.y + self.height).y - 1) * self.map.tileHeight - self.height
            end
        end
    }
end

function Player:update(dt)
    self.behaviors[self.state](dt)
    self.animation:update(dt)
    self.currentFrame = self.animation:getCurrentFrame()
    self.x = self.x + self.dx * dt
    self.xmax = math.max(self.x, self.xmax) -- tester to update xmax if player moves further to right than ever before
    self.xmin = math.max(1, math.min(self.xmax - VIRTUAL_WIDTH / 2, map.mapWidthPixels - VIRTUAL_WIDTH))  -- farthest mario may go to the left, based on xmax and left border of map
    self:calculateJumps()

    self:gameover()
    self:reachflag()
    if self.map:victory() == true then
        self.victory = true
    end

    -- apply velocity
    self.y = self.y + self.dy * dt
end

function Player:gameover()
    if self.y > 300 then
        self.game_over = true
    end
end

function Player:reachflag(Flag)
    if self.x >= flag.x then
        self.victory = true
    end
end

-- jumping and block hitting logic
function Player:calculateJumps()

    -- if we have negative y velocity (jumping), check if we collide
    -- with any blocks above us
    if self.dy < 0 then
        if self.map:tileAt(self.x, self.y).id ~= TILE_EMPTY or
            self.map:tileAt(self.x + self.width - 1, self.y).id ~= TILE_EMPTY then
            -- reset y velocity
            self.dy = 0

            -- change block to different block
            local playCoin = false
            local playHit = false
            if self.map:tileAt(self.x, self.y).id == JUMP_BLOCK then
                self.map:setTile(math.floor(self.x / self.map.tileWidth) + 1,
                    math.floor(self.y / self.map.tileHeight) + 1, JUMP_BLOCK_HIT)
                playCoin = true
            else
                playHit = true
            end
            if self.map:tileAt(self.x + self.width - 1, self.y).id == JUMP_BLOCK then
                self.map:setTile(math.floor((self.x + self.width - 1) / self.map.tileWidth) + 1,
                    math.floor(self.y / self.map.tileHeight) + 1, JUMP_BLOCK_HIT)
                playCoin = true
            else
                playHit = true
            end

            if playCoin then
                self.sounds['coin']:play()
            elseif playHit then
                self.sounds['hit']:play()
            end
        end
    end
end

-- checks two tiles to our left to see if a collision occurred
function Player:checkLeftCollision()
    if self.dx < 0 then
        -- check if there's a tile directly beneath us
        if self.map:collides(self.map:tileAt(self.x - 1, self.y)) or
            self.map:collides(self.map:tileAt(self.x - 1, self.y + self.height - 1)) then

            -- if so, reset velocity and position and change state
            self.dx = 0
            self.x = self.map:tileAt(self.x - 1, self.y).x * self.map.tileWidth
        end
    end
end

-- checks two tiles to our right to see if a collision occurred
function Player:checkRightCollision()
    if self.dx > 0 then
        -- check if there's a tile directly beneath us
        if self.map:collides(map:tileAt(self.x + self.width, self.y)) or
            self.map:collides(map:tileAt(self.x + self.width, self.y + self.height - 1)) then

            -- if so, reset velocity and position and change state
            self.dx = 0
            self.x = (self.map:tileAt(self.x + self.width, self.y).x - 1) * map.tileWidth - self.width
        end
    end
end

function Player:checkLeftBoundary()
    if self.x <= self.xmin then -- went too far left
        self.x = self.xmin
        if self.direction == 'left'then
            self.dx = 0 -- set speed to zero but keep state, ie walking, jumping/falling
        end
    end
end

function Player:checkRightBoundary()
    if self.x >= map.mapWidthPixels - 16 then -- went too far right
        self.x = map.mapWidthPixels - 16
        if self.direction == 'right'then
            self.dx = 0 -- set speed to zero but keep state, ie walking, jumping/falling
        end
    end
end

function Player:render()
    local scaleX

    -- set negative x scale factor if facing left, which will flip the sprite
    -- when applied
    if self.direction == 'right' then
        scaleX = 1
    else
        scaleX = -1
    end

    -- draw sprite with scale factor and offsets
    love.graphics.draw(self.texture, self.currentFrame, math.floor(self.x + self.xOffset),
        math.floor(self.y + self.yOffset), 0, scaleX, 1, self.xOffset, self.yOffset)

    if self.game_over == true then
        self.state = 'idle'
        self.dy = 0
        self.dx = 0
        map.music:stop()
        if self.musicplayed == false then
            love.audio.newSource('sounds/Laser_Shoot2.wav', 'static'):play()
            self.musicplayed = true
        end
        love.graphics.print('Oh Snap!  Try again? (y/n)', self.xmin + 40, 40)
        if love.keyboard.isDown('y') then
            self.map:init()
            self.map:render()
        elseif love.keyboard.isDown('n')then
            love.event.quit()
        end
    end

    if self.victory == true then
        self.state = 'victory'
        self.animation = self.animations['victory']
        if self.musicplayed == false then
            love.audio.newSource('sounds/Powerup23.wav', 'static'):play()
            self.musicplayed = true
        end
        love.graphics.print('Congratulations! Play again? (y/n)', self.xmin + 35, 40)
        if love.keyboard.isDown('y') then
            self.map:init()
            self.map:render()
            map.music:stop()
        elseif love.keyboard.isDown('n')then
            love.event.quit()
        end
    end
end

--[[
    Super Mario Bros. Demo
    Author: Colton Ogden
    Original Credit: Nintendo

    Demonstrates rendering a screen of tiles.
]]

Class = require 'class'
push = require 'push'

require 'Animation'
require 'Map'
require 'Player'
require 'Flag'

-- close resolution to NES but 16:9
VIRTUAL_WIDTH = 432
VIRTUAL_HEIGHT = 243

-- actual window resolution
WINDOW_WIDTH = 1280
WINDOW_HEIGHT = 720

-- seed RNG
math.randomseed(os.time())

-- makes upscaling look pixel-y instead of blurry
love.graphics.setDefaultFilter('nearest', 'nearest')

-- an object to contain our map data
map = Map()
flag = Flag(map)
player = Player(map)

-- performs initialization of all objects and data needed by program
function love.load()

    -- sets up a different, better-looking retro font as our default
    love.graphics.setFont(love.graphics.newFont('fonts/font.ttf', 16))

    -- sets up virtual screen resolution for an authentic retro feel
    push:setupScreen(VIRTUAL_WIDTH, VIRTUAL_HEIGHT, WINDOW_WIDTH, WINDOW_HEIGHT, {
        fullscreen = false,
        resizable = true
    })

    love.window.setTitle('Super Mario 50')

    love.keyboard.keysPressed = {}
    love.keyboard.keysReleased = {}

end

-- called whenever window is resized
function love.resize(w, h)
    push:resize(w, h)
end

-- global key pressed function
function love.keyboard.wasPressed(key)
    if (love.keyboard.keysPressed[key]) then
        return true
    else
        return false
    end
end

-- global key released function
function love.keyboard.wasReleased(key)
    if (love.keyboard.keysReleased[key]) then
        return true
    else
        return false
    end
end

-- called whenever a key is pressed
function love.keypressed(key)
    if key == 'escape' then
        love.event.quit()
    end

    love.keyboard.keysPressed[key] = true
end

-- called whenever a key is released
function love.keyreleased(key)
    love.keyboard.keysReleased[key] = true
end

-- called every frame, with dt passed in as delta in time since last frame
function love.update(dt)
    map:update(dt)

    -- reset all keys pressed and released this frame
    love.keyboard.keysPressed = {}
    love.keyboard.keysReleased = {}
end

-- called each frame, used to render to the screen
function love.draw()
    -- begin virtual resolution drawing
    push:apply('start')

    -- clear screen using Mario background blue
    love.graphics.clear(108/255, 140/255, 255/255, 255/255)

    -- renders our map object onto the screen
    love.graphics.translate(math.floor(-map.camX + 0.5), math.floor(-map.camY + 0.5))
    map:render()

    -- end virtual resolution
    push:apply('end')
end

--[[
    Contains tile data and necessary code for rendering a tile map to the
    screen.
]]

require 'Util'

Map = Class{}

TILE_BRICK = 1
TILE_EMPTY = -1

-- cloud tiles
CLOUD_LEFT = 6
CLOUD_RIGHT = 7

-- bush tiles
BUSH_LEFT = 2
BUSH_RIGHT = 3

-- mushroom tiles
MUSHROOM_TOP = 10
MUSHROOM_BOTTOM = 11

-- jump block
JUMP_BLOCK = 5
JUMP_BLOCK_HIT = 9

-- flagpole
FLAGPOLE_TOP = 8
FLAGPOLE_MIDDLE = 12
FLAGPOLE_BOTTOM = 16
PYRAMID_BLOCK = 17

-- a speed to multiply delta time to scroll map; smooth value
local SCROLL_SPEED = 62

-- constructor for our map object
function Map:init()
    self.spritesheet = love.graphics.newImage('graphics/spritesheet.png')
    self.sprites = generateQuads(self.spritesheet, 16, 16)
    self.music = love.audio.newSource('sounds/music.wav', 'static')
    self.pyramid_block = love.graphics.newImage('graphics/pyramidblock.png')

    self.tileWidth = 16
    self.tileHeight = 16
    self.mapWidth = 300
    self.mapHeight = 28
    self.tiles = {}

    -- applies positive Y influence on anything affected
    self.gravity = 15

    -- associate player with map
    self.player = Player(self)
    self.flag = Flag(self)

    -- camera offsets
    self.camX = 0
    self.camY = -3

    -- cache width and height of map in pixels
    self.mapWidthPixels = self.mapWidth * self.tileWidth
    self.mapHeightPixels = self.mapHeight * self.tileHeight

    -- first, fill map with empty tiles
    for y = 1, self.mapHeight do
        for x = 1, self.mapWidth do

            -- support for multiple sheets per tile; storing tiles as tables
            self:setTile(x, y, TILE_EMPTY)
        end
    end

    -- begin generating the terrain using vertical scan lines
    local x = 1
    while x < self.mapWidth - 20 do

        -- 2% chance to generate a cloud
        -- make sure we're 2 tiles from edge at least
        if x < self.mapWidth - 2 then
            if math.random(20) == 1 then

                -- choose a random vertical spot above where blocks/pipes generate
                local cloudStart = math.random(self.mapHeight / 2 - 6)

                self:setTile(x, cloudStart, CLOUD_LEFT)
                self:setTile(x + 1, cloudStart, CLOUD_RIGHT)
            end
        end

        -- 5% chance to generate a mushroom
        if math.random(20) == 1 then
            -- left side of pipe
            self:setTile(x, self.mapHeight / 2 - 2, MUSHROOM_TOP)
            self:setTile(x, self.mapHeight / 2 - 1, MUSHROOM_BOTTOM)

            -- creates column of tiles going to bottom of map
            for y = self.mapHeight / 2, self.mapHeight do
                self:setTile(x, y, TILE_BRICK)
            end

            -- next vertical scan line
            x = x + 1

        -- 10% chance to generate a bush, being sure to generate away from edge
        elseif math.random(10) == 1 and x < self.mapWidth - 3 then
            local bushLevel = self.mapHeight / 2 - 1

            -- place bush component and then column of bricks
            self:setTile(x, bushLevel, BUSH_LEFT)
            for y = self.mapHeight / 2, self.mapHeight do
                self:setTile(x, y, TILE_BRICK)
            end
            x = x + 1

            self:setTile(x, bushLevel, BUSH_RIGHT)
            for y = self.mapHeight / 2, self.mapHeight do
                self:setTile(x, y, TILE_BRICK)
            end
            x = x + 1

        -- 10% chance to not generate anything, creating a gap
        elseif math.random(10) ~= 1 then

            -- creates column of tiles going to bottom of map
            for y = self.mapHeight / 2, self.mapHeight do
                self:setTile(x, y, TILE_BRICK)
            end

            -- chance to create a block for Mario to hit
            if math.random(15) == 1 then
                self:setTile(x, self.mapHeight / 2 - 4, JUMP_BLOCK)
            end

            -- next vertical scan line
            x = x + 1
        else
            -- increment X so we skip two scanlines, creating a 2-tile gap
            x = x + 2
        end
    end

    while x <= self.mapWidth do

        -- draw in pyramid
        if x == self.mapWidth - 13 then
            local row = 1 -- how wide pyramid to be
            while row < 7 do
                local column = 1 -- might need to not say local everytime
                while column <= row do
                    self:setTile(x, self.mapHeight / 2 - column, PYRAMID_BLOCK)
                    column = column + 1
                end
                 -- creates column of tiles going to bottom of map
                for y = self.mapHeight / 2, self.mapHeight do
                    self:setTile(x, y, TILE_BRICK)
                end
                row = row + 1
                x = x + 1
            end
        end

        -- draw in flagpole
        if x == self.mapWidth - 2 then
            self:setTile(x, self.mapHeight / 2 - 3, FLAGPOLE_TOP)
            self:setTile(x, self.mapHeight / 2 - 2, FLAGPOLE_MIDDLE)
            self:setTile(x, self.mapHeight / 2 - 1, FLAGPOLE_BOTTOM)
        end

        -- creates column of tiles going to bottom of map
        for y = self.mapHeight / 2, self.mapHeight do
            self:setTile(x, y, TILE_BRICK)
        end

        -- next vertical scan line
        x = x + 1
    end

    -- start the background music
    self.music:setLooping(true)
    self.music:play()
end

-- return whether a given tile is collidable
function Map:collides(tile)
    -- define our collidable tiles
    local collidables = {
        TILE_BRICK, JUMP_BLOCK, JUMP_BLOCK_HIT,
        MUSHROOM_TOP, MUSHROOM_BOTTOM, PYRAMID_BLOCK
    }

    -- iterate and return true if our tile type matches
    for _, v in ipairs(collidables) do
        if tile.id == v then
            return true
        end
    end

    return false
end

-- this function doesn't appear to be doing anything...
function Map:victory(player, flag)
    if self.player.x >= self.flag.x * map.tileWidth then
        return true
    else
        return false
    end
end

-- function to update camera offset with delta time
function Map:update(dt)
    self.player:update(dt)
    self.flag:update(dt)
    -- keep camera's X coordinate following the player, preventing camera from
    -- scrolling past 0 to the left and the map's width
    self.camX =  math.min(self.mapWidthPixels - VIRTUAL_WIDTH, math.max(self.camX, math.min(self.player.x - VIRTUAL_WIDTH / 2,
        math.min(self.mapWidthPixels - VIRTUAL_WIDTH, self.player.x))))
end

-- gets the tile type at a given pixel coordinate
function Map:tileAt(x, y)
    return {
        x = math.floor(x / self.tileWidth) + 1,
        y = math.floor(y / self.tileHeight) + 1,
        id = self:getTile(math.floor(x / self.tileWidth) + 1, math.floor(y / self.tileHeight) + 1)
    }
end

-- returns an integer value for the tile at a given x-y coordinate
function Map:getTile(x, y)
    return self.tiles[(y - 1) * self.mapWidth + x]
end

-- sets a tile at a given x-y coordinate to an integer value
function Map:setTile(x, y, id)
    self.tiles[(y - 1) * self.mapWidth + x] = id
end

-- renders our map to the screen, to be called by main's render
function Map:render()
    for y = 1, self.mapHeight do
        for x = 1, self.mapWidth do
            local tile = self:getTile(x, y)
            if tile ~= TILE_EMPTY then
                if tile > 16 then
                    love.graphics.draw(self.pyramid_block,
                        (x - 1) * self.tileWidth, (y - 1) * self.tileHeight)
                else
                    love.graphics.draw(self.spritesheet, self.sprites[tile],
                        (x - 1) * self.tileWidth, (y - 1) * self.tileHeight)
                end
            end
        end
    end
    self.player:render()
    self.flag:render()
end

A: You're using 'self.player' which is a brand new player at the init() (which is a different player than the one you want)
You need to use 'player' that you passed as an argument to check if player.victory is true.


text:
Q: Jisti Videobridge using Node js Currenrtly we are using Kurento for 1-many & many-many video calls using Node Js ( Kurento Tutorial ).
We are now planning to move to Jitsi-videobridge.
Is there any example / tutorial of how to use Jitsi-videobridge with NodeJs?
All I could find is Jitsi-meet with nginx/apache without any explanation.
Any documentation / tutorial for Jitsi-Videobridge with Node will be great
Thanks


text:
Q: Combinatorics with just 2 letters Using the letters A & B only to make two strings of 7 letters each, how many combinations are possible based on the following criteria?
Criteria 1: There must be at least 2 B's in each string.
Criteria 2: A can be on top or below A and B but B cannot be above or below another B.
Examples:

AAABBAA
BBBAAAB

ABABAAB
AABABAA

BAAABBB
ABBBAAA

BAAAAAB
ABAAABA

I think I understand how to calculate the number of combinations of the top string but I can't figure out how to link that to the bottom string.
Any help is greatly appreciated!

My solution for the top string combinations:
$\sum_{i=1}^{4} \binom{7}{2}\binom{5}{5-i}$
Where $\binom{7}{2}$ is the required 2 B's, and the $\binom{5}{5-i}$ is the other choices for the remaining letters.

A: I think the simplest way to approach this is to consider the cases "there are exactly $k$ Bs in the top string" for each $k$ separately, and add everything up in the end.
For example, if there are exactly $2$ Bs in the top string, then there are $\binom{7}{2}$ ways to choose the top string and $2^5 - 1 - 5$ ways to choose the bottom string (the two positions below the top string's Bs must be As, which leaves $5$ positions, at least two of which must be Bs).
You can continue for "exactly $3$ Bs in the top string," and so on.

 This approach yields $$\sum_{k=2}^5 \binom{7}{k} (2^{7-k} - 1 - (7-k)).$$

I may be missing a more elegant approach though.

A: Since no $B$ can be in the same column as another $B$ and there must be at least two $B$s in each row, there are at least four columns that contain a $B$.  If there are exactly $k$ columns in which a $B$ occurs, there are $\binom{7}{k}$ ways of choosing which columns contain a $B$ and $2$ ways of choosing in which row that $B$ appears.  From these, we must subtract those arrangements in which there are fewer than two $B$s in one the rows. Hence, the number of admissible arrangements is
$$\sum_{k = 4}^{7} \binom{7}{k}\left[2^k - \binom{2}{1}\binom{k}{k} - \binom{2}{1}\binom{k}{k - 1}\right]$$
where the term $\binom{2}{1}\binom{k}{k}$ represents the number of ways we could place all $k$ $B$s in the same row and the term $\binom{2}{1}\binom{k}{k - 1}$ represents the number of ways we could place all but one of the $B$s in the same row.

A: Suppose we initially drop the second condition and ask how many ways there are to arrange 7 A/B's in two rows with at least 2 B's in each row.  In one row there are $2^7$ ways to arrange 7 A/B's.  In $7$ of these there is only one B and in $1$ there are no B's.  So one row can be arranged in $2^7-7-1$ ways, and two rows can be arranged in $N= (2^7-7-1)^2$ ways.
To find the number of these arrangements which satisfy the second condition (no two B's in the same column), we apply the Principle of Inclusion / Exclusion (PIE).  Let's say an arrangement has "Property $i$" if column $i$ has two B's, for $i=1,2,3,\dots,7$.  Let $S_j$ be the number of arrangements with $j$ of the properties, for $j=1,2,3,\dots,7$.
The case $j=1$ is a bit special.  The single column can be chosen in $\binom{7}{1}$ ways.  In the first row the remaining columns can be filled in $2^6$ ways, but one of these ways consists of only A's, violating the rule that the row must contain at least two B's. So the letters in the first row can be arranged in $2^6-1$ ways, and similarly for the second row.  So
$$S_1 = \binom{7}{1}(2^6-1)^2$$
The cases $S_2, S_3, \dots , S_7$ are a bit simpler than $S_1$, because when two or more of the columns contain B's, we have automatically satisfied the requirement that each row contain at least two B's.  So
$$S_j = \binom{7}{j} (2^{7-j})^2$$
for $j = 2,3,4, \dots,7$.
Finally, by PIE, the number of arrangements with none of the properties, i.e. the arrangements in which no column contains two B's, is
$$\begin{align}
N_0 &= N + \sum_{j=1}^7 (-1)^j S_j \\
&= (2^7-7-1)^2 - \binom{7}{1}(2^6-1)^2 + \sum_{j=2}^7 (-1)^j \binom{7}{j} (2^{7-j})^2 \\
&= (2^7-7-1)^2 - \binom{7}{1}(2^6-1)^2 + \sum_{j=0}^7 (-1)^j \binom{7}{j} (2^{7-j})^2 - \sum_{j=0}^1 (-1)^j \binom{7}{j} (2^{7-j})^2 \\
&= (2^7-7-1)^2 - \binom{7}{1}(2^6-1)^2 - (1-4)^7 - 4^7 + 7 \cdot 4^6\\
\end{align}$$
where we have applied the Binomial Theorem in the last line.

A: Another approach is to solve a more general problem, in which the lengths of the two strings are $r$.  The original problem is then the case $r=7$.
Any single column consists of two letters, one of
$$\alpha = \begin{vmatrix} A\\B \end{vmatrix} \qquad \beta = \begin{vmatrix}B\\A \end{vmatrix} \qquad \gamma = \begin{vmatrix} A\\A \end{vmatrix}$$
An acceptable arrangement of length $r$ is a string of $r$ "characters" taken from $\alpha, \beta$ and $\gamma$ with at least two $\alpha$'s and at least two $\beta$'s.  The exponential generating function for the number of acceptable strings is
$$\begin{align}
f(x) &= \left( \frac{1}{2!} x^2 + \frac{1}{3!} x^3 + \frac{1}{4!} x^4+ \dots \right)^2 \left( 1 + x + \frac{1}{2!} x^2 + \dots \right) \\
&= (e^x-1-x)^2 \; e^x \\
&= e^{3x}+e^x+x^2 e^x-2e^{2x}-2xe^{2x}+2xe^x
\end{align}$$
From this last expression we can find the coefficient of $(1/7!)x^7$, which is the solution to the original problem:
$$7! \;[x^7] f(x) = 3^7 + 1 + 6 \cdot 7 - 2^8 - 7 \cdot 2^7 + 2 \cdot 7 =1092$$


text:
Q: how to do Kafka syncing between two consumer groups in my requirement I have two consumer group, one Group(Main) just take the data and send to other server, if sending to other server is failed then I need to rejoin(start) other consumer group(Failed processing)
.
In this case Main Group  continues to read and retry , and it will continue the same and some point when message sending become success it needs to notify other consumer group(Failed processing). Now Failed processing should start sending from where first fail to last fail.
public void StartMainstreamHandler() {
       StreamsBuilder builder = new StreamsBuilder();

        KStream<String, String> userStream = builder.stream("usertopic",Consumed.with(Serdes.String(), Serdes.String()));
        Properties props = new Properties();
        props.put(StreamsConfig.APPLICATION_ID_CONFIG, "main-streams-userstream");
        props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "ALL my bootstrap servers);
        props.put(StreamsConfig.NUM_STREAM_THREADS_CONFIG, 4);
        props.put("enable.auto.commit", "true");
        props.put("auto.commit.interval.ms", "500");
        props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest");
        //consumer_timeout_ms
        props.put(ConsumerConfig.MAX_POLL_INTERVAL_MS_CONFIG, 2000);

        props.put("state.dir","/tmp/kafka/stat));

   userStream.peek((key,value)->System.out.println("key :"+key+" value :"+value));
   /* Send Data to other Server if Failed call other consumer */

KafkaStreams kafkaStreams = new KafkaStreams(builder.build(), props);

kafkaStreams.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread t, Throwable e) {

                logger.error("Thread Name :" + t.getName() + " Error while processing:", e);
            }
        });

        kafkaStreams.cleanUp();
        kafkaStreams.start();
    }

Other Consumer
public void StartFailstreamHandler() {
       StreamsBuilder builder = new StreamsBuilder();

        KStream<String, String> userStream = builder.stream("usertopic",Consumed.with(Serdes.String(), Serdes.String()));
        Properties props = new Properties();
        props.put(StreamsConfig.APPLICATION_ID_CONFIG, "failed-streams-userstream");
        props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "ALL my bootstrap servers);
        props.put(StreamsConfig.NUM_STREAM_THREADS_CONFIG, 4);
        props.put("enable.auto.commit", "true");
        props.put("auto.commit.interval.ms", "500");
        props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest");
        //consumer_timeout_ms
        props.put(ConsumerConfig.MAX_POLL_INTERVAL_MS_CONFIG, 2000);

        props.put("state.dir","/tmp/kafka/stat));

     Wait('till get notfication from other consumer" ){
     userStream.peek((key,value)->System.out.println("key :"+key+" value :"+value));
     /* start sending */
     /* how to break when it is reached last offest */
   }

KafkaStreams kafkaStreams = new KafkaStreams(builder.build(), props);

kafkaStreams.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread t, Throwable e) {

                logger.error("Thread Name :" + t.getName() + " Error while processing:", e);
            }
        });

        kafkaStreams.cleanUp();
        kafkaStreams.start();
    }

Now How to know and sync the offset details at second consumer to exactly stop at last failed ( last failed happened at main consumer)

A: It's not reasonably possible to sync consumer groups between clusters with messages alone because there's not way for a consumer to seek to a particular "replicated start point".
You'd have to store extra metadata to the side such as timestamps that replication started, maybe embedding that information in the record headers (assuming your version of Kafka supports it}. Otherwise, you're more or less blindly copying data with minimal guarantees of delivery (and therefore might be better off using MirrorMaker anyway).
MirrorMaker 2 or Confluent Replicator are currently the only two options available for "syncing" of consumer groups, to make an active-active dual cluster setup


text:
Q: Google chart, annotations and label issues I'm generating a graph using google chart, however I have several problems.
First: Currently an annotation is displayed in the second series in which it shows the place in the ranking. However, if there is more space in the second series (gray background) the text is moved lower or disappears completely. I would like the annotation ("place in the ranking") to be always on one line and in case of lack of space, it overlaps both series (blue and gray).
Second: in the case of labels (january, february, march etc.) when the label is too long or consists of several words is dotted, and I would like it to move to the next line.
How to solve this problem ? Thank you in advance for your answer.
var data = google.visualization.arrayToDataTable([
        ['Genre', 'Zrealizowane', {role: 'annotation'}, 'Niezrealizowane', {role: 'annotation'}],
        ['january', 10, '', 90, '7th place in the ranking'],
        ['february', 16, '', 84, '7th place in the ranking'],
        ['march', 16, '', 84, '12th place in the ranking'],
        ['april', 10, '', 90, '7th place in the ranking'],
        ['may', 16, '', 84, '12th place in the ranking'],
        ['june', 100, '', 9, '7th place in the ranking'],
        ['juli', 16, '', 84, '12th place in the ranking'],
        ['august', 81, '', 90, '2nd place in the ranking']
    ]);

    var options = {
        chartArea: {width: size, height: '90%', right: 20},
        legend: {position: 'top', maxLines: 2},
        bar: {groupWidth: '46px'},
        isStacked: 'percent',
        hAxis: {
            minValue: 0,
            ticks: [0, .25, .5, .75, 1]
        },
        series: {
            0: {color: '#0077c4'},
            1: {color: '#f2f2f2'}
        }
    };

    var chart = new google.visualization.BarChart(document.getElementById('chart_progress'));
    chart.draw(data, options);


text:
Q: Open a pdf in React by getting path from Node JS How can I open pdfs in Reactjs which are saved in local drive and it's path is coming from backend(ExpressJS)?
Actually, I am showing some data in Table and each row of Table is a link in itself. I want to open a related pdf by clicking on a row. Since, DB is Mongo, so I can provide a seperate link to each document for pdf. As of now, I am getting data from back-end using axios. How can I write the code such that I can open pdf by clicking the rows of a Table using links from back-end?
Please help me how can I do so.

A: Try this code :
Just pass this code in view handler
viewHandler = async () => {
    axios(your Api url, {
      method: "GET",
      responseType: "blob"
      //Force to receive data in a Blob Format
    })
      .then(response => {
        //Create a Blob from the PDF Stream
        const file = new Blob([response.data], {
          type: "application/pdf"
        });
        //Build a URL from the file
        const fileURL = URL.createObjectURL(file);
        //Open the URL on new Window
        window.open(fileURL);
      })
      .catch(error => {
        console.log(error);
      });

A: you need to get the PDF data from API endpoint
axios (${apiURL}/PDF, {
method:'GET',

A: Code at Back-end (NodeJs):
//id is unique for each Link (row) in a table, based on 'id', data is fetched from DB and pdf is returned from Node for that particular id
app.get('/papers/:id', (req, res) => {
  connectionForPdf(req.params.id).then((data)=>{
  var tempFile=data.paperLocation; //data.paperLocation physical path of the paper
                                   //fetched from DB
        fs.readFile(tempFile, function (err,data){
            res.contentType("application/pdf");
            res.send(data);
        });
      })
      .catch(error=>{
        console.log('Shit');
      })
})

connectionForPdf=(id)=>{
  return mongoose.connect(url,{ useNewUrlParser: true, useUnifiedTopology: true })
  .then((database)=> {
    return exampleModel.findOne({_id:id}).then(data=>{
      if(data) {
        return data.toObject();
      }
      database.close();
    }).catch(error=>{
      console.log('Con')
    })

  .catch((error)=>{
    console.log('not connected')
    let err=new Error("Couldn't connect");
    err.status=500;
    throw err;
  })
}

Code at front-end (ReactJs):
// id is passed on onClick() of each Link (Row)
handleClick=(id)=>{
       const viewHandler = async () => {
        axios('http://localhost:3001/papers/'+id, {
          method: "GET",
          responseType: "blob"
          //Force to receive data in a Blob Format
        })
          .then(response => {
            //Build a URL from the file
            var file = new Blob([response.data], {type: 'application/pdf'});
            const fileURL = URL.createObjectURL(file);
            //Open the URL on new Window
            window.open(fileURL);
          })
          .catch(error => {
            console.log(error);
          });

        }
         viewHandler();
      }


text:
Q: How do I take in image view in iOS and make it go behind the other layers to make it the background? There isn't really code for this it's more on the story board.
I have tried to go to the attributes and size modifier but I can't find anything that makes the UIImageView the background.

A: Just Drag the uiimageview in the left side, and drop it to the top of the other component.

A: Just set an image as the backgroundColor, something like:
self.view.backgroundColor = UIColor(patternImage: image)

See: https://developer.apple.com/reference/uikit/uicolor for more details.


text: Q: Can multiple process pull off the same record from an Oracle FIFO queue? My understanding of Oracle AQ (Advanced Queuing) is that no two (or more) processes can pull off (drain/consume) the same record of an Oracle FIFO queue.  Is this correct or is some code needed to prevent this from occurring?


text:
Q: How to specify path to resources inside a war file? I have build my project with maven and spring framework using text editors.
I am able to run the project the root folder using the command on terminal
mvn spring-boot:run

I have referenced to my source files inside java file using the java statement
Document doc = builder.parse("src/main/resources/data/resorts.xml");

Everything works fine.
When I export the whole project as a war file using the command
mvn package

on terminal
I get a war file inside the target folder of the root directory
I run the war file using the command
java -jar filename.war

There is no compilation error but during runtime it shows the error java.io.FileNotFoundException
I think I have not specified the path of the reference file correctly
Can you mention how the relative path must be mentioned in the the path string to make it able to be run from the war file.
My directory structure is
.
    |-- src
    |   `-- main
    |       |-- java
    |       |   `-- hello
    |       |       `-- org
    |       |           `-- json
    |       `-- resources
    |           |-- data
    |           `-- templates
    `-- target
        |-- classes
        |   |-- data
        |   |-- hello
        |   |-- org
        |   |   `-- json
        |   `-- templates
        |-- generated-sources
        |   `-- annotations
        |-- gs-handling-form-submission-0.1.0
        |   |-- META-INF
        |   `-- WEB-INF
        |       |-- classes
        |       |   |-- data
        |       |   |-- hello
        |       |   |-- org
        |       |   |   `-- json
        |       |   `-- templates
        |       `-- lib
        |-- maven-archiver
        `-- maven-status
            `-- maven-compiler-plugin
                `-- compile
                    `-- default-compile

    33 directories

The java files are inside the hello directory.

A: You are probably experiencing problems with the path received from the URI class to a file located inside a jar.
Application.class.getClassLoader().getResource("path-to/filename.txt").getPath()

Outputs: /path-to-your/application.jar!/path-to/filename.txt
If you try to create a File object or a Stream to that path it will fail with FileNotFoundException
If possible you should change the class Document to receive the content of the file or a InputStream.
Then you can use the classloader to fetch the stream for the file instead of the path.
In your case:
InputStream is = Application.class.getClassLoader()
            .getResourceAsStream("data/resorts.xml");

And then create the Document with the is object.


text:
Q: Docker on Windows and django I have docker on Windows and ubuntu container and when I run django server there i can't see it in my browser under 127.0.0.1. I created docker container with ports exposed. When I created nginx image i could see nginx page in my browser. Why cant I see django page ? When I look at my containers I see ports 0.0.0.0:80->80/tcp next to my container

A: I think your problem is not docker related since your nginx image is working. Could you enter in your container using bash and execute wget or curl on localhost ?
If you see your page (or the html) it is probably a docker problem. If not check your django configuration.
Please post your Dockerfile and the exact docker run command you are using.
Regards


text:
Q: Flutter Container not shown because of borderRadius? I added borders on 3 of 4 sides of my Container. It is not shown if I'm adding a borderRadius in the BoxDecoration. Without the borderRadius it is visible with the borders and the text in it. How can I add a borderRadius to the Container without it being hidden?
[...]
    Container(
              padding: EdgeInsets.all(10),
              height: 85,
              width: 330,
              decoration: BoxDecoration(
                border: Border(
                  top: BorderSide(color: Colors.black, width: 2),
                  right: BorderSide(color: Colors.black, width: 2),
                  bottom: BorderSide(color: Colors.black, width: 2),
                ),
                // borderRadius: BorderRadius.all(Radius.circular(5)),
              ),
              child: Text(
                'Example text! Example text! Example text! Example text!',
                style: TextStyle(fontSize: 22, fontFamily: 'Dosis'),
              ),
            ),
[...]

A: You can get reference from below code..
body: Container(
          margin: EdgeInsets.all(100.0),
          decoration: BoxDecoration(
            color: Colors.white,
            shape: BoxShape.rectangle,
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(25.0),
              bottomRight: Radius.circular(25.0)
            ) ,
            border: Border(
              top: BorderSide(color: Colors.black, width: 2),
              right: BorderSide(color: Colors.black, width: 2),
              bottom: BorderSide(color: Colors.black, width: 2),
            ),
          ),
        )


text:
Q: Apache mod_rewrite help on shared server I'm using a shared hosting server with multiple domains, and my main .htaccess (inside the public_html/ directory) redirects all traffic to the server to my main domain (fine). The problem becomes now that I have Wordpress running on the main domain that the subfolder is being included in the %{REQUEST_URI} variable. So my .htaccess code:
RewriteRule .* https://%{HTTP_HOST}/index.php?%{REQUEST_URI} [L,R=301]

moves:
http://www.tonydiloreto.com/about/
to:
https://www.tonydiloreto.com/?/tonydiloreto/about/
(I put the ? in there so I could see what is being stored in the variable). My question is, how do I use regex to remove the additional /tonydiloreto from the %{REQUEST_URI} variable when Rewriting? If this were PHP I would do:
$new_url = str_replace("/tonydiloreto", "", %{REQUEST_URI});

If that makes sense. If you want to see what I'm talking about just go to my site now (tonydiloreto.com) and put anything after a trailing slash.
Thank you!

A: Not really sure what the issue here is... You simply specify a request rule which captures only part of the uri. There are millions of examples for this...
RewriteEngine on
RewriteRule ^/tonydiloreto/(.*)$ https://%{HTTP_HOST}/index.php?$1 [L,R=301]

This is documented, obviously: http://httpd.apache.org/docs/current/mod/mod_rewrite.html
Note: the above is the version for the host configuration. If you really have to use .htaccess style files, then you have to remove the leading slash (/) from the pattern, since such files work on relative URIs. .htaccess style files are notoriously error prone, hard to debug and really slow the server down.


text:
Q: Why is the relative tangent bundle called so and why is a bundle of tangent vectors to the fibre? Let $X$ and $Y$ be smooth manifolds and $\varphi:X\to Y$ be a submersion. Let $T_X$ and $T_Y$ be the tangent bundles over $X$ and $Y$ respectively. The relative tangent bundle $T_{X/Y}$ is defined as the kernel of the map $T_\varphi:T_X\to\varphi^*T_Y$.
Question 1: Why is this bundle called "relative" tangent bundle?
Question 2: Why can it be thought of as the bundle of tangent vectors that are tangent to fibres of $\varphi$?
What we have is a short exact sequence of vector bundles over $X$ - $$0\to T_{X/Y}\to T_X\xrightarrow{T_\varphi} \varphi^*T_Y\to 0$$ So the over a point $x\in X$ we have the SES of vector spaces $$0\to T_{X/Y,x}\to T_{X,x}\xrightarrow{T_{\varphi,x}} T_{Y,\varphi(x)}\to 0$$
Where $T_{X/Y,x}=\{u\in T_{X,x}\ |\ T_{\varphi,x}(u)=0\}$. But it is not clear to me why such $u$ are precisely the tangents to the fibres?
Thank you.

A: a) If $\varphi:X\to Y$ is a submersion and $y=\varphi(x)$, then the fibre $X_y=\varphi^{-1}(y)\subset X$ is a submanifold whose tangent space at $x$ is the linear subpace $T_x(X_y)\subset T_x(X)$ defined by $$T_x(X_y)=\operatorname {Ker}[T_x(X)\xrightarrow {D{\varphi }_x }T_{\varphi(x)}(Y)] $$ Hence we have for each $x\in X$ an exact sequence of vector spaces $$   0\to T_x(X_y)\to T_x(X) \xrightarrow{D\varphi_x} T_{\varphi(x)}(Y) \to  0 \quad (\bigstar)_x                 $$ This has nothing yet to do with vector bundles and follows from the basic properties of submersions: see Lee, Proposition 5.38, page 117 whose notations I have adopted for ease of reference, although your notation too is  beautifully functorial!
b) The collection of all those subspaces $T_x(X_y)\subset T_x(X)$ for varying $x\in X$ forms a sub-vector bundle $T(X/Y)=T_{\operatorname {vert}}(X)\subset T(X)$ called the vertical tangent bundle of $X$ with respect to $\varphi$ (a more adequate terminology than relative tangent bundle).
The exact sequence
$$0\to T_{\operatorname {vert}}(X)\to T(X) \xrightarrow{T(\varphi)} \varphi^* T(Y)\to 0 \quad ( \bigstar)$$ of vector bundles on $X$ is thus  obtained by the globalization of  the exact sequences of vector spaces $(\bigstar)_x$.
Note carefully that there does not exist a   canonical horizontal bundle $T_{\operatorname {hor}}(X)\subset T(X) $ such that $$T(X)=T_{\operatorname {vert}}(X)\oplus T_{\operatorname {hor}}(X)$$ In other words our exact sequence of vector bundles  $ (\bigstar )$ has no canonical splitting.


text:
Q: How can I as a user flag/vote for questions to be migrated? I would like to help Stack Exchange out by flagging/voting for questions to be migrated to an appropriate site. How does this work and how can I do this?

A: For new users, you can downvote and leave a comment about how the question should be closed.
Users with 3K+ rep can vote to close a question with the option of moving it.  For example:
Vote to close

Choose "This question belongs on another site in the stack exchange network"

Choose where it should go


text:
Q: Outline Text Rendering Time in WPF I have a serious problem that Outline Text takes lots of CPU Usage.
I take OutlineText Control source in
http://blogs.msdn.com/b/wpfsdk/archive/2006/12/24/using-text-as-a-decorative-graphic.aspx
and in onTimer() I update OutlineText's Foreground per 100ms but it takes much more CPU than TextBlock.
Cause I think it refers to image processing inside it.
How can I improve the source code or is there any other way to implement Outline Text in WPF?

A: I find the best thing to do in situations like this, where your code is slow but you dont know why is to use a profiler, http://www.quest.com/jprobe/software_download.aspx you can get a free trail of this java profiler and it will tell you line by line how much time is spent and how many times it is executed, you should be able to pinpoint exactly what is slowing you code down with this.
Hope this helps, Eamonn

A: Rendering Time And CPU usage problems are successfully resolved by freezing outline text's individual object.
you can get correct answer in http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/512a88a3-1285-4c79-9f41-95e6dc5d097d?prof=required
I wish this will help you to implement OutlineText in WPF.
Thank you.


text:
Q: truncate partitions with foreign keys without cascade in postgresql I have a schema like this:
create table thing
(
    section  uuid not null,
    thing_id uuid not null,
    alias_of uuid default null,

    constraint alias_ref foreign key (section, alias_of)
        references thing (section, thing_id),

    primary key (section, thing_id)
) partition by list (section);

create table dependent_thing
(
    section            uuid not null,
    dependent_thing_id uuid not null,
    depends_on_thing   uuid not null,
    alias_of           uuid default null,

    constraint thing_ref foreign key (section, depends_on_thing)
        references thing (section, thing_id),
    constraint alias_ref foreign key (section, alias_of)
        references dependent_thing (section, dependent_thing_id),

    primary key (section, dependent_thing_id)
) partition by list (section);

So there are dependent_things which may reference things, and both things and dependent_things may reference themselves.
These tables are partitioned and as can be seen from the foreign key definitions they only ever reference things within their same partition.
However if I `truncate _thing_partitition_63df23f7b60d3345824bfe726cade143 cascade' it will take down all data from all sections from all partitions.
I know that if I were to remove foreign keys, detach the partitions, truncate their contents – I'd be fine. However I am wondering whether there is a smarter way to do this? Theoretically postgres should be able to prove that I am just pruning a partition. If I were to truncate _thing_partition_123 _dependent_thing_partition_123 it should remove all data for section 123, not for any other section; as the foreign keys are limited to the sections by which we partition.

A: If you have a foreign key pointing to a partitioned table, you cannot truncate, drop or detach a partition. But you can do all of these things if you have foreign key constraints between the individual partitions...


text:
Q: Validate and filter email address with RegEx? What's the best way to disallow free email service emails (e.g. Gmail, Yahoo, Hotmail) using RegEx and Javascript email field validation?
^.*@(?!(aol\.com$|yahoo\.com$|hotmail\.com$))$

I've seen the generic "Validate email address in Javascript" solution here Validate email address in JavaScript? but cant figure out how to make it disallow Gmail, Yahoo and Hotmail.
[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)\b

A: One of thousands of acceptable ways to get there - not that yours isn't acceptable...
function isGoodEmail(email) {
    if(isValidEmail(email)) {
        if(/(aol|gmail|yahoo|hotmail)\.com$/.test(email)) {
           alert(' valid email, but not for this site.  No free service emails!');
           return false;
        }
        return true;
    }
    return false;
}

function isValidEmail(email) {
  // implement using any of the email regexp's available
}


text:
Q: ASP.NET Javascript Converter does not seem to be invoked I have an ASP.NET 3.5 SP1 web application that uses a custom JavaScriptConverter.  The code used to work at some time in the past, but has stopped working.  I do not know what changes have happened in the middle server side.  The problem we are seeing now is that the converter is not being invoked, so we are getting errors that System.Data.DataRow cannot be serialized.
The following is the relevant portion of web.config:
<system.web.extensions>
    <scripting>
        <webServices>
            <jsonSerialization>
                <converters>
                    <add name="DataSetConverter" type="Microsoft.Web.Preview.Script.Serialization.Converters.DataSetConverter, Microsoft.Web.Preview" />
                    <add name="DataRowConverter" type="WebUI.DataRowConverter, WebUI.DataRowConverter, Version=1.1.0.323, Culture=neutral" />
                    <add name="DataTableConverter" type="Microsoft.Web.Preview.Script.Serialization.Converters.DataTableConverter, Microsoft.Web.Preview" />
                </converters>
            </jsonSerialization>
        </webServices>
    </scripting>
</system.web.extensions>

A trimmed version of the class is as follows (trimmed only to avoid wasting space on unnecesary implementation):
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Web.Script.Serialization;

namespace WebUI {
    public class DataRowConverter : JavaScriptConverter {
        private ReadOnlyCollection<Type> _supportedTypes = new ReadOnlyCollection<Type>(new Type[] { typeof(DataRow) });

        public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) {
            // stuff
            return dr;
        }

        public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer) {
            // stuff
            return dictionary;
        }

        public override IEnumerable<Type> SupportedTypes {
            get {
                return this._supportedTypes;
            }
        }
    }
}

What seems to happen is that the class is indeed being loaded (if we take it out of web.config and the project references, no breakpoints are available; put it back into web.config and copy the DLL/PDB by hand or add it to the project, breakpoints are available), but it's not being used propertly.  No breakpoint anywhere in the class is hit, and no exceptions (including one thrown in a constructor added to see what happens) are thrown.  It seems like the class is being loaded but never called.
This is on IIS 7.5 and IIS 7.0 in Integrated mode, if it matters.
Anyone have any ideas?

A: OK, just in case anyone else hits this, when calling web services through the automatically generated test pages, the custom serializers are not invoked - they are bypassed.  This is apparently by design.


text:
Q: how to install gdal_proximity I installed gdal with the apt-get install gdal-bin command.
Then this is what I get :
# ls /usr/bin | grep gdal
gdal-config
gdal_contour
gdal_grid
gdal_rasterize
gdal_translate
gdaladdo
gdalbuildvrt
gdaldem
gdalenhance
gdalinfo
gdallocationinfo
gdalmanage
gdalserver
gdalsrsinfo
gdaltindex
gdaltransform
gdalwarp

There is no gdal_proximity but it is stated in the doc that it will be installed with gdal. What am I doing wrong?

A: I had to install python-gdal, it works now

A: It looks like gdal_proximity.py is not included in the Ubuntu gdal-bin repository. gdal-bin
You should be able to directly copy/download the source file and use it, since it is just a python script. gdal_proximity.py
Copy the file into your bin or /usr/bin or somewhere in your PATH. Give it execution permission chmod +x gdal_proximity.py and you should be good to go.


text:
Q: regular expression that matches anything What will be regular expression that accept every thing?
For example
I have a url string /vpv/?pid=FLR1&deviceType=flash#exterior/backplate . Now I want to write regex like
 /vpv/?(any thing : alphabet,number,special chars, )#[exterior/](anything here)

value within() can be anything.

A: You can use .* in the brackets to accomplish this ...

A: What about the dot character?

http://www.regular-expressions.info/reference.html

A: You can play with regular expressions using this http://gskinner.com/RegExr/ write your examples and it will highlight in realtime what is found. so you can play around :D


text:
Q: Passing variable to directives, with array push My controller contains an array. Each item in the array is a directive with template. How do I get value to directive when I push a new one? I want to send ID to directive when I push new item.
Controller
(function () {
  'use strict';

angular
  .module('app')
  .controller('dashboardController', dashboardController);

dashboardController.$inject = ['$scope', '$timeout', '$state', 'apiService'];

function dashboardController($scope, $timeout, $state, apiService) {

$scope.newCMP = newCMP;
$scope.openCMPArray = [];

function newCMP() {
  $scope.openCMPArray.push({id:"3"});
}

}

})();

Directive
(function () {
  'use strict';

  angular
      .module('app')
      .directive('gpCmpForm', cmpForm);

  function cmpForm() {
    return {
      scope: {
        id: '=id' //I've tried doing a lot of different mapping here
      },
       restrict: 'A',
      templateUrl: '/app/views/cmpForm.html',
      controller: function ($scope) {
        $scope.test = "342";
      }
    }
 };
})();

How does the directive get the ID when it is created?

A: If you are looping through a collection for which you generate directives, you just have to push a new element into the collection, AngularJS will pick up the changes and handle the view.
So for instance - if this is your HTML:

    click to add person

You see that a persondirective is created for each person in the collection. If you push a person into the people collection, a new directive will show for that person:
$scope.addPerson = function() {
    $scope.people.push({ name: 'new guy' });
};

I've created a fiddle for you to demonstrate how this works: http://jsfiddle.net/k7qsxo5e/
Also - you probably want to use the '=' binding. This is a two way binding. That means that if the person being displayed in the directive is changed from the controller, the list will update. Also, if the directive changes the person, the collection in the controller will update.


text:
Q: Reshaping data frame with many NAs I have a data frame in R with four variables:

id
var1
var2
var3

1
NA
0.4
NA

1
0.8
NA
NA

2
0.7
NA
NA

2
NA
0.5
NA

2
NA
NA
0.1

3
NA
0.5
NA

3
NA
NA
0.2

There are repeated entries per id and each observation only contains one data value besides the id. I would like to obtain one observation per id with all of the data values "collected".
The output should look like this:

id
var1
var2
var3

1
0.8
0.4
NA

2
0.7
0.5
0.1

3
NA
0.5
0.2

I have played around with pivot_wider, data.table, gather, but am not getting anywhere. It seems to me that this should be very simple. Like some sort of collapse. Grateful for any pointers.

A: Or using summarise per group:
library(dplyr)

df |>
  group_by(id) |>
  summarise(across(everything(), ~ first(na.omit(.))))

Output:
# A tibble: 3 × 4
     id  var1  var2  var3
  <int> <dbl> <dbl> <dbl>
1     1   0.8   0.4  NA
2     2   0.7   0.5   0.1
3     3  NA     0.5   0.2

Thanks to @Darren Tsai for the data.

A: You can use tidyr::fill by groups and then subset unique rows.
library(dplyr)
library(tidyr)

df %>%
  group_by(id) %>%
  fill(var1:var3, .direction = "downup") %>%
  distinct() %>%
  ungroup()

# # A tibble: 3 × 4
#      id  var1  var2  var3
#   <int> <dbl> <dbl> <dbl>
# 1     1   0.8   0.4  NA
# 2     2   0.7   0.5   0.1
# 3     3  NA     0.5   0.2

Data
df <- read.table(text = "
id  var1    var2    var3
1   NA  0.4 NA
1   0.8 NA  NA
2   0.7 NA  NA
2   NA  0.5 NA
2   NA  NA  0.1
3   NA  0.5 NA
3   NA  NA  0.2", header = TRUE)

A: You can first pivot_longer, then remove NA, and finally pivot_widerback again:
library(tidyverse)
df %>%
  pivot_longer(-id) %>%
  na.omit() %>%
  pivot_wider(names_from = name, values_from = value)
# A tibble: 3 × 4
     id  var2  var1  var3
  <dbl> <dbl> <dbl> <dbl>
1     1   0.4   0.8  NA
2     2   0.5   0.7   0.1
3     3   0.5  NA     0.2


text:
Q: Mongodb automatically changing datatype while storing values I have following code in asp.net mvc c#
   [Display(Name = "Marks Range ")]
    [Required(ErrorMessage = "Minimum Marks is Required.")]
    public int? min_marks { get; set; }

While storing data from from in mongodb the datatype automatically changes to string ?
Any reason for this strange behaviour or how to correct this ?

A: Using ScaffoldColumn for prevent from  default datatype :
   [Display(Name = "Marks Range ")]
   [Required(ErrorMessage = "Minimum Marks is Required.")]
   [ScaffoldColumn(false)]
   public int? min_marks { get; set; }


text:
Q: get invalid exception System.InvalidOperationException was unhandled
  Message=An error occurred creating the form. See Exception.InnerException for details.  The error is: Could not load file or assembly 'Interop.WMPLib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An attempt was made to load a program with an incorrect format.
  Source=kn diary
  StackTrace:
       at kn_diary.My.MyProject.MyForms.Create_Instance_[T](T Instance) in 17d14f5c-a337-4978-8281-53493378c1071.vb:line 190
       at kn_diary.My.MyProject.MyForms.get_Form1()
       at kn_diary.My.MyApplication.OnCreateMainForm() in C:\Users\Pak\Desktop\project\kn diary\kn diary\My Project\Application.Designer.vb:line 35
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
       at kn_diary.My.MyApplication.Main(String[] Args) in 17d14f5c-a337-4978-8281-53493378c1071.vb:line 81
       at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: System.BadImageFormatException
       Message=Could not load file or assembly 'Interop.WMPLib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An attempt was made to load a program with an incorrect format.
       Source=AxInterop.WMPLib
       FileName=Interop.WMPLib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
       FusionLog==== Pre-bind state information ===
LOG: User = Pak-PC\Pak
LOG: DisplayName = Interop.WMPLib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
 (Fully-specified)
LOG: Appbase = file:///C:/Users/Pak/Desktop/project/kn diary/kn diary/bin/Debug/
LOG: Initial PrivatePath = NULL
Calling assembly : AxInterop.WMPLib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null.
LOG: This bind starts in default load context.
LOG: Using application configuration file: C:\Users\Pak\Desktop\project\kn diary\kn diary\bin\Debug\kn diary.vshost.exe.config
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework64\v2.0.50727\config\machine.config.
LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
LOG: Attempting download of new URL file:///C:/Users/Pak/Desktop/project/kn diary/kn diary/bin/Debug/Interop.WMPLib.DLL.
ERR: Failed to complete setup of assembly (hr = 0x8007000b). Probing terminated.
   StackTrace:
        at AxWMPLib.AxWindowsMediaPlayer.AttachInterfaces()
        at System.Windows.Forms.AxHost.GetOcxCreate()
        at System.Windows.Forms.AxHost.TransitionUpTo(Int32 state)
        at System.Windows.Forms.AxHost.CreateHandle()
        at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
        at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
        at System.Windows.Forms.AxHost.EndInit()
        at kn_diary.Form1.InitializeComponent() in C:\Users\Pak\Desktop\project\kn diary\kn diary\Form1.designer.vb:line 91
        at kn_diary.Form1..ctor()
   InnerException:

A: This is an indication of failure to load one of the reference assemblies in the chain of references, in this case, an indirect reference.  I normally check the fusion log to find out exactly what assembly is failing to load and often why.
Can you check the fusion log and paste the log here in case if you do not already spot the culprit there?  You can lunch logger by running "fuslogvw.exe" from VS command prompt.  (this link has more detail on how to use the fusion log viewer: http://msdn.microsoft.com/en-us/library/e74a18c4(v=vs.80).aspx)


text:
Q: Does it possible use read only committed in Teradata? I have found that Teradata uses:
READ_ISOLATION_LEVEL= ACCESS|READ|WRITE

How it correspond to usual read commited/dirty in usual databases?
Thanks.

A: Not sure if this addresses your question entirely:
ACCESS locking would allow dirty reads allows WRITE lock to be in place. READ locking allows only committed reads and can block WRITE/EXCLUSIVE locks while reading data. WRITE lock prevents READ locks from access data but allows ACCESS (dirty read) lock to access data.


text:
Q: Looking for a specialized launch bar for WinXP/7 Looking for a launchbar that has the following capabilities:

*

*Icons only.

*Can be free-floating OR pinned to a specific window's title bar.

*In pinned mode, it has to smartly handle fitting between the title bar icons on the left and right. BONUS points for allowing title bar caption to remain visible.

*Applications can be dropped on the bar to add them.

*Data files can be dropped ON existing icons to launch the app with the designated data file.

*Each bar starts with a drop down menu icon that will allow for editing settings, organize order of existing icons, etc.

An example of something that fulfills all but the pinning aspect would be something like RocketDock. But what I'm looking for is something akin to adding a hotkey bar to an application that doesn't have it already.
Any ideas?

A: Use Rocketdock...

A: RocketDock can actually get down to using 16x16 pixel icons, which puts it in the ballpark of fitting onto a titlebar. But it can't be pinned to a window. At least I think it can't. Been awhile. When I ran it, I used 40 pixel size, but I distinctly remember trying it at the smallest size and it would have fit, or come within a pixel or two of fitting. The behaviour is very much what I want, except for the pinning issue. Heck, I'd even go for attaching the solution to the edge of the top window border, if being actually ON the titlebar is impossible.


text:
Q: Cloning a laptop drive with bootable Windows installation I have a laptop (Acer Swift 3) where I am trying to replace its 123GB M.2 drive with a larger 256GB drive. Ideally I want to clone the drive, including the Windows 10 installation.
Since the laptop only has one M.2 port I cannot clone the drive directly. So what I am trying to do is to clone the original drive to an external 256GB SSD and then to clone from that to the new M.2 drive.
I have used EaseUS Todo Backup for the cloning process since it came recommended on several websites. The cloning (from the original M.2 drive to the external SSD) seems to go well and all three partitions are recreated and the data seems to be all there. However, the system partition is not bootable, so I am not able to boot up from the external drive and clone to the new M.2 drive, which was my original idea. Or rather, it does try too boot up, but at some point Windows says it is not able to.
Now I need advice on how to proceed. I either need a way to make the external drive bootable, or a way to clone the drive in a way that will preserve all of the properties of the partitions.
I have actually tried to make several Live CD USB installations (Runtime Live CD, Clonezilla and GParted) but for some reason all of them seem to just stop at some point during the boot-up. I have tried creating them both manually and using creation tools, with same effect. Perhaps I am downloading the wrong versions - perhaps it's something else.
EDIT: I have now successfully cloned the disk using Clonezilla, but it still fails to start and the Windows repair tool is not able to fix the issue.


text:
Q: vector gives troubles I have short code as below:
#include <memory>
#include <vector>
#include <tuple>
using namespace std;

struct A
{
    A() {}
    vector<unique_ptr<int>> m;
    // Change the above line to "unique_ptr<int> m;" removes the compilation error
    // Or add a line "A(A const&) = delete;" removes the compilation error also
};

struct B
{
    tuple<A> t;
};

int main()
{
    A a;
    B b;
    return 0;
}

VC2013 NOV CTP compiler gives errors:
error C2280: 'std::unique_ptr<int,std::default_delete<_Ty>>::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)' : attempting to reference a deleted function xmemory0   593

Is this a compiler bug or code bug?

A: This was a bug in Visual Studio; according to @Gonmator's comment it's been fixed as of VS2013 Update 1.
It might have been similar to reported bugs such as
https://connect.microsoft.com/VisualStudio/feedback/details/801826/std-tuple-with-rvalue-references-not-working-if-clr-enabled
or
https://connect.microsoft.com/VisualStudio/feedback/details/891428/c-std-pair-has-no-default-move-constructor
— apparently MSVC has had several residual bugs involving "move semantics + std::tuple".


text:
Q: How to get something like the last order per customer? I've written the following query but it takes a lot of time. I'm trying to fetch the latest records inserted in my pm_data_records table per each node. Nodes are stored in pm_info table, one row per node.
I wrote a query and I think it retrieves my intended data but it takes 15 secs.
Note that I have more than a million records.
Here's the query:
SELECT
    info.pm_detail_id,
    ... ,
    info.pm_min_pressure,
    datas.`pm_detail_id`,
    ... ,
    MAX(pm_sent_time)
FROM
   `pm_data_records` as datas
RIGHT JOIN pm_info as info
   ON datas.pm_detail_id = info.pm_detail_id
GROUP BY
   info.pm_detail_id
ORDER BY
   info.pm_detail_id

tnx a lot

A: Your query is not correct -- the GROUP BY and SELECT clauses are inconsistent.  Here is a correct version:
SELECT i.*, dr.*
FROM pm_info i LEFT JOIN
     pm_data_records dr
     ON i.pm_detail_id = dr.pm_detail_id AND
        dr.pm_sent_time = (SELECT MAX(dr2.pm_sent_time)
                           FROM pm_data_records dr2
                           WHERE dr2.pm_detail_id = dr.pm_detail_id
                        );

Now that you have a reasonable query, you can work on optimizing it.  This query wants an index on pm_data_records(pm_detail_id, pm_sent_time).


text:
Q: Retrieving SelectedIndex value of a GridView inside an UpdatePanel I have a GridView inside an UpdatePanel inside a ModalPopup. I'm using this for when a user wants to change roles in the system. They select a new role from the list (the UpdatePanel prevents the page from refreshing when a selection is made) and presses "Ok". The Ok button's OnClick event fires and uses the GridView's SelectedIndex to match up with a DataRow. The DataRow is used to collect the changed user data to create a new cookie (This is FormsAuthentication). The old cookie is removed, the GenericPrinciple is reset, and the new cookie is added. The page then refreshes (forced with Response.Redirect()).
The problem is that when the Ok button (not set as the Popup's OkControlID) is outside the UpdatePanel, the SelectedIndex retrieved is -1. When the button is inside the UpdatePanel or set as an asynchronous trigger, nothing happens.
Here is the .aspx code for the popup:
<ajaxToolkit:ModalPopupExtender ID="mpeRole" runat="server"
    TargetControlID="btnRole" CancelControlID="btnCancel"
    PopupControlID="pnlRole" BackgroundCssClass="modalBackground">
</ajaxToolkit:ModalPopupExtender>
<asp:Panel ID="pnlRole" runat="server" style="width: 350px" CssClass="popup">

        <asp:UpdatePanel runat="server">
            <ContentTemplate>
                <asp:GridView ID="gvRole" runat="server"
                    AutoGenerateColumns="false" Width="300px">
                    <Columns>
                        <asp:TemplateField HeaderText="Select a role">
                            <ItemTemplate>
                                <asp:LinkButton runat="server"
                                    Text="<%# Container.DataItem %>"
                                    CommandName="Select" />
                            </ItemTemplate>
                            <HeaderStyle Font-Size="Medium" />
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>
            </ContentTemplate>
        </asp:UpdatePanel>

            <asp:Button ID="btnOk" runat="server" Text="OK" Width="60px"
                onclick="btnOk_Click" />

            <asp:Button ID="btnCancel" runat="server" Text="Cancel"
                Width="60px" />

</asp:Panel>

And this is the code-behind of the OnClick and Page_Load events:
    GetRolesTableAdapter roleAdapter = new GetRolesTableAdapter();
protected void Page_Load(object sender, EventArgs e)
{
    DataTable dt;
    DataRow dr;

    /* nameAdapter */
    if (!Page.IsPostBack)
    {
        // Set lblName
        try
        {
            AppUser_NameTableAdapter nameAdapter = new AppUser_NameTableAdapter();
            dt = nameAdapter.GetData(uState.id);
            dr = dt.Rows[0];

            lblName.Text = dr.Field<string>("FirstName") + " " + dr.Field<string>("MiddleName") + " " + dr.Field<string>("LastName");
        }
        catch
        {
            Response.Write(uState.id.ToString());
        }
    }

    // Set lblDate
    lblDate.Text = DateTime.Now.ToLongDateString() + " | " + DateTime.Now.ToShortTimeString();

    /* roleAdapter */
    // Set lblRole and lvRole
    dt = roleAdapter.GetData(uState.id);
    string[] arr = new string[dt.Rows.Count];

    for (int i = 0; i < dt.Rows.Count; i++)
    {
        dr = dt.Rows[i];
        string[] tmp = new string[] {
            dr.Field<string>("ProgModel"),
            dr.Field<string>("Site"),
            dr.Field<string>("Team"),
            dr.Field<string>("Position"),
            dr.Field<string>("Role") };
        arr[i] = string.Join(" - ", tmp.Where(s => !string.IsNullOrEmpty(s)).ToArray());
        if (uState.roleVal == dr.Field<byte>("RoleID") && uState.userPos == dr.Field<int?>("UserPosID"))
        {
            lblRole.Text = arr[i];
        }
    }

    gvRole.DataSource = arr;
    gvRole.DataBind();
    gvRole.SelectedIndex = -1;

    // Display btnRole if there is more than one role for the user
    if (dt.Rows.Count > 1)
        btnRole.Visible = Visible;
}
protected void btnOk_Click(object sender, EventArgs e)
{
    // Ensure a row was selected
    if (gvRole.SelectedIndex != -1)
    {
        try
        {
            // Get data for login
            DataTable dt = roleAdapter.GetData(uState.id);
            DataRow dr = dt.Rows[gvRole.SelectedIndex];

            UserState newState = new UserState();
            newState.id = uState.id;
            newState.role = dr.Field<string>("Role");
            newState.roleVal = dr.Field<byte>("RoleID");
            newState.position = dr.Field<int?>("PositionID");
            newState.programModel = dr.Field<int?>("ProgModelID");
            newState.site = dr.Field<int?>("SiteID");
            newState.team = dr.Field<int?>("TeamID");
            newState.userPos = dr.Field<int?>("UserPosID");

            // Get old ticket
            HttpCookie oldCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
            FormsAuthenticationTicket oldTicket = FormsAuthentication.Decrypt(oldCookie.Value);

            // Create a new ticket used for authentication
            var newTicket = new FormsAuthenticationTicket(
                1, // Ticket version
                oldTicket.Name.ToString(), // Username associated with ticket
                DateTime.Now, // DateTime issued
                DateTime.Now.AddMinutes(60), // DateTime for expiration
                true, // "true" for persistent user cookie
                newState.ToString(), // Userdata,
                FormsAuthentication.FormsCookiePath);

            // Encrypt the cookie using the machine key for secure transport
            string hash = FormsAuthentication.Encrypt(newTicket);
            HttpCookie cookie = new HttpCookie(
                FormsAuthentication.FormsCookieName, // Name of auth cookie
                hash); // Hashed ticket

            // Set the cookie's expiration time to the ticket's expiration time
            if (newTicket.IsPersistent) cookie.Expires = newTicket.Expiration;

            // Remove old cookie and principle
            HttpContext.Current.User = new GenericPrincipal(new GenericIdentity(string.Empty), null);

            // Add the cookie to the list for outgoing response
            Response.Cookies.Remove(oldCookie.Name);
            Response.Cookies.Add(cookie);

            // Refresh page
            Response.Redirect("~/foo.aspx", true);
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message.ToString().Trim());
            Response.Write(ex.StackTrace.ToString().Trim());
        }
    }
    else
    {
        Response.Write(gvRole.SelectedIndex.ToString());
    }
}

Update 1
I noticed that if btnOk is added as an AsyncPostBackTrigger for the UpdatePanel and you hit ok after making a selection, you can't change the selection until you refresh the page. I've tried waiting for a change but nothing happens.
Update 2
I decided to try something else. I removed the UpdatePanel and btnOk. I added a SelectedIndexChanged event handler for gvRole and copied btnOk's code sans SelectedIndex > -1 check. This worked. When I click an item, the page refreshes and the role changes instantly. I'm leaving this question open, though. I still want to know why this wasn't working and how I can solve it in the future.


text:
Q: Numerical integration for equations of motion m = 10(*body of mass*)
e = 0.705(*eccentricity*)
MA = 354.4223(*Mean Anomoly*)
Mo = 12.30336608(*Mean Motion*)
n = Mo*(2*Pi/86400)
μ = 3.986004418*10^14(*Grav parameter of Earth*)
ψ = MA + 2*e*Sin[MA] + 1.25*e^2*Sin[2*MA](*True Anomoly*)
a = ((μ^(1/3))/(n^(2/3)))(*semi major axis*)

I have a body of mass m that is orbiting the Earth. m has an inital postion of 8.65e6e6 m, using the equation of orbital motion:
r[ψ] == a(1 - e^2)/(1 + e Cos[ψ])

and the initial velocity of 6681.5 m/s using equation of orbtial velocity
v = Sqrt[μ (2/r - 1/a)]

The body of mass has a gravitational force of:
Fg = -G M m/r^2 = μ m/r^2

(G M = μ, the standard gravitational parameter of earth)
where the acceleration of the body is given by
a = Fg/m = -μ/r^2

I'm trying to use NDsolve and the differetial equations
orb =
  {x''[t] == (-μ x[t])/(x[t])^3,
   y''[t] == (-μ x[t])/(x[t])^(3),
   x[0] == 8.65*10^6, y[0] == 0,
   x'[0] == 0, y'[0] == 6681.5};

I've been following this video: https://www.youtube.com/watch?v=dEWTX2yA8qM
I'd like to use the expression r, to show elliptical motion of the body, over the range {ψ, 0, 2 Pi}.
I'm trying to plot the orbital path of the body m, using these differential equations. However im stuck at this point.
I think I'm on the right path to solving this problem, but I think I have to include the expression for r[ψ] in the differential equation. Any guidance on how to proceed would be appreciated.


text:
Q: Multiple audio outputs in .Net I am looking to build a PC box that can play up to 16 audio files(mp3/wav) out to 16 analog devices(think of it as 16 sets of speakers).  There will be a one to one relationship for audio file to analog output. The solution that is being presented to be hardware wise is to use multiple sound cards, so my question is, is there a library available that will let me play an audio file to a specific sound card / channel?

A: Yes, the BASS library can do this.
http://www.un4seen.com
C# wrappers are also available, a commercial one:
Bass.NET
and an excellent alternative open source C# wrapper for Bass:
ManagedBass by Mathew Sachin

A: I found this one while I was looking as well.
http://www.alvas.net/alvas.audio.aspx

A: FMOD should do what you're looking for.  It's also an extremely fast, solid and popular library overall.


text:
Q: Cannot see the checkbox and the text in the body of the App I am a beginner in Dart and Flutter. I followed the Flutter YouTube channel's first video in Flutter, and they created a basic page with a checkbox and a progress indicator.
I followed and I can see the progress indicator in the app, but I can't see any checkboxes or the text adjacent to the checkboxes that I had specified. There seems to be no error too! or there is but I couldn't find it!
The main.dart file

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter App',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Checkbox'),
      ),
      body: Column(
        children: [
          MyProgress(),
        ],
      ),
    );
  }
}

class MyProgress extends StatelessWidget {
  const MyProgress({super.key});

  @override
  Widget build(BuildContext context) {
    return Column(
      children: const [
        Text("Your Progess can be viewed here!"),
        LinearProgressIndicator(value: 0.0),
      ],
    );
  }
}

class TaskItem extends StatelessWidget {
  final String label;
  const TaskItem({Key? key, required this.label}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [Checkbox(value: false, onChanged: null), Text(label)],
    );
  }
}

class TaskList extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        TaskItem(label: "AI Note"),
        TaskItem(label: "DAA Note"),
        TaskItem(label: "DDM Note"),
        TaskItem(label: "DPCO Note"),
        TaskItem(label: "DM Note"),
      ],
    );
  }
}

A:
I can't see any checkboxes or the text

its because you not call the TaskList in your scren.
Widget build(BuildContext context) {
   return Scaffold(
      appBar: AppBar(
        title: Text('Checkbox'),
      ),
      body: Column(
        children: [
          MyProgress(), // you only show the linear progress
          TaskList(), // all you need to do is, to add this
        ],
      ),
    );


text:
Q: How to debug realm feature in Tomcat? I have set the realm setting in server.xml host section to something like this:
<Realm  className="org.apache.catalina.realm.JDBCRealm"  driverName="org.gjt.mm.mysql.Driver"
         connectionURL="jdbc:mysql://localhost:3306/test" connectionName="test" connectionPassword="test"
             userTable="users" userNameCol="user_name" userCredCol="user_pass" userRoleTable="user_roles"
       roleNameCol="user_role" />

Also in web.xml:
<security-role>
    <role-name>ADMIN</role-name>
</security-role>

<security-constraint>
    <web-resource-collection>
        <web-resource-name>critical</web-resource-name>
        <url-pattern>/admin/*</url-pattern>
        <http-method>GET</http-method>
        <http-method>POST</http-method>
    </web-resource-collection>
    <auth-constraint>
        <role-name>ADMIN</role-name>
    </auth-constraint>
</security-constraint>

<login-config>
    <auth-method>FORM</auth-method>
    <form-login-config>
        <form-login-page>/login.jsp</form-login-page>
        <form-error-page>/error.jsp</form-error-page>
    </form-login-config>
</login-config>

And I have the databased set up. However when login.jsp is envoked, even I entered the right password I was redirected to error.jsp
I want to know if there is a way to find what's wrong during the process. Can I do it in Eclipse or any other hints that may solve the problem?

A: To get the debug information from the Realm authentication steps, follow this procedure.
When you define your Realm in the server.xml, add debug="9" to the definition (you can of course use a lower number for less detail).
<Realm  className="org.apache.catalina.realm.JDBCRealm"  driverName="org.gjt.mm.mysql.Driver"
   connectionURL="jdbc:mysql://localhost:3306/test" connectionName="test" connectionPassword="test"
   userTable="users" userNameCol="user_name" userCredCol="user_pass" userRoleTable="user_roles"
   roleNameCol="user_role" debug="9" />

You also need to add this to your logging.properties file:
org.apache.catalina.realm.level = ALL
org.apache.catalina.realm.useParentHandlers = true
org.apache.catalina.authenticator.level = ALL
org.apache.catalina.authenticator.useParentHandlers = true

You may also need to add this, to prevent bufferring of the logs.  If you do, remember to remove it after you've finished debugging.
1catalina.org.apache.juli.FileHandler.bufferSize = -1

Now, the debug logs for the realms should end up in the catalina.out file.

A: For others finding this issue, I found the following worked for Tomcat 8.5.40:
java.util.logging.ConsoleHandler.level = ALL
org.apache.catalina.level = FINEST
org.apache.catalina.realm.JNDIRealm.level = FINEST
org.apache.catalina.realm.JNDIRealm.useParentHandlers = true

The key fact appears to be that your logging travels through several layers of definitions and will be trimmed by the first one that has a lower level so you need to make sure that each bit it passes through is FINEST or ALL.
Hopefully this will save someone some time ;)
Ian.


text:
Q: How to normalize a slope? Say I have two slopes and two averages for a sample:
$m=4{,}000$ dollars/day, average $a=50{,}000$
$n=80{,}000$ dollars/day, average $b=700{,}000$
Graphically, $n$ is very 'steep' compared to $m$. But I know that $n$ is not very steep relative to it's average size ($b=700{,}000$). Is there a way that I could get a 'percent slope', so that I could compare the slopes of these two values relative to the average size?

A: You can simply express this relative change as a fraction, namely
$$\frac ma=0.080=8.0\%\qquad\text{resp.}\qquad\frac nb\approx0.114=11.4\%$$