text:
Q: multiple clients broadcast to server in same port i am building a client server program, and i want to simulate having clients to send to the servers that can connect to each other in the same ipv4 "255.255.255.255" and i have specific ports to work on: the port 30381 must have the servers if its possible. what is the best solution to make this since i want to run the same program multiple times?
i have this in the code but is not working well  it connects same program client-server but not to other programs:
client:
        datagramSocket = new DatagramSocket(30382);
        datagramSocket.setBroadcast(true);
        this.ipDest = InetAddress.getByName("255.255.255.255");

        byte[] data = new byte[512];
        DatagramPacket request = new DatagramPacket(data, data.length,ipDest, 30381);
        datagramSocket.send(request);
        DatagramPacket reply = new DatagramPacket(data, data.length);
        datagramSocket.receive(reply);
        this.ipDest = reply.getAddress();
        // do something with the reply

server:
        this.datagramSocket = new DatagramSocket(null);
        this.datagramSocket.bind(new InetSocketAddress(30381));
        while (true) {
        DatagramPacket request= new DatagramPacket(data, data.length);
        this.datagramSocket.receive(request);
        clientIP = pedido.getAddress();
        clientPort = pedido.getPort();
        System.out.println(clientPort);

        //write list

        DatagramPacket reply= new DatagramPacket(list.getBytes(),list.length(), clientIP, clientPort);
        this.datagramSocket.send(reply);
    }

im sorry if this is question is not very well, im new to this page.


text:
Q: Why don't I have iPhone native look any more? At some point I seem to have a lost the ability to go to native iPhone look in the codenameone emulator. How can I get it back to normal?
I did have two themes in the theme.res file - I've tried deleting them both and creating a new native one called "Theme". I've also commented out all my initialization code in the before call for the Form, but it still looks like this:

A: Codename One migrated to iOS 7 as required by Apple: http://www.codenameone.com/3/post/2014/01/switching-defaults.html http://www.codenameone.com/3/post/2013/10/seven.html
To use the old simulator for the old theme just select Skins->More and select the old iOS 6 skin. You probably shouldn't though since you need to migrate to iOS 7 which most devices have already migrated to.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I get element value by Id in Angular I have to get value of element by Id, I need string value and by selecting state from dropdown list, API returning ID. Now, what I've to do?
My sample code:
ShippingDetails.html
<ion-item lines="none" style="--border-radius: 5px;">
                    <ion-label>State</ion-label>
                    <ion-select value="0" okText="OK" #S (ionChange)="onStateChange(S.value)" cancelText="Cancel"
                      [(ngModel)]="address.state" required interface="popover">
                      <ion-select-option value="0">Select State</ion-select-option>
                      <ion-select-option *ngFor="let item of deliveryStateList" value="{{item.statE_ID}}">{{ item.statE_NAME}}
                      </ion-select-option>
                    </ion-select>
                  </ion-item>

ShippingDetails.ts
  async getDeliveryStateList() {
    const payload = {
      countryId: 1
    };
    this.generalService.getStateList(payload).subscribe(async res => {
      let response = new ApiResponse();
      response = Object.assign(response, res);
      this.deliveryStateList = response.data;
    });
  }

  async getDeliveryCityListList(stateid) {
    const payload = {
      // tslint:disable-next-line:radix
      stateId: parseInt(stateid)
    };
    this.generalService.GetCityListbyState(payload).subscribe(async res => {
      let response = new ApiResponse();
      response = Object.assign(response, res);
      this.deliveryCityList = response.data;
    });
  }

  onStateChange(stateid) {
    this.getDeliveryCityListList(stateid);
  }

A: You're not using ionChange right. Try with:
(ionChange)="onStateChange($event)

And in ts change your method to:
onStateChange(event) {
    this.getDeliveryCityListList(event.detail.value);
}

If you want to make sure the getDeliveryCityListList will get called with a string and not a number, you can do:
this.getDeliveryCityListList(event.detail.value.toString());

or:
this.getDeliveryCityListList(event.detail.value + '');


text:
Q: xml string to class conversion I have string that represents xml serialized class.
I have xsd of this class and I successfully managed to create a class from it.
Now I am looking for a way how to serialize this string to instance of this class.
What is the best way doing so?
Thanks.

A: There are several different serializers in .NET, such as the binary formatter, soap formatter, the XML serializer, etc.  Some of them use XML, some don't.  They have different pro's and cons, but for basic uses, often people just use the XmlSerializer which uses XML to represent the object:
public T DeSerialize<T>(string serializedObject)
{
    XmlSerializer serializer = new XmlSerializer(typeof(T));
    using StringReader reader = new StringReader(serializedObject)
    {
        return (T)serializer.Deserialize(reader);
    }
}


text:
Q: How To fix Error: options.uri is a required argument? I'm trying to make a CORS POST request, but it's giving this error:
Error: options.uri is a required argument
Here's my code:

var express = require('express');
var request = require('request');
var app = express();
var gg = false;
var gg2 = false;
app.use('/', function(req, res, next) {
 var url = req.url.substr(1);
 req.headers = {};
 req.headers['Host'] = "*";
 req.header['Cache-Control'] = 'no-cache';
 req.header['User-Agent'] = 'iPad\r\n';
 req.header['Accept'] = '*/*';
 req.header['Accept-Encoding'] = 'gzip, deflate, sdch, br';
 req.header['Accept-Language'] = 'en-US,en;q=0.8';
 res.header('access-control-allow-origin', '*');
 // console.log(url);
 var proxy = request(url);
 proxy.on('data', function(data) {
  gg = data;
  gg2 = url;
  console.log('Proxy data: url: ' + url + "\n" + data);
 });
 req.pipe(proxy);
 proxy.pipe(res);
});

app.listen(process.env.PORT || 8080);

A:
Error: options.uri is a required argument

This error is possible, if the url you provide turns out to be a falsy value.
  // A URI is needed by this point, emit error if we haven't been able to get one
  if (!self.uri) {
    return self.emit('error', new Error('options.uri is a required argument'))
}

Source code : link
You can log the url and check the value


text:
Q: Extra line bundles from torsors Another math.stackexchange question (here: $\mathbb{G}_m$-torsors and line bundles) goes over a way to construct a line bundle $L$ from a $\mathbb{G}_m$-torsor $T \to B$, by using a decomposition $\mathcal{O}_T = \bigoplus_{n \in \mathbb{Z}} P_n$. $P_1$ is naturally isomorphic (as an $\mathcal{O}_B$-module) to the line bundle $L$ whose everywhere nonzero sections form $T$, while $P_n$ is isomorphic to $L^{\otimes n}$.
I'm interested in extending this to sub-torsors of $T$. Let $G$ be a subgroup of $\mathbb{G}_m$ (with a fixed inclusion), $T \to B$ a $\mathbb{G}_m$-torsor as above, and $S \to B$ a $G$-torsor that lives inside $T$. In a fairly natural way, the decomposition $\mathcal{O}_T = \bigoplus_{n \in \mathbb{Z}} P_n$ can be viewed as turning $\mathcal{O}_T$ into a graded ring, graded by the characters of $\mathbb{G}_m$. I'd like to use a similar construction to break up $\mathcal{O}_S = \bigoplus_{\chi \colon G \to \mathbb{G}_m} P_\chi$, in order to get a line bundle $L^\chi$ for each character of $G$. The character given by the fixed inclusion should give $L$ itself back, and its $n$th power should give $L^{\otimes n}$.
My motivation for this question involves $p$-adic modular forms, and the geometric construction of them as given by Pilloni and others. In this light, I think of sections of $L^{\otimes n}$ as corresponding to functions $f \colon (x \in B, \omega \in L|_x) \mapsto f(x,\omega) \in R$ which are homogeneous of degree $n$, meaning $f(x,\lambda \omega) = \lambda^nf(x,\omega)$. I hope that I can naturally think of sections of $L^\chi$ as corresponding to functions $f \colon (x \in B, \omega \in L|_x) \mapsto f(x,\omega) \in R$ which are homogeneous with character $\chi$, meaning $f(x,\lambda \omega) = \chi(\lambda)f(x,\omega)$. Any insight into how these interact with the above is welcome as well.
EDIT: As an addition, I have a feeling this decomposition I'm looking for might come from the coaction $\mu \colon \mathcal{O}_S \to \mathcal{O}_G \otimes_{\mathcal{O}_B} \mathcal{O}_S$ (as in the linked post from the first paragraph) and a grading by characters on $\mathcal{O}_G$. It seems to work out for $(\mathbb{G}_m)^r$, but I can't prove anything for algebraic groups $G$ where I don't really know what $\mathcal{O}_G$ looks like.


text:
Q: ASP.NET MVC Rich Text Editor Goal
The goal of this wiki entry is to create a comprehensive list of available rich text editors for err... traditional websites.  By traditional we mean anything that isn't asp.net with server controls and viewstate.  Open source and commercial options are both viable for discussion.
Why This Wiki
I have found bits and pieces of user feedback on which editors people like, but a lot of input lacks an equal comparison across the available solutions.
Criteria
Editors should be compared on the following criteria:
(If people suggest more criteria I will be happy to add them if appropriate)

*

*Price

*Browsers supported

*Dependencies on other frameworks

*Support level/developer community
presence

*Number & size of required include
files

*Number of lines for basic
functionality

*Editors visual appearance

*Generated content quality
(POSH/XHTML)

*End user experience

*Known bugs or missing functionality

*Known quirks/general complaints

Please include the following:

*

*The name of the editor

*Version reviewed

*A link to the editor's homepage

Dojo Toolkit
Pending
FreeTextBox 3.2.2
Not valid as it is a server side control
RadEditor 2009 Q1
Not valid as it is a server side control.  I have heard a few people talking about getting the rad suite behave in asp.net mvc, so if someone wants to review this in more detail I will look at not discounting it.
TinyMCE 3.2.4.1
pending
YUI Rich Text Editor
pending

A: FCKEditor
http://www.fckeditor.net/
By and far my favorite because it is 'traditional', degrades gracefully in browsers that can't handle complex javascript, and produces standards compliant code.


text:
Q: How to capture Url change on WP* Webbrowser Control How can i listen the Url changes event on a Phone browser control?
My requirement is page1.html will be loaded on browser by default. On click event of Submit button on page1.html , it will redirected internally to Page2.html with some parameters. So i want to capture those parameters . How can i do this? Is there any AddressChanged event or similar events can be added ?

A: try this:
private void Browser_Navigated(object sender,System.Windows.Navigation.NavigationEventArgs e)
        {
            string uri = e.Uri.OriginalString;
        }

By using Browser_Navigated and Browser_Navigating both events u can get the Uri of current navigation along with all its parameters.

A: There is events Navigated and Navigating, where you can get current Uri in parameters and react accordingly.


