text:
Q: crash on Orientation change while filming with Library CWAC CAM2 I've a crash on my nexus 5 Android 6 (hammered/hammered) using CommonsWare library cwac:cam2
when I change the orientation on the recording/photo capturing activities. The bug is systematic on my device.
stacktrace :
E / AndroidRuntime: FATAL EXCEPTION: main
Process: com.m360learning.android, PID: 9637
java.lang.RuntimeException: Unable to start activity ComponentInfo {
 com.m360learning.android / com.commonsware.cwac.cam2.VideoRecorderActivity
}: de.greenrobot.event.EventBusException: Subscriber class com.commonsware.cwac.cam2.CameraFragment already registered to event class com.commonsware.cwac.cam2.CameraController$ControllerReadyEvent
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java: 2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java: 2476)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java: 4077)
at android.app.ActivityThread. - wrap15(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java: 1350)
at android.os.Handler.dispatchMessage(Handler.java: 102)
at android.os.Looper.loop(Looper.java: 148)
at android.app.ActivityThread.main(ActivityThread.java: 5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java: 726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java: 616)
Caused by: de.greenrobot.event.EventBusException: Subscriber class com.commonsware.cwac.cam2.CameraFragment already registered to event class com.commonsware.cwac.cam2.CameraController$ControllerReadyEvent
at de.greenrobot.event.EventBus.subscribe(EventBus.java: 179)
at de.greenrobot.event.EventBus.register(EventBus.java: 165)
at de.greenrobot.event.EventBus.register(EventBus.java: 133)
at com.commonsware.cwac.cam2.CameraFragment.onStart(CameraFragment.java: 123)
at android.app.Fragment.performStart(Fragment.java: 2244)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java: 1002)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java: 1148)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java: 1130)
at android.app.FragmentManagerImpl.dispatchStart(FragmentManager.java: 1958)
at android.app.FragmentController.dispatchStart(FragmentController.java: 163)
at android.app.Activity.performStart(Activity.java: 6274)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java: 2379)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java: 2476)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java: 4077)
at android.app.ActivityThread. - wrap15(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java: 1350)
at android.os.Handler.dispatchMessage(Handler.java: 102)
at android.os.Looper.loop(Looper.java: 148)
at android.app.ActivityThread.main(ActivityThread.java: 5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java: 726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java: 616)

Thank you very much for the support, the fixes are very quicly implemented.

A: The issue is the you are trying to register the service twice enter code here as you can see in the trace. The service isn't unregistered therefore the easiest option for you is to check whether the service is registered before you register it EventBus.getDefault().isRegistered(...)or check in onStart is event service isn't stopped and therefore still registered. For example:
if (!EventBus.getDefault().isRegistered(this)) {
    EventBus.getDefault().register(this);
}


text:
Q: VS Code built-in color picker feature doesn't work in JSON files I have found info that VS Code has built-in color picker feature
But I can't figure out why it doesn't work for my JSON files.
For instance, this is my apple.json file:
{
    "apple": {
        "color": "#ff0000"
    }
}

So, color picker doesn't appear.
But - if I open VS Code's own settings.json file, and update it like so, for instance:
{
"workbench.colorCustomizations": {
    "activityBar.background": "#00AA00"
  }
}

color picker will instantly appear.
Why? What differs apple.json from settings.json?

A: To have that work, you need a JSON schema associated with the json file.
The schema has to say format: color on the property that represents a color. Only then a color decorator and picker is shown.
You can look here if you want to set up your own JSON schema:
https://code.visualstudio.com/docs/languages/json#_json-schemas-and-settings

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there any difference between the terminals of the rheostat This is probably a dumb question but I just wanted to be sure for my practical exams.
Is there any difference between the upper or the lower terminal of the rheostat? Are you supposed to connect the positive terminal of the battery to any specific terminal of the rheostat or is it all the same? Thanks in advance.

A: No there are no differences other than physical position. The rheostat is just a variable resistor with no regard to polarity. After all, it works perfectly well on AC but, if you pushed the frequency up to the MHz and beyond then maybe you'd start see some effects. You might also see some polarity effects in a damp corrosive atmoshphere too.

A: Short answer is No.
A rheostat is a different kind of potentiometer so the only difference really is that the two end terminals are two different ends of (basically) a piece of wire.
The effect of polarity across the terminals changes the direction of current.


text:
Q: Keyboard module doesn't work in a tkinter Gui I wanted to create a keyboard whose keys were
colored when I pressed the key on the keyboard.
The code has no errors, but when the button is pressed, nothing happens:
I don't now if is possible to do that keyboard with that module or i made some errors.
Please, help me.
import tkinter as tk
import keyboard

class SensibleKeyboard:

    def __init__(self):
        self.root = tk.Tk()
        self.root.title("Sensible Keyboard")
        self.root.resizable(False,False)
        self.root.geometry("520x265")

        #Titolo
        self.title = tk.Label(text = "SensibleKeyboard",font = ("Arial",26)).place(x = 120 ,y = 10)

        #Frame contenitore tastiera
        self.frame = tk.Frame(width = 520, height = 165, bg = "#fff")
        self.frame.place(x = 0, y = 100)

        #Tastiera grafica
        #Riga 1
        self.q =  tk.Button(self.frame,text = "Q", height = 3, width = 6, activebackground = "black", activeforeground = "white").place(x = 0 , y = 0)
        self.w =  tk.Button(self.frame,text = "W", height = 3, width = 6, activebackground = "black", activeforeground = "white").place(x = 52 , y = 0)
        self.e =  tk.Button(self.frame,text = "E", height = 3, width = 6, activebackground = "black", activeforeground = "white").place(x = 104 , y = 0)
        self.r =  tk.Button(self.frame,text = "R", height = 3, width = 6, activebackground = "black", activeforeground = "white").place(x = 156 , y = 0)
        self.t =  tk.Button(self.frame,text = "T", height = 3, width = 6, activebackground = "black", activeforeground = "white").place(x = 208 , y = 0)
        self.y =  tk.Button(self.frame,text = "Y", height = 3, width = 6, activebackground = "black", activeforeground = "white").place(x = 260 , y = 0)
        self.u =  tk.Button(self.frame,text = "U", height = 3, width = 6, activebackground = "black", activeforeground = "white").place(x = 312 , y = 0)
        self.i =  tk.Button(self.frame,text = "I", height = 3, width = 6, activebackground = "black", activeforeground = "white").place(x = 364 , y = 0)
        self.o =  tk.Button(self.frame,text = "O", height = 3, width = 6, activebackground = "black", activeforeground = "white").place(x = 416 , y = 0)
        self.p =  tk.Button(self.frame,text = "P", height = 3, width = 6, activebackground = "black", activeforeground = "white").place(x = 468 , y = 0)

        #Riga 2
        self.a =  tk.Button(self.frame,text = "A", height = 3, width = 6, activebackground = "black", activeforeground = "white").place(x = 17 , y = 56)
        self.s =  tk.Button(self.frame,text = "S", height = 3, width = 6, activebackground = "black", activeforeground = "white").place(x = 69 , y = 56)
        self.d =  tk.Button(self.frame,text = "D", height = 3, width = 6, activebackground = "black", activeforeground = "white").place(x = 121 , y = 56)
        self.f =  tk.Button(self.frame,text = "F", height = 3, width = 6, activebackground = "black", activeforeground = "white").place(x = 173 , y = 56)
        self.g =  tk.Button(self.frame,text = "G", height = 3, width = 6, activebackground = "black", activeforeground = "white").place(x = 225 , y = 56)
        self.h =  tk.Button(self.frame,text = "H", height = 3, width = 6, activebackground = "black", activeforeground = "white").place(x = 277 , y = 56)
        self.j =  tk.Button(self.frame,text = "J", height = 3, width = 6, activebackground = "black", activeforeground = "white").place(x = 329 , y = 56)
        self.k =  tk.Button(self.frame,text = "K", height = 3, width = 6, activebackground = "black", activeforeground = "white").place(x = 381 , y = 56)
        self.l =  tk.Button(self.frame,text = "L", height = 3, width = 6, activebackground = "black", activeforeground = "white").place(x = 433 , y = 56)

        #Riga 3
        self.z =  tk.Button(self.frame,text = "Z", height = 3, width = 6, activebackground = "black", activeforeground = "white").place(x = 40 , y = 112)
        self.x =  tk.Button(self.frame,text = "X", height = 3, width = 6, activebackground = "black", activeforeground = "white").place(x = 92 , y = 112)
        self.c =  tk.Button(self.frame,text = "C", height = 3, width = 6, activebackground = "black", activeforeground = "white").place(x = 144 , y = 112)
        self.v =  tk.Button(self.frame,text = "V", height = 3, width = 6, activebackground = "black", activeforeground = "white").place(x = 196 , y = 112)
        self.b =  tk.Button(self.frame,text = "B", height = 3, width = 6, activebackground = "black", activeforeground = "white").place(x = 248 , y = 112)
        self.n =  tk.Button(self.frame,text = "N", height = 3, width = 6, activebackground = "black", activeforeground = "white").place(x = 300 , y = 112)
        self.m =  tk.Button(self.frame,text = "M", height = 3, width = 6, activebackground = "black", activeforeground = "white").place(x = 352 , y = 112)

        #Funzione accensione da tastiera
        #Funzioni
        if keyboard.is_pressed("q"):
            self.q.config(bg = "blue")
        elif keyboard.is_pressed("w"):
            self.w.config(bg = "blue")
        elif keyboard.is_pressed("e"):
            self.e.config(bg = "blue")
        elif keyboard.is_pressed("r"):
            self.r.config(bg = "blue")
        elif keyboard.is_pressed("t"):
            self.t.config(bg = "blue")
        elif keyboard.is_pressed("y"):
            self.y.config(bg = "blue")
        elif keyboard.is_pressed("u"):
            self.u.config(bg = "blue")
        elif keyboard.is_pressed("i"):
            self.i.config(bg = "blue")
        elif keyboard.is_pressed("o"):
            self.o.config(bg = "blue")
        elif keyboard.is_pressed("p"):
            self.p.config(bg = "blue")
        elif keyboard.is_pressed("a"):
            self.a.config(bg = "blue")
        elif keyboard.is_pressed("s"):
            self.s.config(bg = "blue")
        elif keyboard.is_pressed("d"):
            self.d.config(bg = "blue")
        elif keyboard.is_pressed("f"):
            self.f.config(bg = "blue")
        elif keyboard.is_pressed("g"):
            self.g.config(bg = "blue")
        elif keyboard.is_pressed("h"):
            self.h.config(bg = "blue")
        elif keyboard.is_pressed("j"):
            self.j.config(bg = "blue")
        elif keyboard.is_pressed("k"):
            self.k.config(bg = "blue")
        elif keyboard.is_pressed("l"):
            self.l.config(bg = "blue")
        elif keyboard.is_pressed("z"):
            self.z.config(bg = "blue")
        elif keyboard.is_pressed("x"):
            self.x.config(bg = "blue")
        elif keyboard.is_pressed("c"):
            self.c.config(bg = "blue")
        elif keyboard.is_pressed("v"):
            self.v.config(bg = "blue")
        elif keyboard.is_pressed("b"):
            self.b.config(bg = "blue")
        elif keyboard.is_pressed("n"):
            self.n.config(bg = "blue")
        elif keyboard.is_pressed("m"):
            self.m.config(bg = "blue")
        else:
            pass
    def start(self):
        self.root.mainloop()
sk = SensibleKeyboard()
sk.start()

A: You do not need the keyboard library to handle this.
First lets fix your very redundant code. Instead of writing each button one at a time we can do this in a dynamic way based on a list of characters. At the same time we can store our buttons in a list that we can use to update the buttons on click.
With the use of bind() we can check if one of the keys was press and then update the corresponding button in the list.
By binding all Key Presses and all Key Releases we can use a method to check if one of those keys was from our list and if so update the button on key press and key release.
import tkinter as tk

class SensibleKeyboard(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("Sensible Keyboard")
        self.resizable(False, False)
        self.geometry("520x265")
        self.title = tk.Label(text="SensibleKeyboard",
                              font=("Arial", 26)).grid(row=0, column=0, pady=20, sticky='ew')
        main_frame = tk.Frame(self)
        main_frame.grid(row=1, column=0, sticky='ew')
        self.orig_color = self.cget("background")
        self.btn_list = []
        btn_rows = ['QWERTYUIOP', 'ASDFGHJKL', 'ZXCVBNM']
        row_pad = 0
        btn_ndex = 0
        for ndex, rows in enumerate(btn_rows):
            row_frame = tk.Frame(main_frame)
            row_frame.grid(row=ndex, column=0, sticky='ew', padx=(row_pad,0))
            row_pad += 20
            for row_ndex, value in enumerate([char for char in rows]):
                self.btn_list.append(tk.Button(row_frame, text=value, height=3, width=6,
                                               activebackground="black", activeforeground="white"))
                self.btn_list[-1].grid(row=0, column=row_ndex)
                btn_ndex += 1
        self.bind('<KeyPress>', lambda e: self.change_bg(e, 'p'))
        self.bind('<KeyRelease>', lambda e: self.change_bg(e, 'r'))

    def change_bg(self, event, press_type):
        print(event)
        c = event.char.upper()
        for btn_ndex, value in enumerate([char for char in 'QWERTYUIOPASDFGHJKLZXCVBNM']):
            if value == c:
                if press_type == 'p':
                    self.btn_list[btn_ndex].config(bg='blue')
                else:
                    self.btn_list[btn_ndex].config(bg=self.orig_color)
                break

if __name__ == '__main__':
    SensibleKeyboard().mainloop()


text:
Q: chrome-remote-desktop, new X session After installing chrome-remote-desktop on Ubuntu 18.04, I had issues with google-chrome not opening correctly and also terminal would not open. Also, trying to remote in would give me a blank screen on the client machine.
After following the instructions here,
https://medium.com/@vsimon/how-to-install-chrome-remote-desktop-on-ubuntu-18-04-52d99980d83e
remote desktop works flawlessly, with the existing X session on the host machine.
The question is how can I make remote desktop work with using a new X session, as its intended by the default chrome-remote-desktop script?

A: Short answer: yes, but you need to use cinnamon for remote sessions. Local users can use Unity or whatever they want.
Symptoms: in remote session: xterm runs, gnome-terminal/nautilus does not.
Short fix:
sudo DEBIAN_FRONTEND=noninteractive \
    apt install --assume-yes cinnamon-core desktop-base

sudo bash -c 'echo "exec /etc/X11/Xsession /usr/bin/cinnamon-session-cinnamon2d" > /etc/chrome-remote-desktop-session'

Long answer.
I recently tried to get chrome-remote-desktop on Ubuntu 20.04, and found that most of the instructions either ignore issues with sessions (gnome-terminal does not open, etc); or patch /opt/google/chrome-remote-desktop/chrome-remote-desktop with
FIRST_X_DISPLAY_NUMBER = 0, etc, which is not helpful if I want to sign in with multiple accounts at the same time.
There are Google instructions on installing chrome-remote-desktop on virtual instance:
https://cloud.google.com/solutions/chrome-desktop-remote-on-compute-engine
which insist on disabling the display manager. I decided to follow that guide but without disabling display manager. And it worked!
Step-by-step:

*

*Create additional [local] user accounts. Account which is used to setup remote access won't be accessible for regular sign in (at some point I was getting an error message from remote desktop where it blamed a bug in display manager; I tried gdm3, lightdm, and sddm with no luck).

Note: if you forgot to create an additional [local] account you can "unlock" it by visiting https://remotedesktop.google.com/ on another machine and deleting remote device you set up.
2.
# Install cinnamon
sudo DEBIAN_FRONTEND=noninteractive \
    apt install --assume-yes cinnamon-core desktop-base

# Select default session
sudo bash -c 'echo "exec /etc/X11/Xsession /usr/bin/cinnamon-session-cinnamon2d" > /etc/chrome-remote-desktop-session'

# Download remote desktop.
wget https://dl.google.com/linux/direct/chrome-remote-desktop_current_amd64.deb

# apt install will install it together with dependencies.
sudo apt install ./chrome-remote-desktop_current_amd64.deb

# Allow this user to setup machine for remote access.
# You will be logged in by this user when using chrome remote desktop.
# It is possible to list multiple users in this group, and access your machine with multiple remote sessions simultaneously.
sudo usermod -a -G chrome-remote-desktop $USER

# Install Google Chrome (if not installed yet)
wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
sudo apt install ./google-chrome-stable_current_amd64.deb

*Go to https://remotedesktop.google.com/, and setup this machine for access.

*Reboot.
There are extra steps listed at
https://cloud.google.com/solutions/chrome-desktop-remote-on-compute-engine
(like enabling clipboard), but I did not try it.
I was able to login to my machine with two users simultaneously using remote desktop (and run gnome-terminal in the cinnamon session), and third user running Unity desktop directly on machine.


text:
Q: Dual of the fact that equalizers are dependent sums over the identity type An equalizer of $A$ along two morphisms $f, g : A \to B$ can be thought of as a dependent sum over an identity type (see nLab):
$$A|_{f = g} = \sum_{a : A} (f(a) = g(a))$$
Does this idea have a dual? Can we somehow express a coequalizer (quotient type) using dependent products and whatever the "dual of an identity type" is?


text:
Q: React useState() issue I have a problem with using function component. I'm writing Hangman game and i stuck while trying to do staff about letters discovering. Here is my code.
App.js
import CreateSubject from './components/CreateSubject'
import Hangman from './components/Hangman'
import { HangmanProvider } from './context/HangmanContext'

function App() {
  return (
    <HangmanProvider>

        <CreateSubject/>
        <Hangman/>

    </HangmanProvider>
  );
}

export default App;

CreateSubject.js
import {HangmanContext } from '../context/HangmanContext'

function CreateSubject(props){

    const {password,displayGame,displayForm} = useContext(HangmanContext)
    const [subject,setSubject] = password
    const [gameDisplay,setGameDisplay] = displayGame
    const [createSubjectDisplay,setCreateSubjectDisplay] = displayForm

    const handleSubmit = (e) =>{
        e.preventDefault()
        if(subject != ''){
            setCreateSubjectDisplay('none')
            setGameDisplay('')
        }
    }
    const handleChange = (e) =>{
        setSubject(e.target.value)
        e.target.value = subject
    }
    return(
        <form style={{display: createSubjectDisplay}} onSubmit={handleSubmit}>

Enter a Word:

                <input type='text'
                 value={subject}
                 onChange={handleChange}
                 className='createSubject'
                 maxLength='40'/>

            <button type='submit'>Create</button>
        </form>
    )
}

export default CreateSubject

Hangman.js
import al from '../alphabet'
import {HangmanContext} from '../context/HangmanContext'

const Hangman = (props) =>{
    const {password,displayGame,displayForm} = useContext(HangmanContext)

    const [subject,setSubject] = password
    const [gameDisplay,setGameDisplay] = displayGame
    const [createSubjectDisplay,setCreateSubjectDisplay] = displayForm

    let passwordArr = Array.from(subject)
    const [hiddenPassword,changeHiddenPassword] = useState()

    useEffect(() => {
        let passwordArr = Array.from(subject)
        changeHiddenPassword(passwordArr.map(item => '_'))
    },[]);

    const chooseLetter = (e) => {
        let letter = e.target.innerHTML
        passwordArr.forEach((e,i) => {
            if (e == letter){
              console.log(hiddenPassword)
            }
        })
    }

    const letters = al.map((letter) =>
        {letter}
    )

    return(

                {
                //passwordArr.map((item,i) => {hiddenPasswordArr[i]})
                }

Enter password:<input type='text' maxLength='30'/>

 {letters}

    )
}

export default Hangman

My problem is in Hangman.js when i'm trying to change 'hiddenPassword' state which is an array. When i'm outputing this state in console it shows me an empty array. What have i done wrong ?

A: You need to initialize your hiddenPassword state:
const [hiddenPassword,changeHiddenPassword] = useState(passwordArr.map(item => '_'))

A: subject might have to be in the useEffect's dependency array
    useEffect(() => {
        let passwordArr = Array.from(subject)
        changeHiddenPassword(passwordArr.map(item => '_'))
    },[subject]);


text:
Q: Is a SQL Server scalar value recognized in Entity Framework 6? I have a function that returns a table default constraint. I want to use that value for calculations in another table. When query my application, the result set has the correct values (check out BaseValue and ExpcUnits):

However, when I run my ASP.NET MVC application, I get the following error:

The cast to value type 'System.Double' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.

This is part of my query:
select
    b.TimeOffHrs, b.TrainHrs,
    (((a.Bizdays * 8)*(b.FTEVar)-(b.TrainHrs+b.TimeOffHrs)) * (dbo.fn_GetActiveStaffBaseValue(@staffNo, a.Month, a.Year)/8)) as ExpcUnits,
    c.staffno, c.TotalUnits,
    dbo.fn_GetActiveStaffBaseValue(@staffNo, a.Year, a.Month) AS BaseValue,

I've replaced the function with hardcoded values and it works in the application.  I don't know why it doesn't work with my function.


text:
Q: Subplots by variable ID on Plotly Express with Python I have plot like this:
var_names = [i for i in test_df.variable.unique()]
var_names.sort()

fig = px.scatter(test_df, x='date', y='value', color='variable', category_orders={'variable': var_names},
                template="ggplot2", title='Median of access',
                 labels={'value': 'Median of access on the week', 'date': 'Week'}
                 ).update_traces(mode='markers+lines')
fig.show()

And my dataframe is:
test_df = pd.DataFrame({
        'ID':list('aabdee'),
        'date':['2020-03-22', '2020-03-22', '2020-03-29', '2020-03-22','2020-03-22', '2020-03-29'],
         'B':[1,0.5,4,5,5,4],
         'C':[7,8,9,4,2,3],
         'D':[1,3,1,7,1,1],
         'E':[5,3,6,9,2,4]
})
test_df = test_df.melt(['ID', 'date']).

I want to run the code just once and build different subplots depending on the ID, like if each graph in the picture below were corresponding to the variables of a specific ID.
 I tried with 'add trace' as is on the doc, but if I do this I have to copy and paste the code each time filtering by the ID.

Thank you a lot!

A: In the end was super simple, the problem is that the documentation of plotly express is not so easy to find.
So, you can put the variable facet_col='ID' on your px.scatter(...) and it works :).