text:
Q: RefreshAll function not working on excel when call from a python function on a unsaved excel workbook I want to update all the functions on my current workbook when I am working on it by the press of a button from the ribbon but the refreshAll function does not work.
Following is the refresh_func function mapped to button clicked which run the logic
from win32com.client.gencache import EnsureDispatch
def refresh_func():
    ExcelApp  = EnsureDispatch('Excel.Application')
    ExcelApp.Visible = True
    ExcelWrkbook = ExcelApp.Workbooks(1)
    ExcelWrkbook.RefreshAll()

Specs:
Python 3.8.6 32 bit
Pyxll 5.0.5 32 bit
Microsoft Excel 2016

There can be a situation that the excel file is not saved and the user would like to update the function on his working sheet but does not want to save it. Also, the solution should not force me to save or close a file for the solution to work or refresh the function
I am open to any github package that solves this issue.

A: Hey guys got the solution :
ExcelApp  = EnsureDispatch('Excel.Application')

# Either of the following 3

# this will also work
ExcelApp.CalculateFull()

# this is basically using shortcut keys CTRL+ALT+F9 (CTRL+ALT+SHIFT+F9 this an alternative that also works)
ExcelApp.SendKeys("^%{F9}")

# this will also work
ExcelApp.CalculateFullRebuild()


text:
Q: What is the difference between the Return-into-Libc and ROP attack implementations in the hope-RIPE buffer-overflow benchmark? This question is regarding the hope-RIPE buffer-overflow benchmark.
Platform: gem5 simulator (RISCV).
I noticed that the return-to-libc and ROP attacks in the code do almost the same thing. They call an unreachable function by overflowing a target address with the address of the ret2libc_target() and rop_target(). The only difference is during the payload.overflow_pointer initialization:
case RETURN_INTO_LIBC:
    // JM: simulate ret2libc by invoking mock libc function
    payload.overflow_ptr = &ret2libc_target;
    break;
case RETURN_ORIENTED_PROGRAMMING:
    // skip over the prologue code of rop_target
    // to simulate return-oriented programming gadget
    payload.overflow_ptr = (uintptr_t) &rop_target + 16;
break;

I wanted to know why the overflow_ptr for ROP has a type conversion to uintptr_t and an offset of 16 bytes when in fact both the target functions are of void type and print similar messages when executed. Even the payload building process is the same for both these attacks (just copying the overflow_ptr value at the end of the payload to overflow the target address).
The reason I want to know this is that I am using a RISCV port of gem5 to execute this benchmark and ROP always fails while return-to-libc is mostly successful. Here are the gem5 simulation outputs of similar rop and ret2libc configurations:
RIPE configuration: -t direct -l stack -c funcptrstackvar -i rop -f memcpy -d
gem5 output:
**** REAL SIMULATION ****
info: Entering event queue @ 0.  Starting simulation...
tech: 100
location: 400
code ptr: 301
attack: 202
function: 500
debug info enabled
----------------
Shellcode instructions:
lui t1,  0x00011                     00011337
addi t1, t1, 0x47a                   47a30313
jalr t1                              000300e7
----------------
target_addr == 0x7ffffffffffffc38
buffer == 0x7ffffffffffff800
payload size == 1089
bytes to pad: 1080

overflow_ptr: 0x11526
payload: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA&

panic: panic condition !handled occurred: Page table fault when accessing virtual address 0
Memory Usage: 8495668 KBytes
Program aborted at tick 40075500

RIPE configuration: -t direct -l stack -c funcptrstackvar -i returnintolibc -f memcpy -d
gem5 output:
**** REAL SIMULATION ****
info: Entering event queue @ 0.  Starting simulation...
tech: 100
location: 400
code ptr: 301
attack: 201
function: 500
debug info enabled
----------------
Shellcode instructions:
lui t1,  0x00011                     00011337
addi t1, t1, 0x47a                   47a30313
jalr t1                              000300e7
----------------
target_addr == 0x7ffffffffffffc28
buffer == 0x7ffffffffffff7f0
payload size == 1089
bytes to pad: 1080

overflow_ptr: 0x11494
payload: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA�

Executing attack... success.
Ret2Libc function reached.
Exiting @ tick 42464500 because exiting with last active thread context

The one interesting difference in the two outputs I noticed was the different target address and buffer address values for the same location and target code pointer (which does not make sense because they remain the same between shellcode and returnintolibc):
ROP and Shellcode (for location-stack and target code pointer-funcptrstackvar):
target_addr == 0x7ffffffffffffc38
buffer == 0x7ffffffffffff800

Return-into-Libc (for location--stack and target code pointer--funcptrstackvar):
target_addr == 0x7ffffffffffffc28
buffer == 0x7ffffffffffff7f0

Can someone please help me understand why this is happening and if it is related to the difference in how their overflow pointers are initialized?


text:
Q: C function with pointers in C# I'm currently playing with CppSharp and I generated the bindings for the SDL2 library. It almost works, but I can't get working the event part of the library. In C, you just use the API like this
SDL_Event event;
while(SDL_WaitEvent(&event))
{
    if(e.type = SDL_QUIT)
        exit(0);
}

But in C# with the generated bindings I can't do it:
SDL.SDL_Event e = new SDL.SDL_Event();
while(SDL.SDL_WaitEvent(e))
{
    if(e.Type == (uint)SDL.SDL_EventType.SDL_QUIT)
        System.Environment.Exit(0);
}