text:
Q: Who built the large-scale cell phone sonar device? In the Christopher Nolan Batman movies, Lucious Fox seems to be the primary technologic mastermind. In fact, we're never shown Batman/Bruce actually inventing anything new himself - just devising clever uses for existing technology.
Fox was the one who created the cell phone sonar technology until Bruce redirects all the money in R&D to build a large scale version of the device.
Bruce explains that he is spending the money on a government contract and "playing this one close to the chest".
With everything going on, it doesn't seem like Bruce or Alfred would have time (or even enough knowledge) to build such a large scale version of the device by themselves. Was there someone else involved in its construction?

A: Yes, the gentleman (and perhaps ladies) that work in the R&D department. Lucius Fox didn't build Batman's arsenal single handed. Instead, he had merely gathered up the results of the various classified contracts they had won from the government during Wayne Enterprise's time as a defense contractor (established in Rises). WE is basically under the sole control of Bruce Wayne at the time (established in Begins) and Bruce could easily tell a working group "hey, you guys are reporting directly to me and this is what you are working on".  Imagine Apple level secrecy with no shareholders to answer to. The person that would normally blow the whistle on that is Lucius himself, and he was personally assured that it was intentional and asked to stay out of it by his boss.
As for the technology itself, I'm sure that Bruce and Lucius have vetted the guys in those positions fully and wrapping them up in nondisclosure agreements. As I think about it, it's entirely possible that the guys who built those things think that Bruce Wayne is supplying Batman, but are so good at keeping their mouths shut they never mention it. It could even be a sort of open secret in certain departments, made up of people who are smarter than the outside auditor in TDK. Bruce isn't Tony Stark and he has no problem with finding trusted people to help him in his work.
UPDATE
We actually see a few of these wrench turners at the end of Rises, when Lucius Fox is examining the Bat.

A: It's been a few years since I watched this... but as far as I understand it's a software product covertly loaded onto all the phones that WE sells or provides service to. As such, the scale of the system is dependent on loading it onto new phones and doing so on 500,000 phones is as simple as doing so on 10 of them. A relatively small team of software developers and engineers could pull this off, perhaps numbering as few as two dozen individuals.


text:
Q: TypeScript typing for function that transforms an object whose values are functions? How would I type the following transformer function?
class MyClass {
  public id: string = ''
}

const instance = new MyClass()

function transformer(funcs) {
  return Object.fromEntries(
    Object.entries(funcs)
     .map(([key, func]) => [key, func.bind(instance)])
  )
}

The crux of my conundrum: More than just passing muster with the linter and compiler, I want intelligent typing for this, such that passing in an object with various string keys bonded to function values (each which expect a this arg of type MyClass) gets transformed such that the output is identical to the input except that it's had its requisite this param "burnt-in," and this is known to the editor/linter/compiler.
In fact, I can't even solve for the simpler solitary case, a function that takes a single param of a function needing a this of type MyClass, along with any number of additional params, and a certain return type… and it spits back a function that's typed identically, except its this has been "burnt-in."
function transform(fn) {
  return fn.bind(new MyClass())
}

Even partial answers or further insight would be helpful here! I'd think that we'd need some clever and deep use of generics here, but don't even exactly know where to start. And any answers that can point to further documentation or reference material on the concepts used are especially appreciated!

A: You can do this via using mapped types and a conditional type to strip the this param.  I also modified your transformer function to be generic on the instance but still require that the function's this argument is the type of the instance provided to avoid code dupe later on.  Here is my solution:
class MyClass {
  public id: string = ''
}

const instance = new MyClass()

type StripThisParam<T extends (...args: any[]) => any> =
    T extends (this: any, ...params: infer $RestParams) => any
        ? (...args: $RestParams) => ReturnType<T>
        : T;

function transformer<
    I,
    T extends Record<string, (this: I, ...otherArgs: any[]) => any>
>(instance: I, funcs: T): { [K in keyof T]: StripThisParam<T[K]> } {
  return Object.fromEntries(
    Object.entries(funcs)
     .map(([key, func]) => [key, func.bind(instance)])
  ) as any;
}

const foo = transformer(instance, {
    bar(this: MyClass, name: string, age: number) {
        console.log(this.id);
    }
});

foo.bar("hey", 23);

TypeScript Playground Link

A: A function type can include the type of this inside the function. For example:
const f: (this: MyClass, x: number) => string =
  function(this: MyClass, x: number): string { /* ... */}

There's a builtin utility type OmitThisParameter that can remove or 'burn in' this this parameter:
/**
 * Extracts the type of the 'this' parameter of a function type,
 * or 'unknown' if the function type has no 'this' parameter.
 */
type ThisParameterType<T> = T extends (this: infer U, ...args: never) => any
  ? U
  : unknown

/**
 * Removes the 'this' parameter from a function type.
 */
type OmitThisParameter<T> = unknown extends ThisParameterType<T>
  ? T
  : T extends (...args: infer A) => infer R ? (...args: A) => R : T

You can type transform and transformer like this:
type MyClassFn = (this: MyClass, ...args: never[]) => unknown

function transform<F extends MyClassFn>(fn: F): OmitThisParameter<F> {
  // requires a type cast here: fn.bind doesn't seem to have an overload
  // for a generic number of parameters with possibly different types
  return (fn.bind as (thisArg: MyClass) => OmitThisParameter<F>)(instance)
}

function transformer<T extends Record<string, MyClassFn>>(
  funcs: T
): {[K in keyof T]: OmitThisParameter<T[K]>} {
  return Object.fromEntries(
    Object.entries(funcs)
     .map(([key, func]) => [key, func.bind(instance)])
  ) as {[K in keyof T]: OmitThisParameter<T[K]>}
}

// Usage
declare const f1: (this: MyClass, x: number, y: string) => number
declare const f2: (this: MyClass, x: number, y: boolean) => string
declare const f3: (this: MyClass) => void

// (x: number, y: string) => number
transform(f1)

// (x: number, y: boolean) => string
transform(f2)

// () => void
transform(f3)

// {
//   f1: (x: number, y: string) => number
//   f2: (x: number, y: boolean) => string
//   f3: () => void
// }
transformer({f1, f2, f3})

Playground link


text: Q: Mini HDMI female - is one pin supposed to be shorter? I have a Raspberry Pi Zero with Mini HDMI output. I acts kinda weirdly - it does work with a TV with HDMI input, but when plugged into a monitor with DVI input (with an appropriate HDMI>DVI cable) it makes the monitor turn off (yes, you're reading that right - Pi is still running, but the monitor turns off and can't be turned back on until I unplug the Pi, as if it was shorting something). I noticed that one of the pins in the female HDMI connector of the Pi is shorter than others - 18th, to be specific. Is it supposed to be that way, or do I have a defective unit? I wasn't able to find any high resolution image of the connector to be able to determine that by myself, so I would appreciate some help.


text:
Q: Elementary Properties of Groups Let $G$
  be a group and $g,h\in G$
  two elements. I need to prove that the equation $xg=h$
  has a unique solution.
Applying $g^{-1}$
  to both sides of the equation we get : $(xg)g^{-1}=hg^{-1}$
If I consider the Right Hand Side of the equation:
$$(xg)g^{-1}=x(gg^{-1})=x\cdot e=x$$
Now $x=hg^{-1}$
  which makes me conclude that $xg=h$
  has a unique solution. Can anyone correct me please!!!

A: This is 100% correct.  It is an application of the cancellation laws.

A: Your answer is correct, as you argued:
\begin{align}
xg = h &\iff (xg) g^{-1} = h g^{-1} \\
       &\iff x = h g^{-1}.
\end{align}
Hence, as you say, $ x = h g^{-1} $ solves the equation $ xg = h $.
But be sure to establish that while you found "a" solution to the equation, the solution you found must in fact be the unique solution and why this is so:
$x = hg^{-1}$ is the unique solution to the equation $xg = h$ because $h, g \in G$ and $g^{-1}\in G$ is the unique inverse of $g \in G$, by definition of the fact that $G$ is a group, and each element in a group has a unique inverse within the group. You need only appeal to the definition of the inverse of a group element and its uniqueness.
So there is no other element $j\neq g^{-1}$ such that $x = hj$ is a solution, else $j$ would also necessarily be the inverse of $g$ which is impossible, as the inverse of an element in a group is unique.
In short, it's a minor point, but nonetheless it's worth stating at the conclusion of your argument that the uniqueness of the solution follows from the uniqueness of the inverse of $g$.

A: After much thought, I have decided to make significant revisions to my original post.

Firstly, let us try to recreate Timoci's thought process.

*

*As required by the group axioms, $ g $ has an inverse.

*Without further knowledge of group theory, it is unclear if $ g $ has only one inverse or has many inverses. Whatever the case is, just fix an inverse and denote it by $ g^{-1} $.

*Multiply both terms in the equation $ xg = h $ on the right by $ g^{-1} $ to obtain $ x = h g^{-1} $.

*Verify that $ x = h g^{-1} $ is indeed a solution to the equation.
Timoci's own argument settles the existential part of his problem by furnishing a solution. Concerning the uniqueness of this solution, I would like to make the following point: By fixing an inverse $ g^{-1} $ of $ g $ in the second step, Timoci actually proves that any solution must equal $ h g^{-1} $. Hence, we do not need to assume that $ g $ has a unique inverse in order to prove that the solution is unique. Indeed, we only need to assume that $ g $ possesses at least one inverse. A more formal argument is presented below.

Suppose that $ x_{1} $ and $ x_{2} $ are solutions to the equation $ xg = h $. Then $ x_{1} g = x_{2} g = h $. Pick any inverse of $ g $ (an inverse exists, as stipulated by the group axioms) and denote it by $ g^{-1} $. Apply $ g^{-1} $ to both terms in the equation $ x_{1} g = x_{2} g $ on the right to obtain $ x_{1} = x_{2} $. Therefore, all solutions are identical.