It compiles but e.Type is always zero, which is not correct, it's like the C# object never changes internally. Is there a way to let C# pass an SDL.SDL_Event like C does.
For reference, here are the bindings (I would like to not change them, because they're generated by CppSharp):
[SuppressUnmanagedCodeSecurity]
[DllImport("SDL2", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,EntryPoint="SDL_WaitEvent")]
internal static extern int SDL_WaitEvent(global::System.IntPtr @event);

public static int SDL_WaitEvent(global::SDL.SDL_Event @event)
{
    var ____arg0 = @event.__Instance;
    var __arg0 = new global::System.IntPtr(&____arg0);
    var __ret = __Internal.SDL_WaitEvent(__arg0);
    return __ret;
}

How can I get the event loop working in C#?
EDIT: SDL_Event generated struct
public unsafe partial struct SDL_Event
{
    [StructLayout(LayoutKind.Explicit, Size = 56)]
    public partial struct __Internal
    {
        [FieldOffset(0)]
        internal uint type;

        [FieldOffset(0)]
        internal global::SDL.SDL_CommonEvent.__Internal common;

        [FieldOffset(0)]
        internal global::SDL.SDL_WindowEvent.__Internal window;

        [FieldOffset(0)]
        internal global::SDL.SDL_KeyboardEvent.__Internal key;

        [FieldOffset(0)]
        internal global::SDL.SDL_TextEditingEvent.__Internal edit;

        [FieldOffset(0)]
        internal global::SDL.SDL_TextInputEvent.__Internal text;

        [FieldOffset(0)]
        internal global::SDL.SDL_MouseMotionEvent.__Internal motion;

        [FieldOffset(0)]
        internal global::SDL.SDL_MouseButtonEvent.__Internal button;

        [FieldOffset(0)]
        internal global::SDL.SDL_MouseWheelEvent.__Internal wheel;

        [FieldOffset(0)]
        internal global::SDL.SDL_JoyAxisEvent.__Internal jaxis;

        [FieldOffset(0)]
        internal global::SDL.SDL_JoyBallEvent.__Internal jball;

        [FieldOffset(0)]
        internal global::SDL.SDL_JoyHatEvent.__Internal jhat;

        [FieldOffset(0)]
        internal global::SDL.SDL_JoyButtonEvent.__Internal jbutton;

        [FieldOffset(0)]
        internal global::SDL.SDL_JoyDeviceEvent.__Internal jdevice;

        [FieldOffset(0)]
        internal global::SDL.SDL_ControllerAxisEvent.__Internal caxis;

        [FieldOffset(0)]
        internal global::SDL.SDL_ControllerButtonEvent.__Internal cbutton;

        [FieldOffset(0)]
        internal global::SDL.SDL_ControllerDeviceEvent.__Internal cdevice;

        [FieldOffset(0)]
        internal global::SDL.SDL_AudioDeviceEvent.__Internal adevice;

        [FieldOffset(0)]
        internal global::SDL.SDL_QuitEvent.__Internal quit;

        [FieldOffset(0)]
        internal global::SDL.SDL_UserEvent.__Internal user;

        [FieldOffset(0)]
        internal global::SDL.SDL_SysWMEvent.__Internal syswm;

        [FieldOffset(0)]
        internal global::SDL.SDL_TouchFingerEvent.__Internal tfinger;

        [FieldOffset(0)]
        internal global::SDL.SDL_MultiGestureEvent.__Internal mgesture;

        [FieldOffset(0)]
        internal global::SDL.SDL_DollarGestureEvent.__Internal dgesture;

        [FieldOffset(0)]
        internal global::SDL.SDL_DropEvent.__Internal drop;

        [FieldOffset(0)]
        internal fixed byte padding[56];

        [SuppressUnmanagedCodeSecurity]
        [DllImport("SDL", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
            EntryPoint="??0SDL_Event@@QEAA@AEBT0@@Z")]
        internal static extern global::System.IntPtr cctor(global::System.IntPtr instance, global::System.IntPtr _0);
    }


text:
Q: Making a process non-blocking inside a websocket asyncio I am using websocket library in python to communicate with a JS code in front end. Here is a summary of what I am doing. When I receive a message from the client, I call __process_msg, generate some output, and then send back the result to the client. The problem here is that __process_msg is time-consuming. While we are inside the __process_msg, I cannot serve any other requests from the clients. How can I make the __process_msg non-blocking?
def __start_webtool_server(self, server, ephemeral_port):

    log.info("Starting the Webtool server thread on %s:%s" % (server, ephemeral_port))

    graph_gui_thread = Thread(target=self.__start_webtool_server_run,
                              args=[server, ephemeral_port],
                              daemon=True)
    graph_gui_thread.start()
    return graph_gui_thread

def __start_webtool_server_run(self, server, ephemeral_port):

    try:
        asyncio.set_event_loop(asyncio.new_event_loop())
        start_server = websockets.serve(self.__start_webtool_server_async, server, ephemeral_port, max_size=None)
        asyncio.get_event_loop().run_until_complete(start_server)
        asyncio.get_event_loop().run_forever()
    except Exception as E:
        log.error("Error: %s" % E)

async def __start_webtool_server_async(self, websocket, path):

        async for message in websocket:

            await self.__process_msg(message, websocket)

async def __process_msg(self, message, websocket):

    await self.__process_sub_msg(message, websocket)

async def __process_sub_msg(self, message, websocket):

    ### a long blocking processing here ......

    data_to_send = "blablabla"
    await websocket.send(data_to_send)

A: If __process_msg is invoking CPU-bound or otherwise non-async (blocking) code, you should off-load it to a thread pool to avoid halting the event loop while the code is running. The easiest way to do that is to use the run_in_executor event loop method:
async def __process_msg(self, message, websocket):
    #value = long_running_function(args...)
    loop = asyncio.get_event_loop()
    value = await loop.run_in_executor(None, long_running_function, args...)


text:
Q: OpenUp/Basic In Practice I have some confusion understanding the OpenUp/Basic process. It is described as an iterative process consisting of four phases:

*

*Inception,

*Elaboration,

*Construction, and

*Transition.

I am not clear if a single iteration consists of all these phases or if we make several iterations within a single phase and then move to next phase. In the later case, it seems to be impractical but in former case feasibility of project can not be identified.
Is there anyone who has experience implmenting it in the organisation?

A: Open Up is a "modified" version of Rational Unified Process.[RUP][ R is for Rational].
It is customizable  software developemnet process [ Infact you should always customize it to your own needs...You should have AUP where A stands for Anergy :-) ]
At RUP,OpenUP [and probably in your AUP] there are  4 phases.Each phase cosist of "n" iterations. Each iteration ends with "executable" software. But there may exception for this at "Inception".
At Inception you basically check/investigate  business-technological feasibility of software...You ask yourself should we do this, and if we want to do can we able to do it? For some large projects in order to answer those questions you may have to "write some software"...But this is so rare case...
At Elaboration basically you take most risky-hard parts of the system and code it iteratively...So at the end of this phase you will had a "solid" architecture which is proven by most risky-hard part of the system features/requirements...You have "executable architecture"- not  architecture stay just on "document"...
Then comes Construction in which you code relatively lower risk parts iteratively...This takes more time than the other phases generally...
Then  Transition....bla bla bla....
Shortly

*

*Each phase in RUP/OpenUP consiste of several[n] iterations...

*Each iteration generally result with executable code..

*At each iteration you basically do Requirement analysis-
Implementation- Test - and produce "small version" of system which
can be exceuted tested..

*At each iteration you incerement software...add some feature-value

RUP is iterative and incremental software developement process...
To get more undestanding i advice you to read/watch those :

*

*Kruchten, "What Is the Rational Unified Process?" Link

*Kruchten, "A Software Development Process for a Team of One" Link

*Larman,Kruchten,Bittner, "How to Fail with the Rational Unified Process"Link

*IJI Consulting, "Why Iterate? Understanding the Essentials of
Iterative Development" Watch at Youtube

*IJI Consulting, "Are you ready for Iterative Development" Watch at youtube


text:
Q: Kubernetes - How to execute a command inside the .yml file My problem is the following:
I should execute the "envsubst" command from inside a POD, I'm using Kubernetes.
Actually I'm executing the command manually accessing to the POD and then executing it, but I would do it automatically inside my configuration file, which is a .yml file.
I've found some references on the web and I've tried some examples, but the result was always that the POD didn't start correctly, presenting the error CrashBackLoopOff error.
I would execute the following command:
envsubst < /usr/share/nginx/html/env_token.js > /usr/share/nginx/html/env.js
There's the content of my .yml file (not all, just the most relevant part)
spec:
  containers:
  - name: example 1
    image: imagename/docker_console:${deploy.version}
    env:
      - name: PIPPO_ID
        valueFrom:
          secretKeyRef:
            name: pippo-${deploy.env}-secret
            key: accessKey
      - name: PIPPO
        valueFrom:
          secretKeyRef:
            name: pippo-${deploy.env}-secret
            key: secretAccessKey
      - name: ENV
        value: ${deploy.env}
      - name: CREATION_TIMESTAMP
        value: ${deploy.creation_timestamp}
      - name: TEST
        value: ${consoleenv}
    command: ["/bin/sh"]
    args: ["envsubst", "/usr/share/nginx/html/assets/env_token.js /usr/share/nginx/html/assets/env.js"]

The final two rows, "command" and "args", should be written in this way? I've already tried to put the "envsubst" in the command but it didn't work. I've also tried using commas in the args row to separate each parameter, same error.
Do you have some suggestions you know they work for sure?
Thanks


text:
Q: Is co kriging appropriate for interpolation of three spatial co variates? I want to estimate an interpolation model(s) for daily minimum temperature, daily maximum temperature and daily rainfall. I have samples of approximately the same size for all three variables at different locations although for certain days and locations only 1 or 2 of the 3 covariates are sampled . All three variables have some correlation, especially minimum temperature and maximum temperature. I read that co-kriging is especially adequate in cases where:

*

*one wishes to interpolate one variable that is relatively sparsely sampled

*one has available another covariate which is more densely sampled

This is not my case. Rather I have available samples for three covariates and want to interpolate all three. I have the following questions:

*

*Is it better to develop a separate ordinary/universal kriging model for each variable or to develop a co-kriging model for all three.

*I am using days and locations with no missing values to estimate the parameters of the interpolation model , but want to use it to interpolate missing values in different days and locations. Is it possible to do this in cases where:

*

*certain locations have all three variables missing

*certain locations have one o two out of the three variables missing

I am working in R in case there are any special considerations to heed.

A: Yes, it is appropriate. Prediction by kriging can theoretically only get better when you bring in more correlated information, and that is what you do when moving from kriging to co-kriging. In practice, the gain can be disappointing, considering the effort it takes.
There can also be other reasons to favor co-kriging. An example is when you need the correlation of the kriging prediction errors for two or more variables, e.g. because you want to sum them or compute their difference.


text:
Q: Can't get available DrmEngines android I'm using DrmManagerClient to get available DRMengines like this:
DrmManagerClient mDrmManager = new DrmManagerClient(context);
   String[] engines = mDrmManager.getAvailableDrmEngines();

With some devices like huawei or honor, getAvailableDrmEngines returns 0 but the device can support widevine because I tested it with DRM Info App. What did I do wrong, or what did I miss?

A: Probably your device doesn't support the classic DRM apis. Maybe try with the new MediaDrm api.
I haven't tried this myself but what I am expecting is Widevine L1 should return 6 (default) or SECURITY_LEVEL_HW_SECURE_ALL while L3 should report SECURITY_LEVEL_SW_SECURE_DECODE or SECURITY_LEVEL_SW_SECURE_CRYPTO.
The values returned might change but you get the idea.
widevine L3 vs widevine L1:

*

*L1: all content processing and cryptography operations are handled
inside a Trusted Execution Environment (TEE)

*L2: only cryptography
operations are handled inside a TEE

*L3: content processing and
cryptography operations are (intentionally) handled outside of a TEE,
or the device doesn't support a TEE.


text:
Q: Validating date input field in parsley js For some reason, I don't have datepicker for the date input field and I want to allow to enter value in mm/dd/yyyy format only. I've used parsley js for validation.
Somehow, I've managed to validate email, image, digits field and i don't find built in validation method for date.
Is there any parsley rule for the date ?

A: Yes, there is. It's unfortunately not documented but it was added in version 2.7 according to the CHANGELOG
The date parse code is here
It expects YYYY-MM-DD so you could do something like
<input type="text" id="somedate"
       placeholder="YYYY-MM-DD"
       data-parsley-type="date"
       data-parsley-type-message="Date must be YYYY-MM-DD"
       data-parsley-mindate="{{ today|date:'Y-m-d' }}"
       data-parsley-mindate-message="Date must be after today"
       required>


text:
Q: Ionic: Touchstart and Touchend don't trigger on Android I'm using Ionic v3.0 and trying to create a directive that will cover an element with an overlay when it's touched and remove that overlay once the touch ends. So far I wrote this:
import {Directive, ElementRef, HostListener, Renderer2} from '@angular/core';

@Directive({
  selector: '[tappable]' // Attribute selector
})
export class TappableDirective {

  private readonly _overlay;

  constructor(private _elmRef: ElementRef, private _renderer: Renderer2) {
    this._overlay = _renderer.createElement('div');

    this._renderer.setStyle(this._overlay, 'position', 'absolute');
    this._renderer.setStyle(this._overlay, 'width', '100%');
    this._renderer.setStyle(this._overlay, 'height', '100%');
    this._renderer.setStyle(this._overlay, 'background', '#ffffff00');
    this._renderer.setStyle(this._overlay, 'left', '0');
    this._renderer.setStyle(this._overlay, 'top', '0');
    this._renderer.setStyle(this._overlay, 'display', 'block');
    this._renderer.setStyle(this._overlay, 'transition', '0.2s');

    _renderer.appendChild(_elmRef.nativeElement, this._overlay);
  }

  @HostListener('touchstart')
  tapped() {
    this._renderer.setStyle(this._overlay, 'background', '#ffffff22')
  }

  @HostListener('touchend')
  untapped() {
    this._renderer.setStyle(this._overlay, 'background', '#ffffff00')
  }

}

This works just fine when I run my app on an iOS emulator, but it's not the case with Android. It seems that the touchstart and touchend do not get triggered when I interact with the element. Did I miss something here?

A: I figured it out. Looks like changing the opacity using #ffffff00 to #ffffff22 does not work in Android. The way to go around it is by using rgba(255, 255, 255, 0) to rgba(255, 255, 255, 50) or changing the opacity.


text:
Q: How can I draw the plan of one floor of the building using javascript I want to draw 2D floor plan on html page.
I have a data set looks like below.
Dataset
{
  floor:{
    "id" : 2,
     rooms:[
       {
        "id" : 21,
        "x"  : 0.0,
        "y"  : 0.0,
        "height" : 15,
        "weight" : 20
       }
       .
       .
       .
     ]
  }
}

I want to get a plan similar to the image below

And I want to add tooltip when hover on room.

Is there a library you can recommend?

A: No library needed, draw the SVG shapes yourself, it is worth the investment.
Your main SVG elements are:

*

*RECTangles: https://developer.mozilla.org/en-US/docs/Web/SVG/Element/rect

*Groups: https://developer.mozilla.org/en-US/docs/Web/SVG/Element/g
Door openings are white rectangles layered on top.
Alternative is use PATHs

*

*https://developer.mozilla.org/en-US/docs/Web/SVG/Element/path
My advice: Draw 5 RECTangles first, after that learn PATH notation (drawing the same RECT shape)
Overlays are 'mouseover' EventListeners that show/hide (Group)SVG, just like you show/hide HTML Elements with JavaScript
Start with typing SVG in a JSFiddle or CodePen.
If you use VS-Code, add the SVG Preview extension: https://github.com/SimonSiefke/vscode-svg-preview
You will have a first draft within an hour.
Note: Your current dataset does not have/show coordinates, so drawing is all up to you.

A: You'll need more details in your data set. Here's code that produces the image you want... or something like it.

      const dataSet = {
        floor:{
          "id" : 2,
           rooms:[
             {
              "id" : 21,
              "x"  : 0.0,
              "y"  : 0.0,
              "height" : 15,
              "width" : 15,
              "weight": 0.4,
              "gap": 0.8,
              "roomSize": 5,
              "corridor": 2

             }
           ]
        }
      }

      const roomData = dataSet.floor.rooms[0]
      const { id
           , x
           , y
          , height
          , width
          , weight
          , gap
          , roomSize
          , corridor
          } = roomData

      const areaWidth = width - roomSize - 2 * weight
      const areaHeight = roomSize - weight
      const area = areaWidth * areaHeight
      const areas = {
        room1: area
      , room2: area
      , room3: area - weight * areaWidth
      , room4: (roomSize - 2* weight) * (roomSize - 2* weight)
      }

      let html = `<svg
        version="1.1"
        xmlns="http://www.w3.org/2000/svg"
        viewBox="0 0 ${width} ${height}"
        style={style}
      >
         <path
          d="M ${x},${y}
             h ${width - roomSize}
             v ${height - roomSize}
             h ${roomSize}
             v ${roomSize}

             h -${roomSize + 2 * weight}
             v -${weight}
             h ${weight}
             v -${weight}
             h ${weight}
             v ${weight}

             h ${roomSize - weight}
             v -${roomSize - 2 * weight}
             h -${roomSize - weight}
             v ${roomSize - 3 * weight - gap}
             h -${weight}

             v -${height - 3 * weight - gap}
             h -${width - roomSize - 2 * weight}

             v ${roomSize - weight}
             h ${width - roomSize - 2 * weight - corridor}
             v ${ weight}
             h -${width - roomSize - 2 * weight - corridor}

             v ${roomSize - weight}
             h ${width - roomSize - 2 * weight - corridor}
             v ${ weight}
             h -${width - roomSize - 2 * weight - corridor}

             v ${roomSize - 2 * weight}
             h ${width - roomSize - 2 * weight - corridor}
             v ${weight}
             H 0
             z
            "
        />
        <rect
          id="room1"
          x="${weight}"
          y="${weight}"
          width="${width - roomSize - 2 * weight}"
          height="${roomSize - weight}"
          fill="#fee"
        />
        <rect
          id="room2"
          x="${weight}"
          y="${roomSize + weight}"
          width="${width - roomSize - 2 * weight}"
          height="${roomSize - weight}"
          fill="#efe"
        />
        <rect
          id="room3"
          x="${weight}"
          y="${roomSize * 2 + weight}"
          width="${width - roomSize - 2 * weight}"
          height="${roomSize - 2 * weight}"
          fill="#eef"
        />
        <rect
          id="room4"
          x="${width - roomSize}"
          y="${roomSize * 2 + weight}"
          width="${roomSize - weight}"
          height="${roomSize - 2 * weight}"
          fill="#fef"
        />
      </svg>
      `

      const svg = document.createElement("svg")
      svg.innerHTML = html

      document.body.appendChild(svg)

      const showArea = (event) => {
        const id = event.target.id
        const area = Math.round(areas[id])
        console.log("Area " + area + " square feet")
      }

      const rooms = [...document.querySelectorAll("rect")]
      rooms.forEach(room => {
        room.addEventListener("mouseenter", showArea, false)
      })

The room area is shown in the Console rather than as an overlay, so you'll have to modify the code to show it as a tooltip.

A: I think you would need an SVG based solution, because SVGs are efficient when there are user interactions like clicks & mouseovers involved. to ha there are a couple of libraries.
I would recommend Raphael.js
Its been around for a while, its simple to set up and easy to use. There are also a couple of good starter books that help you learn the whole library in a day.
Raphael JS, Raphael JS Starter

A: I think you can use D3.js, although I don't know if it will be an overkill for your usecase. D3.js is an awesome library to create data-driven documents, i.e when you have some custom data, and you want to use that data to manipulate the HTML DOM elements. It also supports dynamic runtime behaviour and animation.

*

*An easy quickstart for d3.js is https://www.dashingd3js.com/svg-basic-shapes-and-d3js.

*Freecodecamp tutorial

*Drawing Rectangle blocks using D3.js - https://bl.ocks.org/romsson/568e166d702b4a464347 (This example is a bit interactive).

*This example shows how to show Tooltips while creating a document with d3.js https://bl.ocks.org/d3noob/a22c42db65eb00d4e369


text:
Q: DataBindig returns wrong onFocusChangeListener to layout I have a login form validation mechanism. There are two TextInputEditTexts for email and password, both being attached to respective onFocusChangeListeners, DataBinding is used to set those, but DataBinding returns wrong listeners.
Here is the form:
<?xml version="1.0" encoding="utf-8"?>
<layout>
    <data>
        <variable
            name="loginViewModel"
            type="com.example.increaseyouriq.ui.forms.LoginFormViewModel" />
    </data>
<LinearLayout
    android:id="@+id/ll_login"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    style="@style/parent.contentLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="26dp">

    <com.google.android.material.card.MaterialCardView
        style="@style/cardOutline"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:padding="16dp">

            <TextView
                style="@style/viewParent.headerText"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/login_title" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:orientation="vertical">

                <com.google.android.material.textfield.TextInputLayout
                    style="@style/textInputStyle"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:hint="@string/enter_email"
                    error="@{loginViewModel.loginForm.emailError}"
                    app:errorEnabled="@{loginViewModel.loginForm.isEmailError()}"
                    app:endIconMode="clear_text">

                    <com.google.android.material.textfield.TextInputEditText
                        android:id="@+id/et_login_email"
                        style="@style/textInputEditext"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        onFocus="@{loginViewModel.onFocusEmailChangeListener}"
                        android:text="@={loginViewModel.loginFields.email}"
                        android:inputType="textNoSuggestions|textEmailAddress" />

                </com.google.android.material.textfield.TextInputLayout>

                <com.google.android.material.textfield.TextInputLayout
                    style="@style/textInputStyle"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="@string/enter_password"
                    error="@{loginViewModel.loginForm.passwordError}"
                    app:errorEnabled="@{loginViewModel.loginForm.isPasswordError()}"
                    app:endIconMode="password_toggle">

                    <com.google.android.material.textfield.TextInputEditText
                        style="@style/textInputEditext"
                        android:id="@+id/et_login_password"
                        onFocus="@{loginViewModel.onFocusPasswordChangeListener}"
                        android:text="@={loginViewModel.loginFields.password}"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:inputType="textPassword" />

                </com.google.android.material.textfield.TextInputLayout>

            </LinearLayout>
        </LinearLayout>
    </com.google.android.material.card.MaterialCardView>

</LinearLayout>
</layout>

Here is my LoginFormViewModel.java:

public class LoginFormViewModel extends ViewModel {
    private static final String LOG_TAG = "LoginFormViewModel";

    private View.OnFocusChangeListener onFocusEmail;
    private View.OnFocusChangeListener onFocusPassword;

    public void init() {
        loginForm = new LoginForm();

        onFocusPassword = (v, hasFocus) -> {
            TextInputEditText et = (TextInputEditText) v;
            MyUtilsApp.showLog(LOG_TAG,
                    String.format("%s password listener attached to :%d", String.valueOf(et.getText()), et.getId()));

            if (et.getText().length() > 0 && !hasFocus) {
                loginForm.isPasswordValid(true);
            }
        };

        onFocusEmail = (v, hasFocus) -> {
            TextInputEditText et = (TextInputEditText) v;

            MyUtilsApp.showLog(LOG_TAG, "email listener attached");

            if (et.getText().length() > 0 && !hasFocus) {
                loginForm.isEmailValid(true);
            }
        };

    }

    public View.OnFocusChangeListener getOnFocusEmailChangeListener() {
        return onFocusEmail;
    }

    public View.OnFocusChangeListener getOnFocusPasswordChangeListener() {
        return onFocusPassword;
    }

    @BindingAdapter("onFocus")
    public static void bindFocusChange(TextInputEditText editText, View.OnFocusChangeListener onFocusChangeListener) {
        if (editText.getOnFocusChangeListener() == null) {
            editText.setOnFocusChangeListener(onFocusChangeListener);
        }
    }

}

Here is my LoginActivity.java:
public class LoginActivity extends AppCompatActivity {

    private static final String LOG_TAG = "LoginActivity";
    ActivityLoginBinding binding;
    private LoginRegisterViewModel loginRegisterViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_login);
        setupBindings(savedInstanceState);

    }

    private void setupBindings(Bundle savedInstanceState) {
        LoginFormViewModel loginFormViewModel = new ViewModelProvider(this).get(LoginFormViewModel.class);

        if(savedInstanceState==null)
            loginFormViewModel.init();

        binding.setLoginViewModel(loginFormViewModel);
        binding.setLifecycleOwner(this);

        loginFormViewModel.getLoginFields().observe(this, loginFields -> {
            Toast.makeText(LoginActivity.this,
                    "Email " + loginFields.getEmail() + ", Password " + loginFields.getPassword(),
                    Toast.LENGTH_SHORT).show();
        });

        binding.inLayoutLogin.btnLoginLogin.setOnClickListener(view -> {
            binding.executePendingBindings();
            loginFormViewModel.getLoginForm().onClick();

        });
    }

}