This argument is a demonstration of the phenomenon of group cancellation, so what I have done here is simply an elaboration of ncmathsadist's solution. With due respect to the other contributors to this thread, we can also solve the problem by translating the assumption that there exist two different solutions into the contradictory statement that $ g $ has two different inverses. However, a satisfactory explanation does not necessarily require prior knowledge of the uniqueness-of-inverse result.


text:
Q: Convenience method for parsing a signed cookie in Express/Connect? Using node.js with Express. This question also pertains to Connect since that's the Express sub-component in question.
I receive a signed cookie from the client over socket.io. Then I take the value of it which is in this format:
s:sessionID.signature
Currently to validate this I had to manually require the cookie-signature module and use its unsign method, which requires me to .slice(2) the s: off of this string, and just feels kludgy.
Is there a convenience method for this? I feel like I ought to be able to just do something like:
mySessionID = express.unsignCookie(thisCookie, forThisSessionIDKey, withThisSecret);
But no such method exists... am I missing something?
Oh, BTW, I can't access res/req due to being in socket.io... Which is why I'm having to pass the session ID over from the client's cookie in the first place...

A: Here was the solution I ultimately found. Inside socket.js:
var parseSignedCookie = connect.utils.parseSignedCookie;

...

socket.on('taste:cookie', function (data, callback) {
   var sid = data.sid;
   sid = parseSignedCookie(sid['connect.sid'], "mySecret");


text:
Q: Bootstrap grid displays columns as rows I have bootstrap grid

Column 1

Column 2

Column 3

{{Item.Field1}

{{Item.Field2}}

{{Item.Field3}}

It should display a 3-column grid, instead the columns are displayed as rows. What am I doing wrong?

A: So your first row is the like the "header" and the next row are the records.  Your header is 1-2-1 but your records are 2-4-6 => it won't line up.  To keep it from stacking even on small screens you can do col-xs-x instead.

Column 1

Column 2

Column 3

{{Item.Field1}

{{Item.Field2}}

{{Item.Field3}}

A: I'm assuming you want them to always line up. Bet way to do that will be this:

Column 1

        {{Item.Field1}}

Column 2

        {{Item.Field2}}

Column 3

        {{Item.Field3}}

Alternatively, you can replace the br and wrap the elements in divs and display: block;
Working example here:
http://www.bootply.com/tb10AKqzM1

A: Having put in the code myself, it actually does work. It will put in rows when the viewport size is below the small viewing size (so xs, extra small size). If you want to view it on all viewing sizes then you would have to add xs instead of s to all your classes.


text:
Q: Implementing nested layout using Bootstrap 3 I am trying to implement recursive layout using Bootstrap 3 but width of cell are reducing every time I put it in a container/row.

Example 1:

[SIDEBAR]

Cell Outer

Cell Outer

Cell Outer

Cell Outer

Example 2:

                [SIDEBAR]

Cell In

Cell In

Cell In

Cell In

Cell In

Cell In

Cell In

Cell In

http://jsfiddle.net/firozansari/jXt69/3/
In example 1, "Cell Outer" has proper widths but in example 2, "Cell In" widths are reduced because of parent row.
I am trying to implement layout which is something like this:

A: can you please try the updated html?

CELL

CELL

SIDEBAR

CELL

CELL

CELL

CELL

CELL

CELL

CELL

CELL

CELL

CELL

CELL

CELL

CELL

CELL

CELL

CELL


text:
Q: How do you inflate views outside of fragments and activities without leaking context? I have a view that is not a fragment or activity, it is a view that is used inside of a fragment.
Inside of the view, I inflate like this
   private val binding = ViewVideoPlayerBinding.inflate(LayoutInflater.from(context), this)
But Android studio tells me Leaking 'this' in constructor of non-final class VideoPlayerView
I looked at Google's guide for viewbinding, and I only saw them mention fragments and activities. What is the best practice these days for inflating these views out leaking the context?


text:
Q: What is the Proper Way to Share Credit on Script Authoring and Editing? In my scripting exploits I often check to see if a script has been written previously before I begin from scratch.  Often I can at least find some of what I need through google or other means.  I then adapt what I find to my needs and put it into production.  As a best practice, I comment my code and include author information (I'm not a fan of plagiarizing).  However there becomes the question of how and when it's appropriate to add/change that author designation.  I'll use a sample script from Ed Wilson off his blog for reference:
Function Get-OutlookCalendar {
    <#
   .Synopsis
    This function returns appointment items from default Outlook profile
   .Description
    This function returns appointment items from default Outlook profile. It
    uses the Outlook interop assembly to use the olFolderCalendar enumeration.
    It creates a custom object consisting of Subject, Start, Duration, Location
    for each appointment item.
   .Example
    Get-OutlookCalendar |
    where-object { $_.start -gt [datetime]"5/10/2011" -AND $_.start -lt `
    [datetime]"5/17/2011" } | sort-object Duration
    Displays subject, start, duration and location for all appointments that
    occur between 5/10/11 and 5/17/11 and sorts by duration of the appointment.
    The sort is shortest appointment on top.
   .Notes
    NAME:  Get-OutlookCalendar
    AUTHOR: ed wilson, msft
    LASTEDIT: 05/10/2011 08:36:42
    KEYWORDS: Microsoft Outlook, Office
    HSG: HSG-05-24-2011
   .Link
     Http://www.ScriptingGuys.com/blog
    #Requires -Version 2.0
    #>

    Add-Type -AssemblyName "Microsoft.Office.Interop.Outlook" | Out-Null
    $olFolders = "Microsoft.Office.Interop.Outlook.OlDefaultFolders" -as [type]
    $outlook = New-Object -ComObject Outlook.Application
    $namespace = $outlook.GetNameSpace("MAPI")
    $folder = $namespace.getDefaultFolder($olFolders::olFolderCalendar)
    $folder.items |
        Select-Object -Property Subject,Start,Duration,Location
}

I view the author field as the point of contact for that script as it's the person who wrote it and understands it.  Is there a general rule of thumb as to how much a script is changed before it no longer makes sense to list the original author?  Or are they always the author and then you're an editor?
In the case of the latter, what's the appropriate way to designate that?  Is it that you add a line under Author labeled "Editor" and change the last edit label?  How exactly is the right way to document your contributions?  Is there a documented best practice?

A: I generally have myself as the author and include my (work) contact information, seeing as how comments are for internal consumption, and I would be the most useful point of contact to anyone reading the comments.
I also generally place an "adapted from" field or section in there where I list where and from whom I grabbed any code snippets.  It's a lot less about plagiarism (these people provided their code online for free, they expect people to copy it) and a lot more about being able to find the resources again if needed.  My bosses don't care even a little about "credit" for scripts - I could write it from scratch or copy-pasta the whole thing, as long as it works... and I suspect the same is true of most people in IT.

A: Assuming that you're allowed to use the code for what you intend to use it for and are complying with all/any laws and restrictions....
You'll have to figure that out for yourself and the intended audience. If it's for something that you're running as a sysadmin at your company, who cares? You credit yourself and the source(s), doesn't matter who's the author and who's the editor.
For something distributed to clients/the world, you should probably be the main contact anyway if someone has support questions, since it matters how it works in the context that you've distributed it.
Regarding author-vs-editor, that's a fairly limiting way of looking at it. Think of something like the Linux kernel - Linus Torvalds is the original author, but there's a whole lot of people who've contributed.
(I voted to move to SO, because this is really a programming question.)


text:
Q: How do I use radio buttons groups in javafx? I need to make a group of 2 radio buttons and then retrieve the value of the selected one.

A: Simply use a ToggleGroup
RadioButton radioButton1 = ...
RadioButton radioButton2 = ...

// TODO: add RadioButtons to scene

ToggleGroup toggleGroup = new ToggleGroup();

radioButton1.setToggleGroup(toggleGroup);
radioButton2.setToggleGroup(toggleGroup);

// listen to changes in selected toggle
toggleGroup.selectedToggleProperty().addListener((observable, oldVal, newVal) -> System.out.println(newVal + " was selected"));

You can also retrieve the selected radio button from the ToggleGroup using
toggleGroup.getSelectedToggle()

in case you want to do this from the handler of a submit button or something like that...


text:
Q: Why does BlocListener call a state where I removed the whole widget tree? Let me explain, I have two listeners, one in ScreenA, and another in ScreenB, however both have the same state that does different actions, example:
ScreenA
listener : (BuildContext context, StateA state) {

if (state is SuccessB) {
  ... show snackbar
}

if (state is GoToScreenBState) {

  Navigator.of(context).pushReplacementNamed(PageNames.screenB);

}

ScreenB
listener : (BuildContext context, StateA state) {

if (state is SuccessB) {
  ... another code

  BlocProvider.of<ABloc>(context).add(GoToScreenAEvent()); // emit the GoToScreenAState
}

if (state is GoToScreenAState) { // this is the state above

  Navigator.of(context).pushReplacementNamed(
     PageNames.screenA,
     (Route<dynamic> route) => false,
  ); // return to A

}

Now, when I go back to ScreenA, I emit again SuccessB so that the listener of that screen is executed, but also the one of ScreenB is executed, I don't understand why if I already navigue and replace...
Any idea ?


text:
Q: pure javascript equivalent of jquery $("#large_box2_link").click(); I use this small code within a jquery function, it works in every browser apart from ie6 and it just so happens our client only uses ie6,
Can anyone help me translate this into pure javascript?
$("#large_box2_link").click();

A: document.getElementById("large_box2_link").click();


text:
Q: XSLT list item position issue pls check the below code. I am matching the list element and as per the below code the position() function returns correct number of the element with in ul elements i.e 1,2,3 where as if i do the test with position i get only ss,ss,ss . Can anyone let me know where am missing ?
XSL-FO
<xsl:template match="html:li" priority="2">
    <fo:list-item>
       ...
       <xsl:value-of select="position()"/> -- this returns 1,2,3
       <xsl:if test="position() = 1">
        <xsl:text>ss</xsl:text> -- only executes
      </xsl:if>
      <xsl:if test="position() = 2">
        <xsl:text>ssddddd</xsl:text> -- does not only execute
      </xsl:if>
      <xsl:if test="position() = 3">
        <xsl:text>sskkkkkkkkk</xsl:text> -- does not only execute
      </xsl:if>
    </fo:list-item>
</xsl:template

XSL
<xsl:template match="list">
    <xsl:if test="list.item">
        <xsl:variable name="styleAttr">
            <xsl:text>margin-top: 1em;</xsl:text>
        </xsl:variable>

            <xsl:if test="string-length($styleAttr) > 0">
                <xsl:attribute name="style">
                    <xsl:value-of select="$styleAttr"/>
                </xsl:attribute>
            </xsl:if>

                <xsl:apply-templates select="node()[not(self::list)]" />

    </xsl:if>
</xsl:template>

<xsl:template match="list.item" priority="1">

            <xsl:apply-templates />
            <xsl:if test="following-sibling::node()[1][self::list]">
                <xsl:apply-templates select="following-sibling::node()[1]" />
            </xsl:if>

</xsl:template>


text:
Q: Export contacts through API Has anyone got any idea how to export contacts of an Exchange Server 2010 mailbox to a Java-application?
Preferably in Java, or even better in a SOAP-based XML exchange, we're looking for a web-based solution anyway.
Kind regards,
Gerard

A: Have you considered using Exchange Web Services?  There's even source code for a Java API.


text:
Q: MailUp - Contract not signed, please login in console and accept terms of service What are the steps that we do need to follow to resolve error-code
"Contract not signed, please login in console and accept terms of service."
To Get the access token and the refresh token i am using following command
curl -X POST -d "grant_type=password&client_id=MYCLIENTID&client_secret=MYCLIENTSECRET&username=MYUSERNAME&password=MYPASSWORD" /
        https://services.mailup.com/Authorization/OAuth/Token
As mentioned in link:
http://help.mailup.com/display/mailupapi/Authenticating+with+OAuth+v2

A: MailUp has a bug for which, after logging in, in the developer accounts, the popup for accepting the "terms of service" is not displayed. I contacted the support team and they should have solved the problem. This is the case at least for my account.
The command you have copy/pasted from documentation site do not work due to this bug.
So now you just have to log in to the control panel and accept the "terms of service", wait about an hour for their internal cache to be updated, and try to access the API again.


text:
Q: Mocking data using Moq and xunit I am new to unit testing and by following so many articles, I am able to write below unit test but it is not working since there is no relationship between main class and factory class. How to solve this problem? Is it possible to write unit test without changing the structure of my class.
My Class:
public class SomeClass : ISomeClass
        {
            public ServiceClientManager<IScan> scan;

            public SomeClass(Action<String> logMessages)
            {
                this.logMessage = logMessages;
            }

            public void Process(string a, string b, string c)
            {
            if (this.Scan == null)
            {
               ConnectToScan();
            }

            if (status)
            {
                Scan.Proxy.MethodScan(a, b, c);
            }
        }
}

public bool ConnectToScan()
        {
            this.Scan = null;
                NetTcpBinding netTcpBinding = new NetTcpBinding();
                netTcpBinding.MaxBufferSize = int.MaxValue;
                netTcpBinding.MaxReceivedMessageSize = int.MaxValue;
                netTcpBinding.ReaderQuotas.MaxArrayLength = int.MaxValue;
                netTcpBinding.ReaderQuotas.MaxBytesPerRead = int.MaxValue;
                netTcpBinding.ReaderQuotas.MaxDepth = int.MaxValue;
                netTcpBinding.ReaderQuotas.MaxNameTableCharCount = int.MaxValue;
                netTcpBinding.ReaderQuotas.MaxStringContentLength = int.MaxValue;
                netTcpBinding.ReceiveTimeout = TimeSpan.FromMinutes(5);
                netTcpBinding.CloseTimeout = TimeSpan.FromMinutes(5);
                netTcpBinding.OpenTimeout = TimeSpan.FromMinutes(5);
                netTcpBinding.SendTimeout = TimeSpan.FromMinutes(5);
                barcodeScanner = new ServiceClientManager<IScan>(netTcpBinding, new EndpointAddress("net.tcp://localhost/XXXX"));
                return true;
        }

Here, ConnectToScan() will establish the connection to the service and I am using it inside Process method to pass parameters to that service. In order to write unit test for this method, I am trying to mock the service "IScan" and assert that service method is called atleast once.
My unit test:
  private Action<string> _logMessage = msg => Console.WriteLine(msg);

       [Fact]
    public void MethodTest()
    {
        var factoryScanMoq = new Mock<IScan>();
        factoryScanMoq.Setup(x => x.MethodScan("test", "S000", "test2"))
        .Returns(null);

        var mockService = new ServiceClientManager<IScan>(factoryBarcodeScanMoq.Object);

        classObj.process("test", "S000", "test2"); // FactoryScanMoq is not passed here

        classObj.Scan = mockService;

        factoryScanMoq.Verify(x => x.MethodScan("test", "S000", "test2"), Times.Once);
    }

I Know there is no relation between factory Mock and SomeClass but I am not sure how to create a relation since I cannot pass FactoryMoq to SomeClass as a constructor argument.
Thanks in advance


text:
Q: Duplicated item after consulting a View page in angular2 I have an angular2 page that shows off some orders (for restaurants), those orders could be filtered by types (cancelled, in progress,... etc) within checkboxes, By default I'm loading the open and the in progress ones (they are checked by default when refreshing the page):

The problem is that if I have only one open order, if refreshing the page, it will duplicate that order (or in progress), when unchecking and checking any checkbox it will disappear and all stuffs are working smoothly, I couldnt figure out what is the problem.
That is the relevant TS:
The relevant HMTL :

  <md-checkbox [checked]="true" (click)="showOpenOrders(isOpen)">
    {{'open' | translate}}
  </md-checkbox>
  <md-checkbox [checked]="true" (click)="showInProgOrders(isInProg)">
    {{'in_progress' | translate}}
  </md-checkbox>
  <md-checkbox (click)="showCompletedOrders(isCompleted)">{{completedStatus}}
    {{'completed' | translate}}
  </md-checkbox>
  <md-checkbox (click)="showCancelledOrders(isCancelled)">
    {{'cancelled' | translate}}
  </md-checkbox>
  <md-checkbox (click)="showPaidOrders(isPaid)">
    {{'paid' | translate}}
  </md-checkbox>

<app-show-more
  *ngIf="!isOrdersLastPage"
  [label]="'showMoreOrders'"
  (getNextPage)="showMoreOrders($event)"
></app-show-more>

The relevant TS:
export class OrdersListComponent implements AfterContentInit {
  @Input() result: Order[];

  public totalOrders:      number;
  public isOrdersLastPage: boolean;
  public isCompleted:      boolean = false;
  public isOpen:           boolean = false;
  public isInProg:         boolean = false;
  public isCancelled:      boolean = false;
  public isPaid:           boolean = false;
  public status:           string[];

  private selectedName: string;
  private addOption(option: string) {
   this.status.push(option);
  }
  private removeOption(option: string) {
   this.status = this.status.filter(_option => _option !== option);
  }

  constructor(
    private router: UIRouter,
    private pageService:  PageService,
    private orderService: OrderService,
    private coreDataService: CoreDataService,

) {
    this.status = ['open', 'in_progress'];
    this.pageService.getPage().subscribe(
      (data: any): void => this.showMoreOrders(),
      (error: any): void => console.log(`could not load page data from orders home page`, error)
    );
  }

  ngAfterContentInit() {
    this.getOrders();
  }

  showMoreOrders(pageNumber = 0): void {
    let handleLoadOrders, handleLoadOrdersError;
    handleLoadOrdersError = (error: any): void => console.log(`coudn't load more orders`, error);
    handleLoadOrders      = (data: any): void  => {
      this.result           = this.result.concat(data.result);
      this.isOrdersLastPage = data.is_last;
    };
    this.orderService.loadOrders(this.status, pageNumber, this.isPaid).subscribe(
      handleLoadOrders,
      handleLoadOrdersError
    );
  }

  getOrders (): void {
    this.orderService.loadOrders(this.status, 0, this.isPaid).subscribe(
      (data: any): void  => {
      this.result           = data.result;
      this.isOrdersLastPage = data.is_last;
      },
      (error: any): void => console.log(`coudn't load more orders`, error)
    );
  }

  showOpenOrders(isOpen: boolean) {
    if (isOpen) {
      this.addOption('open');
    } else {
      this.removeOption('open');
    }
    this.getOrders();
    this.isOpen = !isOpen;
  }

  showInProgOrders(isInProg: boolean) {
    if (isInProg) {
      this.addOption('in_progress');
    } else {
      this.removeOption('in_progress');
    }
    this.getOrders();
    this.isInProg = !isInProg;
  }

  showCompletedOrders(isCompleted: boolean) {
    if (!isCompleted) {
     this.addOption('completed');
    } else {
      this.removeOption('completed');
    }
    this.getOrders();
    this.isCompleted = !isCompleted;
  }

  showCancelledOrders(isCancelled: boolean) {
    if (!isCancelled) {
     this.addOption('cancelled');
    } else {
      this.removeOption('cancelled');
    }
    this.getOrders();
    this.isCancelled = !isCancelled;
  }

   showPaidOrders(isPaid: boolean) {
    if (!isPaid) {
      this.isPaid = true;
    } else {
      this.isPaid = false;
    }
    this.getOrders();
    this.isPaid = !isPaid;
  }

A: I would say that your problem in 2 requests that you execute on:
1) ngAfterContentInit
ngAfterContentInit() {
    this.getOrders();
}

2) constructor
this.pageService.getPage().subscribe(
    (data: any): void => this.showMoreOrders(),
    (error: any): void => console.log(`could not load page data from orders home page`, error)
);

As in fact you make exact same request twice... Also result is defined as @Input(), so make sure that nothing above doesn't set anything there.


text:
Q: Python ошибка в классах Ребят, подскажите в чем проблема. Пишу адресную книгу по книге Byte of Python.
import pickle

class PhoneBook():
    mybook = {}
    def add_person(self, newcont, new_phone):
        self.newcont = newcont
        self.new_phone = new_phone
        PhoneBook.mybook[self.newcont] = self.new_phone
        f = open('mybook.txt', 'wb')
        pickle.dump(PhoneBook.mybook, f)
        f.close()

При вызове следующего блока (вне класса) выдает ошибку:
newcont = input('Введите имя нового контакта: ')
new_phone = input('Введите телефон этого человека: ')
PhoneBook.add_person(newcont, new_phone)

PhoneBook.add_person(newcont, new_phone)
TypeError: add_person() missing 1 required positional argument: 'new_phone'

A: Ошибка возникает из-за того, что вы пытаетесь вызвать метод экземпляра PhoneBook напрямую из его класса.
Классы в python являются объектами. Каждый класс имеет своё собственное пространство имён. Все переменные и функции которые объявлены в классе находятся в его пространстве имён и могут быть доступны в виде атрибутов объекта класса.
Функции определённые в классе доступны экземплярам класса в виде методов.
У Методов и функций есть 2 важных отличия. Функции не привязаны ни к каким объектам, никакие параметры им не передаются сами собой. Методы всегда привязаны к какому либо объекту (экземпляру), метод всегда получает экземпляр класса в качестве своего первого параметра (обычно его именуют self).
Когда создаётся экземпляр класса все функции определённые в классе становятся его методами.
Пример:
class PhoneBook:
    #код PhoneBook

print( PhoneBook.add_person )
# напечетает что это просто функция
# лежащая в пространстве имен PhoneBook

my_book = PhoneBook()
print( my_book.add_person )
# напишет что это bound метод (не функция!)

my_book.add_person(newcont, new_phone)
# происходит вызов метода (первый параметр будет передан автоматически)

# это эквивалентно следующему вызову
PhoneBook.add_person(my_book, newcont, new_phone)

В вашем коде PhoneBook.add_person(newcont, new_phone) вы вызваете функцию с тремя параметрами, но передаёте ей только 2 параметра. Из-за этого получаете ошибку.


text:
Q: how to be notified of a program execution in linux There is an inotifywait program from inotify-tools, which helps to detect creation, modification, opening and so on of watched files or directories, but there is no distinct "executed" event. I also have tried fileschanged utility, but it seems that although "created" and "modified" events work, "executed" does not. Is there a way to be notified on execution of selected programs or programs in selected directory?
My problem is that although I can monitor "executed" action on binaries with "OPEN" inotify event, I need to compute checksum of that binary so it would be another "OPEN" action and it brings me to infinite recursion. Of course I can use inotifywait in a loop and every time get a single action rather than to use monitor mode, but then there is a chance that some events would be skipped.

A: As far as I know, there is no event in inotify to do what you want exactly. I'm not sure if this is feasible for your situation, but one thing you could try to avoid your recursion problem with "open" is to use the IN_ONESHOT option, then calculate your checksum and re-call inotify on the binary that triggered it in the same script.

A: If you can install sysdig, you can monitor executions based on the command name:
sudo sysdig "proc.name=foobar and evt.type=execve"


text:
Q: How to make a Mesh to move around in BABYLONJS? Hi I have Created a Scene in BABYONJS , I am trying to achieve solor system in BABYONjs here i have made earth self rotate but i have tried to move arround that does not work any Idea ?
My Code
Self Rotate
scene.beforeRender = function () {
        newEarth.rotate(new BABYLON.Vector3(0, 1, 0) , 0.01,
        BABYLON.Space.WORLD);
};

The need is the earth should move arround

A: Here below i have a solution using pivot matrix
currentMesh.setPivotMatrix(BABYLON.Matrix.Translation(70, 0, 0));
   camera.attachControl(canvas, true);
   scene.registerBeforeRender(function () {
        if (currentMesh) {
            currentMesh.rotate(BABYLON.Axis.Y, Math.PI / 64,
              BABYLON.Space.LOCAL);
        }
    });

try this one.


text:
Q: how to export BI report to excel We deployed bi dashboards in our web application using  the performance point service and it enable annonymous acess for users without login they can view.
but when they trying to export it ask authentication , why it asking authentication and how to export report to excel
when i try to export to excel below page opens and asking authentication https://xxx/xxxr/bi/kpi/_layouts/15/PPSWebParts/OfficeExportPage.aspx

A: I'm not sure an Anonymous user have the permission to actually read the data that generates the dashboard. Viewing the dashboard is different than accessing the raw data, and the little SharePoint devil in me tells me that this is correct. You really want users to authenticate before reading data.
That said, you could try to setup the EffectiveUserName property in PerformancePoint Services which override the user-supplied authorization:

If you use a connection string to create the data connection, and the connection string contains an effective user field, the EffectiveUserName feature will override the user-supplied effective user value with the system-supplied value.

Prerequisites are the following:

*

*The PerformancePoint Services application pool account must be an Analysis Services Administrator.

*The EffectiveUserName option in must be enabled in the PerformancePoint Service Application Settings.

*You must select the Per-user Identity option when you create the data source in PerformancePoint Dashboard Designer.

To get this to work you'll need to do the following in the PerformancePoint Service Application:

*

*Click PerformancePoint Service Application Settings.

*Select the Use the EffectiveUserName connection string property instead of Windows delegation check box.

*Click OK.

You probably already have set up access to Analytics Service and connected to the Analysis Services data source from Dashboard Designer.
But again, I would recommend only to allow authenticated users to read (and export) data.
Source: Use EffectiveUserName in PerformancePoint Services (SharePoint Server 2013)


text:
Q: How to find row in SQL which got a specific unicode character We have SQL report builder but we get a error: An error has occured during report processing (rsProcessingAborted).
If I check the ReportServerService log then I see this:
e ERROR: Reporting Services error Microsoft.ReportingServices.Diagnostics.Utilities.RSException: An error has occurred during report processing. ---> Microsoft.ReportingServices.ReportProcessing.ProcessingAbortedException: An error has occurred during report processing. ---> System.Text.EncoderFallbackException: Unable to translate Unicode character \uDB5D at index 389 to specified code page.
   at System.Text.EncoderExceptionFallbackBuffer.Fallback(Char charUnknown, Int32 index)
   at System.Text.EncoderFallbackBuffer.InternalFallback(Char ch, Char*& chars)
   at System.Text.UTF8Encoding.GetByteCount(Char* chars, Int32 count, EncoderNLS baseEncoder)
   at System.Text.UTF8Encoding.GetByteCount(String chars)
   at System.IO.BinaryWriter.Write(String value)
   at Microsoft.ReportingServices.ReportIntermediateFormat.Persistence.PersistenceBinaryWriter.Write(String str, Boolean writeObjType)
   at Microsoft.ReportingServices.ReportIntermediateFormat.Persistence.IntermediateFormatWriter.Write(Object obj, Boolean verify, Boolean assertOnInvalidType)
   at Microsoft.ReportingServices.ReportIntermediateFormat.Persistence.IntermediateFormatWriter.TryWriteSerializable(Object obj)
   at Microsoft.ReportingServices.ReportIntermediateFormat.RecordField.Serialize(IntermediateFormatWriter writer)
   at Microsoft.ReportingServices.ReportIntermediateFormat.Persistence.IntermediateFormatWriter.Write(IPersistable persistableObj, Boolean verify)
   at Microsoft.ReportingServices.ReportIntermediateFormat.Persistence.IntermediateFormatWriter.Write(IPersistable[] array)
   at Microsoft.ReportingServices.ReportIntermediateFormat.RecordRow.Serialize(IntermediateFormatWriter writer)
   at Microsoft.ReportingServices.ReportIntermediateFormat.Persistence.IntermediateFormatWriter.Write(IPersistable persistableObj, Boolean verify)
   at Microsoft.ReportingServices.ReportIntermediateFormat.Persistence.ChunkManager.DataChunkWriter.WriteRecordRow(RecordRow recordRow)
   at Microsoft.ReportingServices.OnDemandProcessing.TablixProcessing.RuntimeOnDemandDataSet.ProcessRow(RecordRow row, Int32 rowNumber)
   at Microsoft.ReportingServices.OnDemandProcessing.RuntimeAtomicDataSet.ProcessRows()
   at Microsoft.ReportingServices.OnDemandProcessing.RuntimeAtomicDataSet.Process()
   at Microsoft.ReportingServices.OnDemandProcessing.RuntimeAtomicDataSet.ProcessConcurrent(Object threadSet)

Probably in a table there is a value with a strange character. Is it also possible to find the correct row which contains the unicode :uDB5D I tried:
SELECT *
  FROM OrderLines
  WHERE OrderLines.ItemDescription LIKE CONCAT('%',UNICODE(0xDB5D),'%')

but this did not give me any results..

A: This seems to work:
DECLARE @test NVARCHAR(50) = 0xDB5D

SELECT @test
WHERE   @test like N'%巛%'

you can test where the 'offending' character is by converting it to binary:
DECLARE @test NVARCHAR(50) = 0xDB5D
SET @test = @test + N'test'
SELECT @test, CONVERT(VARBINARY, @test)
WHERE   @test like N'%巛%'

Results in:
+-------+------------------------+
| 巛test | 0xDB5D7400650073007400 |
+-------+------------------------+

So you can spot the 0xDB5D at the start of the binary string.

A: The unicode conversion is wrong use NCHAR(0xDB5D) like so:
DECLARE @Orders TABLE(ItemDescription NVARCHAR(100))
INSERT INTO @Orders VALUES (N'�')
SELECT * FROM @Orders WHERE ItemDescription LIKE CONCAT(N'%',NCHAR(0xDB5D),N'%')


text:
Q: Display TickMark widget depending on String and boolean value in Dart Need to display icon with checkmark based on a String value that comes dynamically.
Like
this image  is its pending show first widget with tick and rest are blank.
if delivered show with tick and the rest are blank.
Facing problems in creating logic using enums.
Currently, it displays the icons on button clicks
based on four constants which is fine with the widget CheckStatus.
Need to make in a way based on a boolean check if it's true and pending that pending tick widget displayed
and similar with other values.
Here is the complete code for it currently.
import 'package:dotted_border/dotted_border.dart';
import 'package:dotted_line/dotted_line.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:matab/models/order.dart';
import 'package:matab/ui/general_widgets/check_status.dart';
import 'package:matab/ui/pages/styles.dart';

import '../../general_widgets/custom_gradient_button.dart';

class TrackOrder extends StatefulWidget {
  const TrackOrder({Key? key, required this.order}) : super(key: key);
  final Order order;
  @override
  State<TrackOrder> createState() => _TrackOrderState();
}

enum Status { Pending, Confirmed, Shipped, Received }

class _TrackOrderState extends State<TrackOrder> {
  static const darkGreyColor = Colors.grey;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Center(child: Text('Track Order')),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => Get.back(),
        ),
      ),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            const SizedBox(height: 50),
            Text(
              "Order ID:" + widget.order.orderID,
              style: const TextStyle(
                  color: darkGreyColor,
                  fontSize: 18,
                  fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 50),
            const Text('Sat, 12 Mar 2022',
                style: TextStyle(
                    color: darkGreyColor,
                    fontSize: 18,
                    fontWeight: FontWeight.bold)),
            const SizedBox(
              height: 15,
            ),
            Container(
              margin: const EdgeInsets.fromLTRB(15, 0, 0, 0),
              child: const Text('Estimated Time: 07 Days',
                  style: TextStyle(fontSize: 23, fontWeight: FontWeight.bold)),
            ),
            const SizedBox(height: 30),
            SizedBox(
              width: 200,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  OrderStatusBar(title: widget.order.orderStatus, status: true),
                  dottedLine(),
                  OrderStatusBar(
                      title: widget.order.orderStatus, status: false),
                  dottedLine(),
                  OrderStatusBar(
                      title: widget.order.orderStatus, status: false),
                  dottedLine(),
                  OrderStatusBar(
                      title: widget.order.orderStatus, status: false),
                ],
              ),
            ),
            const SizedBox(
              height: 40,
            ),
            Container(
              margin: const EdgeInsets.fromLTRB(15, 0, 0, 0),
              child: const Text('Shipping Address',
                  style: TextStyle(fontSize: 23, fontWeight: FontWeight.bold)),
            ),
            Center(
              child: Text(widget.order.deliveryAddress.address,
                  style: const TextStyle(
                      color: Colors.grey,
                      fontSize: 18,
                      fontWeight: FontWeight.bold)),
            ),
            Center(
              child: Padding(
                padding: const EdgeInsets.all(
                  50.0,
                ),
                child: CustomGradientButton(
                    buttonText: "Track Order".tr, buttonFunction: () => {}),
              ),
            ),
            Center(
              child: Padding(
                padding: const EdgeInsets.only(top: 18.0),
                child: GestureDetector(
                  child: Text(
                    'Back to Home'.tr,
                    style: TextStyle(
                        color: mainColor,
                        fontSize: 23,
                        fontWeight: FontWeight.bold),
                  ),
                  onTap: () => {
                    Get.off(CheckStatus(
                      order: widget.order,
                    ))
                  },
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}

class OrderStatusBar extends StatefulWidget {
  const OrderStatusBar({Key? key, required this.title, required this.status})
      : super(key: key);
  final String title;
  final bool status;

  @override
  State<OrderStatusBar> createState() => _OrderStatusBarState();
}

class _OrderStatusBarState extends State<OrderStatusBar> {
  @override
  Widget build(BuildContext context) {
    return Directionality(
      textDirection: TextDirection.rtl,
      child: Row(
        children: [
          widget.status ? dottedCircleWithCheckMark() : dottedCircle(),
          const SizedBox(width: 30),
          Text(
            widget.title.tr,
            style: TextStyle(
              fontSize: 20,
              fontWeight: widget.status ? FontWeight.bold : null,
            ),
          ),
        ],
      ),
    );
  }
}

const size = 25.0;
const strokeWidth = 1.0;
const checkedColor = Color.fromRGBO(232, 113, 65, 1);

Widget dottedLine() {
  return Directionality(
    textDirection: TextDirection.rtl,
    child: Align(
      alignment: Alignment.topRight,
      child: Container(
        margin: const EdgeInsets.fromLTRB(0, 0, size / 2, 0),
        child: const Padding(
          padding: EdgeInsets.only(left: 27 / 2),
          child: SizedBox(
            height: size,
            child: DottedLine(
              dashColor: Colors.black,
              direction: Axis.vertical,
              lineLength: size,
              lineThickness: strokeWidth,
              dashLength: 5,
              dashGapLength: 5,
            ),
          ),
        ),
      ),
    ),
  );
}

dottedCircle() {
  return DottedBorder(
      borderType: BorderType.Circle,
      dashPattern: const [5, 5],
      child: Container(
        height: size,
        width: size,
        decoration: const BoxDecoration(shape: BoxShape.circle),
      ));
}

dottedCircleWithCheckMark() {
  return Container(
    height: size + strokeWidth * 2,
    width: size + strokeWidth * 2,
    decoration: const BoxDecoration(
      shape: BoxShape.circle,
      color: checkedColor,
    ),
    child: const Icon(
      Icons.check,
      color: Colors.white,
      size: size / 4 * 3,
    ),
  );
}

// ignore_for_file: constant_identifier_names

class CheckStatus extends StatefulWidget {
  const CheckStatus({Key? key, required this.order}) : super(key: key);
  final Order order;
  @override
  State<CheckStatus> createState() => _CheckStatusState();
}

class _CheckStatusState extends State<CheckStatus> {
  int selectedItemIndex = 0;
  var pending = Status.Pending;
  List<bool> orderStatus = [true,true,true,false];
  @override
  void initState() {
    // TODO: implement initState

    super.initState();

  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          for (int i = 0; i < Status.values.length; i++)
            ElevatedButton(
              onPressed: () {
                selectedItemIndex = i;
                setState(() {});
              },
              child: Text("Order Status ${Status.values[i]}"),
            ),
          Row(
            children: [
              for (int i = 0; i <= selectedItemIndex; i++)
                Container(
                  height: size + strokeWidth * 2,
                  width: size + strokeWidth * 2,
                  decoration: const BoxDecoration(
                    shape: BoxShape.circle,
                    color: checkedColor,
                  ),
                  child: const Icon(
                    Icons.check,
                    color: Colors.white,
                    size: size / 4 * 3,
                  ),
                ),
              ElevatedButton(onPressed: () {}, child: Text("Back"))
            ],
          )
        ],
      ),
    );
  }
}


text:
Q: Interpret java.util.Date I have a system where I through a third party lib gets a date. I know for a fact that the date entered is 1914-08-28 and I don't care for the hours and minutes. I need to deliver this date to the client and it should be formatted like 1914-08-28T00:00.
What I get from the third party lib is a java.util.Date and while debugging I stumpled upon something that to me looked strange.
Take a look at the following image. I have a date that when calling toString() it returns Thu Aug 27 22:00:00 CET 1914, but when you look at the contained cdate it looks like being in Zulu time.

Formatting this with the DateFormat gives me 1914-08-27T00:00:
java.text.DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'00:00");

What I really expected here is that I have a date in Zulu time (1914-08-27T22:00Z) which is equivalent to 1914-08-28T00:00 CET (the following day).
This can be reproduced with the following code.
Calendar instance.set(1914, 7, 28, 22, 0);
instance.setTimeZone(TimeZone.getTimeZone("CET"));
Date d = instance.getTime();

Now d will display CET time and the cdate (visible debugging) will show Zulu time, but they are not different. If the default time zone is used I would expect the CET time to be different than the Zulu time.
What is the explanation for this?

A: A java.util.Date isn't in any particular time zone - it's just an instant in time, which will have different local times around the world.
Internally, it's a number of milliseconds since the Unix epoch, but frankly it could be a different representation... and although we usually think of "the Unix epoch" as 1970-01-01T00:00:00Z, you can equally think of it as 1970-01-01T01:00:00+01:00... they represent the same point in time.
Fundamentally, stop thinking about java.util.Date as being in any time zone - it's not, and toString() always just uses the system default time zone, to the confusion of many developers. Always use a dedicated formatter (e.g. SimpleDateFormat) and specify the time zone you're interested in.
Oh, and ideally move to using java.time or Joda Time, both of which are far superior date/time APIs...


text:
Q: Creating randomly shaped clumps of cells in raster from seeds of 1 cell/pixel I wish to "grow" clumps of cells from seeds within a raster. My base raster is full of 1's and 0's, 1's indicate land and 0's sea/NA areas. From the 1's I wish to select 60 random pixels/cells as my seeds, and then randomly grow a connected clump of a pre-defined no. of pixels/cells limit from that seed. I've heard the technique can be referred to as 'spread dye' but haven't had any luck finding much on it. The seed cell would be turned to a value of 2 and then the next cell chosen from surrounding 1's would be converted to 2 as well. 2's are then unavailable to be converted in future.
Randomly altering raster map of habitat types? does help a bit, as I would also be willing to do this in R as I'm familiar with reading and manipulating GIS data in R. However, what I require is a set of rules to randomly select pixels surrounding an existing clump.
Perhaps someone has done this more basic form of cellular automata in a GIS setting.
Example:
I have a target of 250 cells. I randomly select one cell that has a value of 1. This is turned to a value of 2. Then, one of the neighbours of the seed cell that = 1 is turned to a 2. Then, one of the neighbours of either the cells with a 2 value is selected and turned to a 2. This would continue until a continuous shape numbering 250 cells is reached.
Based on @whuber's great answer, I have a few questions about the code:

*

*How do I get allocate the values of the grown cells to just a '2'
rather than variable values which represent the order in which they
were created?

*I need to create 60 clumps of cells within my area of '1's.
I have devised ways to pick random starting positions but how do I make it all work within a loop using the expand function which you wrote about?

Can you suggest a way to create 60 clumps which don't clash with each other and are contained within the same final matrix?
Further Explanation of Problem
Each clump of cells will represent a protected area of a defined size e.g. 250 cells. Each area needs to start on & grow into cells with a value of 1 as this represents land and avoid cells with a value of 0, as this represents sea. I need to iterate this 1000 times with 60 protected areas in each iteration to create a null model, showing what distributions of these areas will be by chance. For this reason, the total count of cells across all 60 areas will need to be identical in each of the 1000 iterations so they are comparable. Therefore, it's ok if the areas touch, but if there is a collision, then ideally the clump would grow in another available direction until the target of 250 is reached. Future modifications to this process will involve varying the size of each of the 60 areas and potentially the shape although I understand this would be difficult.
Once each of these 1000 protected area networks are created, they will be used as a mask against other raster data such as biodiversity measures to see (a) whether they intersect particular species ranges and (b) what % of particular species ranges these random networks of protected areas cover.

A: Without ever having performed your operation, and no time to spare for play, I can only add these two links to your list:
Find the Nearest Raster Cell Value Based on a Vector Point (The first answer (with 4 votes) is what intrigued me).
Also: would Hawth's Gridspread help?

A: I will offer an R solution that is coded in a slightly non-R way to illustrate how it might be approached on other platforms.
The concern in R (as well as some other platforms, especially those that favor a functional programming style) is that constantly updating a large array can be very expensive.  Instead, then, this algorithm maintains its own private data structure in which (a) all the cells that have been filled so far are listed and (b) all the cells that are available to be chosen (around the perimeter of the filled cells) are listed.  Although manipulating this data structure is less efficient than directly indexing into an array, by keeping the modified data to a small size, it will likely take much less computation time.  (No effort has been made to optimize it for R, either.  Pre-allocation of the state vectors ought to save some execution time, if you prefer to keep working within R.)
The code is commented and should be straightforward to read.  To make the algorithm as complete as possible, it makes no use of any add-ons except at the end to plot the result.  The only tricky part is that for efficiency and simplicity it prefers to index into the 2D grids by using 1D indexes.  A conversion happens in the neighbors function, which needs the 2D indexing in order to figure out what the accessible neighbors of a cell might be and then converts them into the 1D index.  This conversion is standard, so I won't comment on it further except to point out that in other GIS platforms you might want to reverse the roles of column and row indexes.  (In R, row indexes change before the column indexes do.)
To illustrate, this code takes a grid x representing land and a river-like feature of inaccessible points, starts at a specific location (5, 21) in that grid (near the lower bend of the river) and expands it randomly to cover 250 points.  Total timing is 0.03 seconds.  (When the size of the array is increased by a factor of 10,000 to 3000 rows by 5000 columns, the timing goes up only to 0.09 seconds--a factor of only 3 or so--demonstrating the scalability of this algorithm.)  Instead of just outputting a grid of 0's, 1's, and 2's, it outputs the sequence with which the new cells were allocated.  On the figure the earliest cells are green, graduating through golds into salmon colors.

It should be evident that an eight-point neighborhood of each cell is being used. For other neighborhoods, simply modify the nbrhood value near the beginning of expand: it is a list of index offsets relative to any given cell.  For instance, a "D4" neighborhood could be specified as matrix(c(-1,0, 1,0, 0,-1, 0,1), nrow=2).
It is also apparent that this method of spreading has its problems: it leaves holes behind.  If that is not what was intended, there are various ways to fix this problem.  For instance, keep the available cells in a queue so that the earliest cells found are also the earliest ones filled up.  Some randomization can still be applied, but the available cells will no longer be chosen with uniform (equal) probabilities.  Another, more complicated, way would be to select available cells with probabilities that depend on how many filled neighbors they have.  Once a cell becomes surrounded, you can make its chance of selection so high that few holes would be left unfilled.
I will finish by commenting that this is not quite a cellular automaton (CA), which would not proceed cell by cell, but instead would update whole swathes of cells in each generation.  The difference is subtle: with the CA, the selection probabilities for cells would not be uniform.
#
# Expand a patch randomly within indicator array `x` (1=unoccupied) by
# `n.size` cells beginning at index `start`.
#
expand <- function(x, n.size, start) {
  if (x[start] != 1) stop("Attempting to begin on an unoccupied cell")
  n.rows <- dim(x)[1]
  n.cols <- dim(x)[2]
  nbrhood <- matrix(c(-1,-1, -1,0, -1,1, 0,-1, 0,1, 1,-1, 1,0, 1,1), nrow=2)
  #
  # Adjoin one more random cell and update `state`, which records
  # (1) the immediately available cells and (2) already occupied cells.
  #
  grow <- function(state) {
    #
    # Find all available neighbors that lie within the extent of `x` and
    # are unoccupied.
    #
    neighbors <- function(i) {
      n <- c((i-1)%%n.rows+1, floor((i-1)/n.rows+1)) + nbrhood
      n <- n[, n[1,] >= 1 & n[2,] >= 1 & n[1,] <= n.rows & n[2,] <= n.cols,
             drop=FALSE]             # Remain inside the extent of `x`.
      n <- n[1,] + (n[2,]-1)*n.rows  # Convert to *vector* indexes into `x`.
      n <- n[x[n]==1]                # Stick to valid cells in `x`.
      n <- setdiff(n, state$occupied)# Remove any occupied cells.
      return (n)
    }
    #
    # Select one available cell uniformly at random.
    # Return an updated state.
    #
    j <- ceiling(runif(1) * length(state$available))
    i <- state$available[j]
    return(list(index=i,
                available = union(state$available[-j], neighbors(i)),
                occupied = c(state$occupied, i)))
  }
  #
  # Initialize the state.
  # (If `start` is missing, choose a value at random.)
  #
  if(missing(start)) {
    indexes <- 1:(n.rows * n.cols)
    indexes <- indexes[x[indexes]==1]
    start <- sample(indexes, 1)
  }
  if(length(start)==2) start <- start[1] + (start[2]-1)*n.rows
  state <- list(available=start, occupied=c())
  #
  # Grow for as long as possible and as long as needed.
  #
  i <- 1
  indices <- c(NA, n.size)
  while(length(state$available) > 0 && i <= n.size) {
    state <- grow(state)
    indices[i] <- state$index
    i <- i+1
  }
  #
  # Return a grid of generation numbers from 1, 2, ... through n.size.
  #
  indices <- indices[!is.na(indices)]
  y <- matrix(NA, n.rows, n.cols)
  y[indices] <- 1:length(indices)
  return(y)
}
#
# Create an interesting grid `x`.
#
n.rows <- 3000
n.cols <- 5000
x <- matrix(1, n.rows, n.cols)
ij <- sapply(1:n.cols, function(i)
      c(ceiling(n.rows * 0.5 * (1 + exp(-0.5*i/n.cols) * sin(8*i/n.cols))), i))
x[t(ij)] <- 0; x[t(ij - c(1,0))] <- 0; x[t(ij + c(1,0))] <- 0
#
# Expand around a specified location in a random but reproducible way.
#
set.seed(17)
system.time(y <- expand(x, 250, matrix(c(5, 21), 1)))
#
# Plot `y` over `x`.
#
library(raster)
plot(raster(x[n.rows:1,], xmx=n.cols, ymx=n.rows), col=c("#2020a0", "#f0f0f0"))
plot(raster(y[n.rows:1,] , xmx=n.cols, ymx=n.rows),
     col=terrain.colors(255), alpha=.8, add=TRUE)

With slight modifications we may loop over expand to create multiple clusters.  It is advisable to differentiate the clusters by an identifier, which here will run 2, 3, ..., etc.
First, change expand to return (a) NA at the first line if there is an error and (b) the values in indices rather than a matrix y.  (Don't waste time creating a new matrix y with each call.)  With this change made, the looping is easy: choose a random start, try to expand around it, accumulate the cluster indexes in indices if successful, and repeat until done.  A key part of the loop is to limit the number of iterations in case that many contiguous clusters cannot be found: this is done with count.max.
Here is an example where 60 cluster centers are chosen uniformly at random.
size.clusters <- 250
n.clusters <- 60
count.max <- 200
set.seed(17)
system.time({
  n <- n.rows * n.cols
  cells.left <- 1:n
  cells.left[x!=1] <- -1 # Indicates occupancy of cells
  i <- 0
  indices <- c()
  ids <- c()
  while(i < n.clusters && length(cells.left) >= size.clusters && count.max > 0) {
    count.max <- count.max-1
    xy <- sample(cells.left[cells.left > 0], 1)
    cluster <- expand(x, size.clusters, xy)
    if (!is.na(cluster[1]) && length(cluster)==size.clusters) {
      i <- i+1
      ids <- c(ids, rep(i, size.clusters))
      indices <- c(indices, cluster)
      cells.left[indices] <- -1
    }
  }
  y <- matrix(NA, n.rows, n.cols)
  y[indices] <- ids
})
cat(paste(i, "cluster(s) created.", sep=" "))

Here's the result when applied to a 310 by 500 grid (made sufficiently small and coarse for the clusters to be apparent).   It takes two seconds to execute; on a 3100 by 5000 grid (100 times larger) it takes longer (24 seconds) but the timing is scaling reasonably well.  (On other platforms, such as C++, the timing should hardly depend on the grid size.)


text:
Q: Add id to dynamically created DIV I would like to add an ID to the div with the class name="leaflet-control-layers-base". Because this HTML script is automatically generated through an API (Leaflet) when the page is loaded, I cannot add the id within the script.
The reason I am asking is because I have two of these scripts as shown below within my page. I would like to distinct them from each other so that I can refer to them individually. The only difference is that the other script is not located in the "TOCContent" div.
Any ideas how I can add an id using JavaScript or jQuery to the 'leaflet-control-layers-base' class?
Here is my script:

        <form class="leaflet-control-layers-list">

        </form>

A: Try this:
$(".leaflet-control-layers-base").attr("id","your id will go here");

A: Select the element using the combinator selector, to ensure it selects a descendant of #TOCContent, then set the id property.
$('#TOCContent .leaflet-control-layers-base').prop('id', 'someid');

Remember to run this after your API code has rendered the elements on the page, not before. You will probably need to hook up to some sort of complete event on your API, because the basic DOM Ready event will likely fire before the API has rendered the elements.

Side note: it may not be necessary to give the element an ID, since by doing so you need to obtain a reference to the element anyway, which you can store in a variable.
var base = $('#TOCContent .leaflet-control-layers-base');


text:
Q: Python lxml - can't get to parent I have an xml tree that I need to search:
<instance>
    <hostName>hostname1</hostName>
    <port enabled="true">9010</port>
    <metadata>
        <branch>master</branch>
    </metadata>
    <vipAddress>vip.address.com</vipAddress>
</instance>
<instance>
    <hostName>hostname2</hostName>
    <port enabled="true">9011</port>
    <metadata>
        <branch>sub_branch</branch>
    </metadata>
    <vipAddress>vip2.address.com</vipAddress>
</instance>

I am trying to do a search via the text in branch then get the grandparent element and get the vipAddress and port but when I use the code below when I try and print the vipAddress and the port it prints all of them instead of the one I was actually looking for:
branch_name = 'master'
for record in tree.xpath('//branch/text()'):
  if(record == branch_name):
     branch = record.getparent()
     target_environment = branch.xpath('//vipAddress/text()')
     print(target_environment)
     target_port = branch.xpath('//port/text()')

example:
If I was to search for master instead of returning target_environment=vip.address.com and port=9011 it will return target_environment=[vip.address.com, vip2.address.com] and port=[9010,9011]
I am sure I am doing something simple wrong I just can't see what.

A: I'm not the best at working with xml in python, but I do see a few issues:
for record in tree.xpath('//branch/text()'): converts your branch elements to string, which you use further down to compare to branch_name.   Strings do not have a getparent() method, so you may want to remove the text() from the xpath and compare branch_name to record.text
Once your record is an element, calling getparent() twice on record will give you it's grandparent element instance.  I'm sure there's a better way to do this, but it seems to work.
.xpath('//') searches for items matching the query anywhere.  Since you just want the element that's a child of <instance>, branch.xpath('vipAddress/text()') should do.  Same goes for finding the target_port.
Also I think .xpath always returns a list, so even if this all works your port will look like [9011]
Putting it together I get something like:
branch_name = 'master'
for record in tree.xpath('//branch'):
  if(record.text == branch_name):
     branch = record.getparent().getparent()
     target_environment = branch.xpath('vipAddress/text()')
     print(target_environment)
     target_port = branch.xpath('port/text()')
     print(target_port)


text:
Q: Appending Blob To Form Data Throws TypeError: source.on is not a function I am having a weird issue with appending a blob to FormData. According to the docs( https://developer.mozilla.org/en-US/docs/Web/API/FormData/append ), the append function can either be a String or Blob. My code is as such:
const blobFromSync = (...args) =>
  import('node-fetch').then(({ blobFromSync }) => blobFromSync(...args));

let file_location = '/path/to/video/file.mp4';

const file = await  blobFromSync(file_location);

const chunkSize = 40000;

for (let start = 0; start < file.size; start += chunkSize) {
            const chunk = file.slice(start, start + chunkSize + 1)

            const form = new FormData();

            form.append('file', chunk, 'an-id');
}

Console logging the chunk shows it a Blob, but it throws this error:
TypeError: source.on is not a function
    at DelayedStream.create (/Users/xxxxxxxxx/Development/terminal-backend/node_modules/delayed-stream/lib/delayed_stream.js:33:10)
    at CombinedStream.append (/Users/xxxxxxx/Development/terminal-backend/node_modules/combined-stream/lib/combined_stream.js:45:37)
    at FormData.append (/Users/xxxxxxxxx/Development/terminal-backend/node_modules/form-data/lib/form_data.js:75:3)
    at /Users/xxxxxxxxxn/Development/terminal-backend/src/server.js:90:18

What am I overlooking here?

A: The official documentation on MDN is related to WHATWG FormData API standards which says that form.append accepts Blob as the second argument. Beware that it's just a specification (not an implementation).
The implementation that you're using doesn't support Blob as highlighted in this issue. As also mentioned in the doc.
You can, however, create a Buffer out of your Blob using Buffer.from(<blob>) and it should work.
P.S.: Credits to @Kaiido for pointing out the WHATWG specification and finding the github issue.