As evident, I have set both listeners to be of onFocusEmail kind, just because onFocusPassword is being attached to both TextInputEditTexts during runtime.
Here are logs:
com.example.increaseyouriq E/LoginFormViewModel:  password listener attached to :2131296499
com.example.increaseyouriq E/LoginFormViewModel: ttf password listener attached to :2131296499

onFocusEmail is nowhere to be seen, it has been attached during runtime.
for more details on code see here

A: I did some experiments on your code and I believe I found out the underlying reason.
Problem:
Neither of your listeners are attached to your email field (TextInputEditText "et_login_email").
Reason:
The reason is that you have a null check here;
@BindingAdapter("onFocus")
public static void bindFocusChange(TextInputEditText editText, View.OnFocusChangeListener onFocusChangeListener) {
    if (editText.getOnFocusChangeListener() == null) {
        editText.setOnFocusChangeListener(onFocusChangeListener);
    }
}

And your email field has an onFocusChangeListener already which is set by "app:endIconMode="clear_text"" attribute.
<com.google.android.material.textfield.TextInputLayout
    ...
    android:hint="@string/enter_email"
    ..."
    app:endIconMode="clear_text">

You cannot set a listener to the email field because its listener is not null from the begining and the current method (bindFocusChange()) only sets it when it is null.
Solution 1:
Remove your null check when setting the onFocusChangeListeners.
Solution 2:
Utilize data binding library's automatic method selection with less code.
Change your custom attribute's name "onFocus" to "onFocusChangeListener". As the TextInputEditText fields have a matching setter method (setOnFocusChangeListener) for this name, the library can handle this automatically and you can remove your "bindFocusChange(...)" method completely:


text:
Q: Sum of Strings as Numbers I'm trying to solve this exercise from Codewars.
Description:
Given the string representations of two integers, return the string representation of the sum of those integers.
For example: sumStrings('1','2') // => '3'
A string representation of an integer will contain no characters besides the ten numerals "0" to "9".
I have removed the use of BigInteger and BigDecimal in java
Python: your solution need to work with huge numbers (about a milion digits), converting to int will not work.
In Python, all my test cases are OK, but the Execution Timed Out is still showing up. Any hints to make it work, please? What other approach could i adopt?
My current code is down below.
Really appreciate any help!!
def sum_strings(x, y):

    if x == '' and y == '':
        return '0'

    if x == '0' and y == '0':
        return '0'

    if x == '' and y == '0' or x == '0' and y == '':
        return '0'

    listaX = list(x)
    listaY = list(y)

    if len(listaX) - len(listaY) > 0:
        while len(listaY) < len(listaX):
            listaY.insert(0, '0')
    if len(listaY) - len(listaX) > 0:
        while len(listaY) > len(listaX):
            listaX.insert(0, '0')

    for i in range(0, len(listaX)):
        listaX[i] = int(listaX[i])
        listaY[i] = int(listaY[i])

    listaSomas = []
    quociente = 0

    for i in range(len(listaX) - 1, -1, -1):
        soma = listaX[i] + listaY[i] + quociente
        if soma > 9 and i > 0:
            quociente = soma // 10
            listaSomas.insert(0, soma % 10)
        elif soma > 9 and i == 0:
            quociente = soma // 10
            listaSomas.insert(0, soma % 10)
            listaSomas.insert(0, quociente)
        elif soma <= 9:
            listaSomas.insert(0, soma)
            quociente = 0

    if listaSomas[0] == 0:
        listaSomas.remove(listaSomas[0])

    for i in range(0, len(listaSomas)):
        listaSomas[i] = str(listaSomas[i])
    listaSomas = ''.join(listaSomas)

    return listaSomas

#MAIN
print(sum_strings('123', '456'))

A: I saw that link and it clearly says : Python: your solution need to work with huge numbers (about a milion digits), converting to int will not work.
Some improvements I can think of are:
a) Don't insert and remove for each digit. Just append to an resultant list.
b) You don't need to append 0s before processing your strings.
A quick way to code it correctly and this got accepted:
    def sumdigits(c, a=0, b=0):
        s = a + b + c
        if s >= 10:
            c = s // 10
            s = s % 10
        else:
            c = 0
        return s, c

    def sum_strings(x, y):
        i = len(x)
        j = len(y)
        c = 0
        out = []
        while i > 0 and j > 0:
            s, c = sumdigits(c, int(x[i-1]), int(y[j-1]))
            out.append(s)
            i -= 1
            j -= 1

        while i > 0:
            s, c = sumdigits(c, int(x[i-1]))
            out.append(s)
            i -= 1

        while j > 0:
            s, c = sumdigits(c, int(y[j-1]))
            out.append(s)
            j -= 1

        if c > 0:
            out.append(c)

        out = ''.join([str(n) for n in reversed(out)]).lstrip("0")

        if out:
            return out

        return "0"

A: One loop should be enough, in order to sum up each digit of both numbers:
def sum_strings(x, y):
    # remove whitespaces from x and y
    x,y = map(str.strip, (x,y))

    # skip useless inputs
    if (x == '0' and y =='0') or (x == '' and y == ''):
        return "0"

    # determine max string, so we could fill the smaller one with leading 0s
    maxLen = max(len(x), len(y))

    # pad both numbers with 0s and reverse them, so we can sum the digits up
    x = x.zfill(maxLen)[::-1]
    y = y.zfill(maxLen)[::-1]

    r = []
    carryover = 0

    # sum both digits and keep the carryover!
    for i  in range(maxLen):
        carryover, res = str(int(x[i]) + int(y[i]) + int(carryover)).zfill(2)
        r.append(res)
        # add the carryover for the last digit as is!
        if i == maxLen-1:
            r.append(carryover)
    r = "".join(r)[::-1].lstrip("0")
    return r if r else "0"

Out:
print(sum_strings('19', '12'))
>> 31

A: Your code times out because list.insert(0... is slow.  When you insert at the beginning, all the other elements need to be move up one index.
Use .append(...) instead, and reverse the list when you're done.

A: Your code times out because of expensive operations, as I mentioned in my original comment. The main problem is inserting at the start of a list. Look up insert vs append for strings and lists here:
https://wiki.python.org/moin/TimeComplexity
As you can see here, appending to a list or string is O(1) but inserting is O(n) because you have to move the rest of the list around. You do this for every digit, so you have O(n^2) complexity just to store the output.
Instead of the expensive insert-at-front operation, store the results with the much more efficient append operation. Once that's all done, simply reverse the output. String and list support efficient reversal.
What is the time complexity of Python List Reverse?
Since we want to iterate, it makes no sense to write your loops with extra code to pad the lengths. It's already done for you in itertools.
I additionally perform my digit math with ord and chr, although that's a relatively minor time saver.
from itertools import zip_longest

zero = ord('0')
nine = ord('9')

def sum_digits(x, y, carry):
    answer = ord(x) + ord(y) - zero
    if carry:
        answer += 1
        carry = False
    if answer > nine:
        carry = True
        answer = answer - 10
    return chr(answer), carry

def sum_strings(x, y):
    answer = ''
    carry = False
    for a, b in zip_longest(reversed(x), reversed(y), fillvalue='0'):
        c, carry = sum_digits(a, b, carry)
        answer += c
    if carry:
        answer += '1'
    answer = answer.rstrip('0')
    if not answer:
        return '0'
    return ''.join(reversed(answer))


text:
Q: Vector ArrayIndexOutOfBounds I'm having an ArrayIndexOutofBounds exception with the following code.
The exception is thrown at the line where  Node nodeJ = vect.get(j)
but it does not make sense to me since j is definitely smaller than i and  Node nodeI = vect.get(i)  does not throw any exception.
any help is appreciated.

public static Vector join(Vector vect) throws ItemNotFoundException {
    Vector<Node> remain = vect;
    for (int i = 1; i < vect.size(); i++) {
        Node nodeI = vect.get(i);
        for (int j = 0; j < i; j++) {//traverse the nodes before nodeI
            Node nodeJ = vect.get(j);

            if (nodeI.getChild1().getSeq().equals(nodeJ.getSeq())) {
                nodeI.removeChild(nodeJ);
                nodeI.setChild(nodeJ);
                remain.remove(j);
            }
            if (nodeI.getChild2().getSeq().equals(nodeJ.getSeq())) {
                nodeI.removeChild(nodeJ);
                nodeI.setChild(nodeJ);
                remain.remove(j);
            }
        }
    }
    return remain;
}

A: You are removing elements from the same vector you are iterating over, via an alias reference, remain. If you want to use a copy instead, you should have
Vector<Node> remain = new Vector<Node>(vect);

A: What happens if in your inner loop you remove more than i - j Nodes from the vector? You will end up with j > vect.size().
Probably best to change the condition in the second for loop to j < i && j < vect.size(), however I think there is something flawed about an algorithm which involves double-iterating over a collection to remove elements from it while you are iterating over it.

A: You're removing things from vect while you're iterating over it. Are you sure that's what you want to do?
Remember that this line:
Vector<Node> remain = vect;

does not create a copy of vect. Remove something from remain and it'll be removed from vect too, because the two names refer to the same actual object.

A: You should use Iterator. Look to documentation http://java.sun.com/docs/books/tutorial/collections/interfaces/collection.html
You can read:

Note that Iterator.remove is the only safe way to modify a collection during iteration; the behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress.

A: You are removing items from your vector.
Use some logging to output the contents of the vector on each iteration of the inner loop and you'll see what's going on.

A: When you remove an item from the vector (which you do), then the length of the vector changes.  The problem is that the code after the removal has had so many nodes removed that it's now using indexes which are no longer valid.


text:
Q: Proof that under the Axiom of Determinacy every subset of $\mathbb{R}$ is Lebesgue-measurable. I was studying Thomas Jech's proof of the above in his book "The Axiom of Choice" (page 178). The proof starts as follows:
"A non-measurable set has different inner and outer measures. In
fact, given a non-measurable set, one can construct a subset of the interval
$[0, 1]$ with inner measure $0$ and outer measure $1$. Thus to show that every
set is measurable, it suffices to show that for every $X\subseteq [0,1]$, either $X$ contains a subset $U$ of positive measure, or $X$ is disjoint from a set $U\subseteq[0,1]$ of positive measure."
My questions are:

*

*How can one can construct a subset of the interval
$[0, 1]$ with inner measure $0$ and outer measure $1$ and why does this help us here?

*Why does it suffices to just show this? Why will this imply every subset of $\mathbb{R}$ is Lebesgue-measurable?

The definition of Lebesgue-measure Jech's gives is as follows:
The standard way of defining the Lebesgue measure is to define first the outer measure $\lambda^{*}(X)$ of a set $X \subseteq \mathbb{R}^{n}$ as the infimum of all possible sums $\sum\left\{ v(I_k) : k \in \mathbb{N} \right\}$ where $\left\{ I_k : k \in \mathbb{N} \right\}$ is a collection of $n$-dimensional intervals such that $X \subseteq \bigcup_{k=0}^{\infty} I_k$, and $v(I)$ denotes the volume of $I$. For each $X$, $\lambda^{*}(X) \geq 0$ and possibly $= \infty$. A set $X$ is null if $\lambda^{*}(X)=0$.
A set $A \subseteq \mathbb{R}^{n}$ is Lebesgue measurable if for each $X \subseteq \mathbb{R}^{n}$,
\begin{equation*}
\lambda^{*}(X)=\lambda^{*}(X \cap A) + \lambda^{*}(X \enspace \backslash \enspace A)
\end{equation*}
For a measurable set $A$, we write $\lambda(A)$ instead of $\lambda^{*}(A)$ and call $\lambda(A)$ the Lebesgue measure of $A$.
Thanks!


text:
Q: Why doesn't ExpressJS middleware execute synchronously I was reading this tutorial https://blog.safaribooksonline.com/2014/03/10/express-js-middleware-demystified/ and it said that you have to call next() for express to know a function is done executing because it is asynchronous. Why not just eliminate next() and making everything synchronous instead?
(sorry...noob question)

A: Because some (or possibly many) middleware do i/o operations (e.g. querying a database, writing to a log file, buffering large stream inputs, etc), and the way Node scales is by doing async operations to not block the processor while waiting for those things to occur.  It allows a single node process to handle far more concurrent requests than it might otherwise.


text:
Q: html2canvas screenshot of external website I don't have even any idea how to do this and the documentation of html2canvas is not really helpful at this part.
I'm able to make a screenshot of my html with this little piece of code:
target = $('#myDiv');
        html2canvas( target, {
        onrendered: function( canvas ) {
            /* canvas is the actual canvas element,
               to append it to the page call for example
             */
               document.body.appendChild( canvas );
            }
        })

but i want to be able to pass an url and make a screenshot of this page. Like they do in their example page on: http://html2canvas.hertzen.com/screenshots.html
If anyone could give me a hint how to get started with that, I would be really glad.

A: You can't, for security reasons, load just any external URL.  That's why, as they described on the page you linked to, you need to set up a separate server-side script that fetches the page.  You then use that script, either directly or via AJAX, to provide the input for html2canvas.


text:
Q: C++ weird for loop syntax std::string decodeMorse(std::string morseCode) {
    // ToDo: Accept dots, dashes and spaces, return human-readable message
    std::string decoded;
    for( auto p : morseCode ) {
      if( p == '.' )
        decoded += MORSE_CODE[ "." ];
      else if( p == '-' )
        decoded += MORSE_CODE[ "-" ];
    }
    return decoded;
}

This is a code extract from https://www.codewars.com
Can somebody explain what for( auto p : morseCode ) means?
Or perhaps re-write this piece of code in more elaborate way?

A: It iterates over every element in morseCode, starting from the one begin refers to and ending with the one before end. The value of each iterated element is copied into p, whose type is the type of the dereferenced iterator.


text:
Q: How do I get the font 'Myriad Pro' for linux (Ubuntu) I've done some googling on this and I can't seem to find this font for ubuntu. I believe that it's an adobe font.

A: Download Adobe Reader, the font is included.

A: As far as I'm aware, regular truetype fonts can be used on Ubuntu without any problems, so if you find a version of it for Windows, it should probably work for you too.


text:
Q: Grabbing the value of an form row on button click where both have the same className I have multiple rows like the following:
const postsOffCountry = {props.posts.map((post => (<input key={post.rowid} defaultValue={post.lcountry} className={post.ref}
onBlur={(event) => props.variables.setLoadingCountry(event.target.value)}></input>)))}	;

const postsUpdateButton = {props.posts.map((post, i) => (<button key={i} className={post.ref} onClick={(event) => {props.variables.update(event.target.id);}}>Update</button>))}	;

Each row has its own update button. My question would be: Is there a way, where i can grab the Value of the row where the button className is the same as the row, where the button has been pressed.


text:
Q: SAS ERROR from GOPTIONS? I'm writing SAS code and experiencing an error that seems to be caused by SAS generated language in code.  I've been using SAS awhile and never experienced this.  Any help/advice would be appreciated.  I've cut out some of the middle code so this is not so long.
1          ;*';*";*/;quit;run;
2          OPTIONS PAGENO=MIN;
3          %LET _CLIENTTASKLABEL='Program';
4          %LET _CLIENTPROJECTPATH='Z:\ACS\Decision Sciences\Analysis\Code\AAU_Analysis.egp';
5          %LET _CLIENTPROJECTNAME='AAU_Analysis.egp';
6          %LET _SASPROGRAMFILE=;
7
8          ODS _ALL_ CLOSE;
9          OPTIONS DEV=ACTIVEX;
10         FILENAME EGSR TEMP;
11         ODS tagsets.sasreport13(ID=EGSR) FILE=EGSR
12             STYLE=HtmlBlue
13             STYLESHEET=(URL="file:///C:/Program%20Files/SASHome/SASEnterpriseGuide/6.1/Styles/HtmlBlue.css")
14             NOGTITLE
15             NOGFOOTNOTE
16             GPATH=&sasworklocation
17             ENCODING=UTF8
18             options(rolap="on")
19         ;
NOTE: Writing TAGSETS.SASREPORT13(EGSR) Body file: EGSR
20
21         options nomprint nomlogic;
22
23         libname acs 'F:\SAS_data\ACS';
NOTE: Libref ACS was successfully assigned as follows:
      Engine:        V9
      Physical Name: F:\SAS_data\ACS
24         %include 'F:\SAS_data\Lysbet\sas_macro_library.sas';
171
173        %macro transform_survey;
174
175        data acs.aau_data_transformed;
176        set acs.aau_data;
177        length brand $3.;

189        %do i=1 %to 10;
190         antonym_pair=&i;
191         %do j = 1 %to &n;
192             %let val = %scan(&lst, &j);
193             brand=&val;
194             suppress_flag1=Q12&val.Flag1;
195             suppress_flag2=Q12&val.Flag2;
196             score=Q_12&val._&i;
197             output;
198         %end;
199         brand='ACS';
200         score=Q_9_&i;
201         output;
202        %end;
205        %mend;
206        %transform_survey;
207
208        %LET _CLIENTTASKLABEL=;
209        %LET _CLIENTPROJECTPATH=;
210        %LET _CLIENTPROJECTNAME=;
211        %LET _SASPROGRAMFILE=;
212
213        ;*';*";*/;quit;run;
                 ____
                 180

ERROR 180-322: Statement is not valid or it is used out of proper order.

A: That means somewhere (probably in the included macro library, or in previously submitted code) you have an unmatched quote (or unmatched %macro/%mend or other similar pair, but it looks like " if you have things lined up correctly).

A: Thanks for all input but classic case of user error.  I forgot the run statement for the data step in my macro.  I knew it was going to end up being something seemingly unrelated.


text:
Q: Error when Removing Row from TableView (Swift) I want to delete a row from a table view, but it isn't working :/
This next code block is triggered from a custom button (not from an internal Apple-Table-Edit).
self.tableView.beginUpdates()
self.sections[indexPath.section].items.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .automatic)
self.tableView.endUpdates()

This is how a section looks like:
class Section: Comparable {
    var state: TrackingObject.stateEnum
    var items: [TrackingObject]
    var expanded: Bool

    init(state : TrackingObject.stateEnum, items : [TrackingObject], expanded : Bool){
        self.state = state
        self.items = items
        self.expanded = expanded
    }

    static func group(trackingObjects: [TrackingObject]) -> [Section] {
        let groups = Dictionary(grouping: Model.trackingObjects) { (trackingObject: TrackingObject) -> TrackingObject.stateEnum in
            return trackingObject.currentState
        }
        return groups.map { (state: TrackingObject.stateEnum, trackingObjects: [TrackingObject]) in
            return Section(state: state, items: trackingObjects, expanded: state == .active_due ? true : false)
        }.sorted()
    }
}

Expected: That the row of the given indexPath is removed with an animation as well as removed in the 'data source' (called: self.sections)
Actual Output: Error-Message:

Terminating app due to uncaught exception
  'NSInternalInconsistencyException', reason: 'attempt to insert row 2
  into section 0, but there are only 0 rows in section 0 after the
  update'

(I was removing the second row in the section 0)

A: self.sections[indexPath.section].items.remove(at: indexPath.row)
    self.tableView.beginUpdates()
    DispatchQueue.main.async {
        tableView.deleteRows(at: [indexPath], with: .automatic)
        self.tableView.endUpdates()
    }

Try removing item from your data source before beginUpdates(). You can also just remove item from the data source and reload the table view as you are setting the animation option as automatic, so tableview will perform the preferable animation.


text:
Q: Switch hover animation when checked I made my own switch with html, css and js. I have an animation, when I hover the switch. This works fine, when the switch is unchecked. I would like to have the same hover animation the opposite way, when the switch is checked. This is my problem, it doesn't work.
I don't get it with checked and hover. I tried something like this:
input:checked + input:hover {
  -webkit-transform: unset;
  -ms-transform: unset;
  transform: unset;
}

$(document).ready(function(){

    $('.js-check').click(function(){
            if($(this).prop("checked") == true){
                $( "#s2" ).removeClass( "switchText-notActive" );
                $( "#s2" ).addClass( "switchText-active" );
                $( "#s1" ).removeClass( "switchText-active" );
                $( "#s1" ).addClass( "switchText-notActive" );
            }
            else if($(this).prop("checked") == false){
                $( "#s1" ).removeClass( "switchText-notActive" );
                $( "#s1" ).addClass( "switchText-active" );
                $( "#s2" ).removeClass( "switchText-active" );
                $( "#s2" ).addClass( "switchText-notActive");
            }
        });
    });
.switchText-active {
    color: #FF6600;
    -webkit-transition: .5s;
    transition: .5s;
}

.switchText-notActive {
    color: #DEDEDE;
     -webkit-transition: .2s;
    transition: .2s;
}

.switch {
    position: relative;
    width: 47px;
    height: 24px;
    margin-left: 15px;
    margin-right: 15px;
    margin-bottom: -6px;
}

.switch input {
   display: none;
}

.slider {
    position: absolute;
    cursor: pointer;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #FF6600;
    -webkit-transition: .2s;
    transition: .2s;
}

.slider:before {
    position: absolute;
    content: "";
    height: 20px;
    width: 20px;
    left: 3px;
    bottom: 2px;
    background-color: white;
    -webkit-transition: .2s;
    transition: .2s;
}

input:checked + .slider {
    background-color: #FF6600;
}

input:checked + .slider:before {
    -webkit-transform: translateX(21px);
    -ms-transform: translateX(21px);
    transform: translateX(21px);
}

input:hover + .slider:before {
    -webkit-transform: translateX(21px);
    -ms-transform: translateX(21px);
    transform: translateX(21px);
}

/* Rounded sliders */
.slider.round {
    border-radius: 36px;
}

.slider.round:before {
    border-radius: 50%;
}

.switch input:disabled + span {
    background-color: #2196F3;
    cursor: not-allowed;
    opacity: 0.6;
}

.switch input:not(:checked):disabled + span {
    background-color: #ccc;
    cursor: not-allowed;
    opacity: 0.6;
}

.myspan {
 height: 14px;
 width: 46px;
 font-family: Arial;
 font-size: 12px;
 font-weight: bold;
 line-height: 14px;
}
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Your Website</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

    <link rel="stylesheet" type="text/css" href="style.css">
    <link rel="stylesheet" type="text/css" href="switch.css">
    <link rel="stylesheet" type="text/css" href="css/checkbox.css">

Checkbox and Switch

                PICKUP

                    <input class="js-check" name="switch" type="checkbox">

                DELIVERY

I expect, that the slider jumps back to the starting point, when the switch is checked and I hover it with the mouse.

A: To hover the checked input elements use input:checked:hover
input[type="checkbox"]:checked:hover + .slider:before {
    -webkit-transform: translateX(0px);
    -ms-transform: translateX(0px);
    transform: translateX(0px);
}

I hope this is what u r expecting:

$(document).ready(function(){

    $('.js-check').click(function(){
            if($(this).prop("checked") == true){
                $( "#s2" ).removeClass( "switchText-notActive" );
                $( "#s2" ).addClass( "switchText-active" );
                $( "#s1" ).removeClass( "switchText-active" );
                $( "#s1" ).addClass( "switchText-notActive" );
            }
            else if($(this).prop("checked") == false){
                $( "#s1" ).removeClass( "switchText-notActive" );
                $( "#s1" ).addClass( "switchText-active" );
                $( "#s2" ).removeClass( "switchText-active" );
                $( "#s2" ).addClass( "switchText-notActive");
            }
        });
    });
.switchText-active {
    color: #FF6600;
    -webkit-transition: .5s;
    transition: .5s;
}

.switchText-notActive {
    color: #DEDEDE;
     -webkit-transition: .2s;
    transition: .2s;
}

.switch {
    position: relative;
    width: 47px;
    height: 24px;
    margin-left: 15px;
    margin-right: 15px;
    margin-bottom: -6px;
}

.switch input {
   display: none;
}

.slider {
    position: absolute;
    cursor: pointer;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #FF6600;
    -webkit-transition: .2s;
    transition: .2s;
}

.slider:before {
    position: absolute;
    content: "";
    height: 20px;
    width: 20px;
    left: 3px;
    bottom: 2px;
    background-color: white;
    -webkit-transition: .2s;
    transition: .2s;
}

input:checked + .slider {
    background-color: #FF6600;
}

input[type="checkbox"]:checked  + .slider:before {
    -webkit-transform: translateX(21px);
    -ms-transform: translateX(21px);
    transform: translateX(21px);
}

input[type="checkbox"]:checked:hover + .slider:before {
    -webkit-transform: translateX(0px);
    -ms-transform: translateX(0px);
    transform: translateX(0px);
}
input:hover + .slider:before {
    -webkit-transform: translateX(21px);
    -ms-transform: translateX(21px);
    transform: translateX(21px);
}

/* Rounded sliders */
.slider.round {
    border-radius: 36px;
}

.slider.round:before {
    border-radius: 50%;
}

.switch input:disabled + span {
    background-color: #2196F3;
    cursor: not-allowed;
    opacity: 0.6;
}

.switch input:not(:checked):disabled + span {
    background-color: #ccc;
    cursor: not-allowed;
    opacity: 0.6;
}

.myspan {
 height: 14px;
 width: 46px;
 font-family: Arial;
 font-size: 12px;
 font-weight: bold;
 line-height: 14px;
}
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Your Website</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

    <link rel="stylesheet" type="text/css" href="style.css">
    <link rel="stylesheet" type="text/css" href="switch.css">
    <link rel="stylesheet" type="text/css" href="css/checkbox.css">

Checkbox and Switch

                PICKUP

                    <input class="js-check" name="switch" type="checkbox">

                DELIVERY


text:
Q: NSTimer thread issue I have singleton that implements NSTimer object.
I run my timer using code below
self.myTimer = [NSTimer scheduledTimerWithTimeInterval: 1.0
                                                        target: self
                                                        selector: @selector(onTick:)
                                                        userInfo: nil repeats:YES];

I have NSUInteger instance variable that increase at each time when - onTick: method is called (so, once a second).
I have UILabel that represents date of my  NSUInteger instance variable and it works good. I have UIScrollView in my view as well. When I am scrolling it my UILabel does not update text. Even NSLog that shows info about timer tick in - onTick: method does not work. If I don't scroll timer begin works.


text:
Q: Drawing a simple line chart using Swift I am writing a Swift program using Xcode 9.2 for the MacOS with the objecting of displaying a simple line chart with three points.
The program's objective is to create a line graph using apple's core graphics. It is a horizontal line graph with three points, one at the center and at each end. If the mouse pointer is over the center point I want some text to display like "xyz" and when the mouse moves away the text would disappear. The end points will have labels containing numbers but for now let's call them "min" and "max".
Using XCode's playground, so far I have managed to accomplish to display a very clunky line graph using the following code:
class MyView : NSView {
   override func draw(_ rect: NSRect) {
       NSColor.green.setFill()
       var path = NSBezierPath(rect: self.bounds)
       path.fill()

  let leftDot = NSRect(x: 0, y: 0, width: 10, height: 20)
  path = NSBezierPath(ovalIn: leftDot)
  NSColor.black.setFill()
  path.fill()

  let rightDot = NSRect(x: 90, y: 0, width: 10, height: 20)
  path = NSBezierPath(ovalIn: rightDot)
  NSColor.black.setFill()
  path.fill()

  let centerDot = NSRect(x: 50, y: 0, width: 10, height: 20)
  path = NSBezierPath(ovalIn: centerDot)
  NSColor.black.setFill()
  path.fill()

  }
}

let viewRect = NSRect(x: 0, y: 0, width: 100, height: 10)
let myEmptyView = MyView(frame: viewRect)

The code produces a clunky looking line graph as follows:

The chart below is from Excel and this line chart is much cleaner and is what I am looking for but I want the line to be horizontal instead of diagonal.

Thanks in advance for your help.

A: To draw a horizontal line similar to the sample image you provided, I took your sample code and modified it. This would give this result:

The code would look like this then:
override func draw(_ rect: NSRect) {
    NSColor(red: 103/255, green: 146/255, blue: 195/255, alpha: 1).set()
    let line = NSBezierPath()
    line.move(to: NSMakePoint(10, 5))
    line.line(to: NSMakePoint(90, 5))
    line.lineWidth = 2
    line.stroke()

    NSColor(red: 163/255, green: 189/255, blue: 218/255, alpha: 1).setFill()

    let origins = [NSPoint(x: 10, y: 1),
                   NSPoint(x: 50, y: 1),
                   NSPoint(x: 90, y: 1)]

    let size = NSSize(width: 8, height: 8)

    for origin in origins {
        let quad = NSBezierPath(roundedRect: NSRect(origin: origin, size: size), xRadius: 2, yRadius: 2)
        quad.fill()
        quad.stroke()
    }
}

Update for iOS
Due to a request in the comments section here the iOS variant:
override func draw(_ rect: CGRect) {
    UIColor(red: 103/255, green: 146/255, blue: 195/255, alpha: 1).set()
    let line = UIBezierPath()
    line.move(to: CGPoint(x: 10, y:5))
    line.addLine(to: CGPoint(x: 90, y:5))
    line.lineWidth = 2
    line.stroke()

    UIColor(red: 163/255, green: 189/255, blue: 218/255, alpha: 1).setFill()

    let origins = [CGPoint(x: 10, y: 1),
                   CGPoint(x: 50, y: 1),
                   CGPoint(x: 90, y: 1)]

    let size = CGSize(width: 8, height: 8)

    for origin in origins {
        let quad = UIBezierPath.init(roundedRect: CGRect(origin: origin, size: size), cornerRadius: 2)
        quad.fill()
        quad.stroke()
    }
}

Alternatively, you could add a CAShapeLayer sublayer whose path property is a UIBezierPath to the UIView.


text:
Q: Scala change data iniside 2D list and return new list If lets say I have
val ll : List[List[Int]] = List(List(1,2,3), List(4,5,6), List(7,8,9))

What I want to do is multiple each number inside my list with the next one. So a n to n+1 multiplication.
So after what I want to do Is multiple 1 by 4, 2 by 5, 3 by 6, 4 by 7, 5 by 8 and 6 by 9.
val x : List[List[Int]] = List(List(4,10,18), List(28,40,54))

I have tried sliding(2) but It didnt work. Can someone point me in the right direction.

A: I have realized that it's much easier using sliding, as you proposed your question
ll.sliding(2).map{
    case List(l1, l2) =>
       l1.zip(l2).map{
          case (v1, v2)=> v1 * v2
       }
}.toList

A: This is a bit tricky, I think the best way is using a foldLeft
// we need to iterate on the list saving the previous element so we can use it for the multiplication. We start the iteration from the second element and we use the head as the first previous element
ll.tail.foldLeft((List[List[Int]](), ll.head)) {
   case ((res, last), elem) =>
     // here we calculate the multiplication
     val mult = elem.zip(last).map{
       case (v1, v2) => v1 * v2
     }
     // we add it to the result and we update the previous element
     (mult :: res, elem)
}._1.reverse

or with a foldRight
ll.dropRight(1).foldRight((List[List[Int]](), ll.last)) {
   case (elem, (res, last)) =>
     val mult = elem.zip(last).map{
       case (v1, v2) => v1 * v2
     }
     (mult :: res, elem)
}._1


text:
Q: How to edit model objects in an inline formset in Django In Django I am trying to use an inline formset factory so a user can edit instances of a model related to a parent model via a foreignkey. For some reason the methods I am trying don't save the changes I make when I click submit.
My view is like this (not including render):
def edit_sets(request, exercisegroup_id):

    exercisename = ExerciseName.objects.get(pk=exercisegroup_id)
    SetLoggerFormSet = inlineformset_factory(ExerciseName, SetLogger, fields=('weight','reps',))

    formset = SetLoggerFormSet(instance=exercisename)

    if request.method == 'POST':
      formset = SetLoggerFormSet(request.POST, instance=exercisename)
      if formset.is_valid():
         formset.save()
      else:
        formset = SetLoggerFormSet(instance=exercisename)

and I am displaying each form in the formset in my template so the user can individually edit the instance:
<form method="post">{% csrf_token %}
               {{ formset.management_form}}
               <table>
                  {% for form in formset %}
                        {{ form }}
                  {% endfor %}
               </table>
               <button type="submit" class="save btn btn-default">Save set</button>
          </form>

Stuck as to why this isn't working. The form displays as it should and this method has previously worked for adding objects, but I am still unable to use it to replace one of those objects in the queryset. Am I missing something I should be doing differently?
Edit:
Turns out the solution was to change my request.method statement to :
if request.method == 'POST':
      formset = SetsFormSet(request.POST, instance=exercisename)
      for form in formset:
        if form.is_valid():
           form.save()

Which allows me to save each form in the formset individually, seeing as I am altering only a section of the formset.

A: Your code is working for me. Maybe you have changed your environment setup or something else. When you submit your form, Is there any error showing to you? If so show us your error details.
You can try like this:
def edit_sets(request, exercisegroup_id):
    exercisename = ExerciseName.objects.get(pk=exercisegroup_id)
    SetLoggerFormSet = inlineformset_factory(ExerciseName, SetLogger, fields=('weight','reps',))

    formset = SetLoggerFormSet(instance=exercisename)

    if request.method == 'POST':
      formset = SetLoggerFormSet(request.POST, instance=exercisename)
      if formset.is_valid():
         formset.save()
      else:
        print("something is wrong in validation")
        print(formset.errors)
        formset = SetLoggerFormSet(instance=exercisename)


text:
Q: Dup2() usage and output redirection I'm trying to redirect the output of a process to the stdin of another process. This is done by dup2(). My question is: do stdin and stdout go back to their place(0,1) after function terminates, or do i have to do something like savestdin = dup(0). More clearly, after the function for one command terminates, at the second call are stdin and stdout on their supposed position?

A: To get your stdout to go to a forked process' stdin, you'll need to use a combination of pipe and dup. Haven't tested it but it should give you some ideas hopefully:
int my_pipe[2];

pipe(my_pipe); // my_pipe[0] is write end
               // my_pipe[1] is read end

// Now we need to replace stdout with the fd from the write end
// And stdin of the target process with the fd from the read end

// First make a copy of stdout
int stdout_copy = dup(1);

// Now replace stdout
dup2(my_pipe[0], 1);

// Make the child proccess
pid_t pid = fork();
if (pid == 0)
{
    // Replace stdin
    dup2(my_pipe[1], 0);
    execv(....); // run the child program
    exit(1); // error
}
int ret;
waitpid(pid, &ret, 0);

// Restore stdout
dup2(stdout_copy, 1);
close(stdout_copy);

close(my_pipe[0]);
close(my_pipe[1]);

So to answer your question, when you use dup2() to replace 0 and 1, they will not be restored to the terminal unless you save the original file descriptor with dup() and manually restore it with dup2().


text:
Q: A llamar método C# en Selenium, el resultado me da un error de VS El método simplemente me tiene que dar un True o False, si está presente en elemento en el DOM. Al llamarlo se ejecuta bien, pero luego me da error de VS:
using System;
using System.Collections.Generic;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using SeleniumExtras;
using OpenQA.Selenium.Interactions;

namespace Selenium
{
    internal class Program
    {

        static void Main(string[] args)
        {
            ChromeOptions option = new ChromeOptions(); // CREAMOS UNA INSTANCIA DEL NAVEGADOR
            option.AddArguments("--windows-size=1920,1080"); // TAMAÑO CORRECTO PARA EL MODO headless
            option.AddArguments("--disable-extensions"); // DESACTIVAR EXTENCIONES
            option.AddArguments("--user-agent/105.0.5195.127 CK={} (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko)");

            IWebDriver driver = new ChromeDriver(option); // CREAMOS EL OBJETO IWebDriver
            driver.Navigate().GoToUrl("https://www.google.com/");

            string ruta = "/html/body/ul[4]/li[1]";

            var c = Presentado(ruta);
            Console.WriteLine(c);

        }
        /// METODO PRESENTADO POR Xpath /////
        public static bool Presentado(string ruta)

        {
            IWebDriver driver = new ChromeDriver();
            var elemento = driver.FindElement(By.XPath(ruta));
            bool resultado = elemento.Displayed;
            return resultado;
        }

    }
}

el resto del código para manejar el navegador funciona correctamente; y al momento de llamar el método al ejecutarse, se abre otra vez el navegador "vacío" y el método falla.
NOTA: son nuevo en C#

A: Al tratar de ser preciso para describir mi problema, pude ver dónde está el error: resulta que el objeto IWebdriver iniciaba una instancia en main, y yo quería llamar a mi método, pero que utilice la instancia del objeto que ya estaba abierto, entonces la invocación es:
var c = Presentado(driver, ruta);
            Console.WriteLine(c);

Y el método quedaría así:
static bool Presentado(IWebDriver driver, string ruta)
    {
        var elemento = driver.FindElement(By.XPath(ruta));
        bool resultado = elemento.Displayed;
        return resultado;
    }


text:
Q: Add multiple geom_line to ggplot The geom_line CUR_MTH_UNEARN_REV_EUR is plotted correctly as a numeric. My goal is to add a second numeric geom_line (i.e., CUR_MTH_EARN_REV_EUR). Here's the code:
library("ggthemes")
library("gridExtra")
library("grid")

p = ggplot(f, aes(DTE_OF_REPORT_EUR, CUR_MTH_UNEARN_REV_EUR, label=(CUR_MTH_UNEARN_REV_EUR)))
+ geom_point(size=ifelse(f$CUR_MTH_UNEARN_REV_EUR<8.0, 11, 5), color=ifelse(f$CUR_MTH_UNEARN_REV_EUR<8.0, '#CC0000', 'black'))
+ geom_line(size=2,aes(group=1)) + geom_rangeframe() + theme_wsj()
+ theme(axis.text.x=element_text(angle=50, size=20, vjust=0.7))
+ geom_smooth(aes(group=1), method="loess", colour = "#CC0000", lwd=2)
+ geom_text(aes(label=CUR_MTH_UNEARN_REV_EUR), hjust=-0.5, vjust=0.5, fontface="bold")
+ ggtitle("Unearned Revenue by Service Code 'BS', in CSG Months, Jul. 2014-Aug. 2015")
+ theme(plot.title = element_text(lineheight=.8, face="bold"))

p

Text1 = textGrob("Source: Revenue Assurance and Quality Control", gp=gpar(fontsize=7))
p2 = p + annotation_custom(grob = Text1, ymin = -0.2, ymax = -30)

p2

format(round(f$CUR_MTH_UNEARN_REV_EUR, 2), nsmall = 2)
f$ScoreRounded <- round(f$CUR_MTH_UNEARN_REV_EUR, 1)
f$DTE_OF_REPORT_EUR <- factor(f$DTE_OF_REPORT_EUR, levels=unique(as.character(f$DTE_OF_REPORT_EUR)))

A: Hope this helps as a start. You can just add things, but you need to have the correct aes.
#data with x and two y-variables
set.seed(123)
f <- data.frame(x=1:10, var1=sample(7:10,10,T),
                var2=sample(5:7,10,T))

#as you want sizing by a measure, make a flag
f$var1_threshold <- f$var1 <9

#example with adding different geoms
#not that it's unnecessary to use my data (f)
#in the call to aes, as everything I need is already
#inside f
p <- ggplot(f, aes(x=x)) +
  geom_point(aes(y=var1,size=var1_threshold, color=var1_threshold))+
  #colors and size in aes allows for legend generation.
  scale_size_manual(values=c("FALSE"=5,"TRUE"=8)) +
  scale_color_manual(values=c("FALSE"='#CC0000',"TRUE"='black')) +
  geom_line(aes(y=var1),size=1) +
  geom_line(aes(y=var2),size=1) +
  geom_smooth(aes(y=var1), colour="#CC0000") +
  geom_smooth(aes(y=var2), colour="black")


text:
Q: R Adjacency Matrix - Get proportion of ties with certain attribute value I have a adjacency matrix depicting friendships. Further I have attribute values for the actors of the matrix stored in vectors (e.g. gender). My aim is to get the percentage of male and female friends for males and females respectively.
e.g. matrix A
 Actor 1   2    3
[1,]  0    1    1
[2,]  0    0    1
[3,]  1    1    0
.
gender <- c("male", "female", "male")

In this example above the result should look something like this:
        male  female
male    50%    50%
female  100%   0%

I`m thankful for any suggestions.

A: How about something like this?
# define matrix
m <- matrix(c(0,0,1,1,0,1,1,1,0),nrow = 3, ncol = 3)

# define gender vector
gender <- c("male", "female", "male")

# find: male-male friendships
mm <- subset.matrix(m, subset = gender == "male", select = gender == "male")
sum(mm)/(dim(mm)[1]*dim(mm)[2])

Which gives you the 1,1 element of your output matrix
But i'm a litte confused. Shouldn't you matrix be symmetric, such that percent_males_friends_with_females are equal to percent_females_that_are_friends_with_males ?


text:
Q: Implementing a custom combo box model failed to override some methods Am trying to implement a custom combobox model using MutableComboBoxModel interface which I hope to populate with dynamic data at runtime especially queried from the database. But I have failed to override some of the methods. Can somebody help to overide or suggest a better way I can achieved my end?
package PiggeryManagementSystem;

import java.util.ArrayList;
import javax.swing.MutableComboBoxModel;
import javax.swing.event.ListDataListener;

/**
 * @author Stanchart
 */
public class MyComboBoxModel  implements MutableComboBoxModel {

    ArrayList <String> columns = new ArrayList();

    public MyComboBoxModel( ArrayList<String> c) {
        this.columns = c;
    }

    @Override
    public void addElement(Object item) {

    }

    @Override
    public void removeElement(Object obj) {

    }

    @Override
    public void insertElementAt(Object item, int index) {
        columns.get(index);
    }

    @Override
    public void removeElementAt(int index) {

    }

    @Override
    public void setSelectedItem(Object anItem) {

    }

    @Override
    public Object getSelectedItem() {
        return columns.getClass();
    }

    @Override
    public int getSize() {
        return columns.size();
    }

    @Override
    public Object getElementAt(int index) {
        return columns.get(index);
    }

    @Override
    public void addListDataListener(ListDataListener l) {

    }

    @Override
    public void removeListDataListener(ListDataListener l) {

    }

}

A: I have managed to figure it out. Thanks a bunch.
package PiggeryManagementSystem;

import java.util.ArrayList;
import javax.swing.MutableComboBoxModel;
import javax.swing.event.ListDataListener;

/**
 * @author Stanchart
 */
public class MyComboBoxModel  implements MutableComboBoxModel {

    private Object selectedItem;
    ArrayList <String> columns = new ArrayList();

    public MyComboBoxModel( ArrayList<String> c) {
       this.columns = c;
    }

    @Override
    public void addElement(Object item) {
        columns.add(item.toString());
    }

    @Override
    public void removeElement(Object obj) {
        columns.remove(obj.toString());
    }

    @Override
    public void insertElementAt(Object item, int index) {
        columns.get(index);
    }

    @Override
    public void removeElementAt(int index) {
        columns.remove(index);
    }

    @Override
    public void setSelectedItem(Object anItem) {
        selectedItem = anItem;
    }

    @Override
    public Object getSelectedItem() {
        return selectedItem;
    }

    @Override
    public int getSize() {
        return columns.size();
    }

    @Override
    public Object getElementAt(int index) {
        return columns.get(index);
    }

    @Override
    public void addListDataListener(ListDataListener l) {

    }

    @Override
    public void removeListDataListener(ListDataListener l) {

    }
}


text:
Q: A variable is not being passed from the previous function Doing an assignment and can't get a variable passed between two methods in the same class.
global check
wage = 0
hours = 0
check = 0

class employee:
  def __init__(self, name, wage, hours, check):
    self.name = name
    self.wage = wage
    self.hours = hours
    self.check = check

  def paycheck(self):
    if self.hours > 41:
      self.hours = self.hours - 40
      overtime = self.wage * self.hours * 1.5
      self.check = (40 * self.wage) + overtime
      return self.check
      #print(self.check)
    else:
      self.check = self.hours * self.wage
      return self.check
      #print(self.check)

  def __str__(self):
    return self.name + ":\n Net Pay: $" + str(self.check)

A_emp = employee("Alice", 20, 40, 0)
B_emp = employee("Bob", 15, 50, 0)

print(A_emp)
print(B_emp)

The output should display the 'Net Pay' of each employee, and works to display most of the str method:
Alice:
 Net Pay: $0
Bob:
 Net Pay: $0

However, the check variable just wont pass values between class methods. I've globalized it, defined it outside of the class, and tried different variations of self.check vs check. Feel like I'm just throwing things and nothing is sticking. Thanks for any help.

A: You forgot to call the paycheck() method.  Also get rid of your global variables and return statements.
class employee:
    def __init__(self, name, wage, hours, check):
        self.name = name
        self.wage = wage
        self.hours = hours
        self.check = check

    def paycheck(self):
        if self.hours > 41:
            self.hours = self.hours - 40
            overtime = self.wage * self.hours * 1.5
            self.check = (40 * self.wage) + overtime

        else:
            self.check = self.hours * self.wage

    def __str__(self):
        return self.name + ":\n Net Pay: $" + str(self.check)

A_emp = employee("Alice", 20, 40, 0)
B_emp = employee("Bob", 15, 50, 0)

A_emp.paycheck()
B_emp.paycheck()

print(A_emp)
print(B_emp)

Output:
Alice:
 Net Pay: $800
Bob:
 Net Pay: $825.0

A: Once you create the class object you need to call
A_emp.paycheck()
B_emp.paycheck()