text:
Q: SwiftNIO: Send and receive UDP broadcast I'm trying to build a TCP server with SwiftNIO. The server starts in the net, but the clients don't know the ip address. Therefore I want to start an UDP server as well and if the clients comes up, he sends a broadcast message to the net. The server will receive and answer, so that the client now knows the IP address.
Is it possible to build something like this with SwiftNIO?

A: Yes, that's possible also there's not much support in SwiftNIO to make this easy.
See below for a commented example which will send HELLO WORLD once a second to en0's broadcast address and port 37020.
import NIO

let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
defer {
    try! group.syncShutdownGracefully()
}

let matchingInterfaces = try System.enumerateInterfaces().filter {
    // find an IPv4 interface named en0 that has a broadcast address.
    $0.name == "en0" && $0.broadcastAddress != nil
}

guard let en0Interface = matchingInterfaces.first, let broadcastAddress = en0Interface.broadcastAddress else {
    print("ERROR: No suitable interface found. en0 matches \(matchingInterfaces)")
    exit(1)
}

// let's bind the server socket
let server = try! DatagramBootstrap(group: group)
    // enable broadast
    .channelOption(ChannelOptions.socket(SOL_SOCKET, SO_BROADCAST), value: 1)
    .bind(to: en0Interface.address)
    .wait()
print("bound to \(server.localAddress!)")

var buffer = server.allocator.buffer(capacity: 32)
buffer.writeString("HELLO WORLD!")

var destAddr = broadcastAddress
destAddr.port = 37020 // we're sending to port 37020

// now let's just send the buffer once a second.
group.next().scheduleRepeatedTask(initialDelay: .seconds(1),
                                  delay: .seconds(1),
                                  notifying: nil) { task in
    server.writeAndFlush(AddressedEnvelope(remoteAddress: destAddr,data: buffer)).map {
        print("message sent to \(destAddr)")
    }.whenFailure { error in
        print("ERROR: \(error)")
        // and stop if there's an error.
        task.cancel()
        server.close(promise: nil)
    }
}

try server.closeFuture.wait()

In case you want to bind to 0.0.0.0 and send to 255.255.255.255 you can use this
import NIO

let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
defer {
    try! group.syncShutdownGracefully()
}

// let's bind the server socket
let server = try! DatagramBootstrap(group: group)
    // enable broadast
    .channelOption(ChannelOptions.socket(SOL_SOCKET, SO_BROADCAST), value: 1)
    .bind(to: .init(ipAddress: "0.0.0.0", port: 0))
    .wait()
print("bound to \(server.localAddress!)")

var buffer = server.allocator.buffer(capacity: 32)
buffer.writeString("HELLO WORLD!")

// we're sending to port 37020
let destPort = 37020
let destAddress = try SocketAddress(ipAddress: "255.255.255.255", port: destPort)

// now let's just send the buffer once a second.
group.next().scheduleRepeatedTask(initialDelay: .seconds(1),
                                  delay: .seconds(1),
                                  notifying: nil) { task in
    server.writeAndFlush(AddressedEnvelope(remoteAddress: destAddress, data: buffer)).map {
        print("message sent to \(destAddress)")
    }.whenFailure { error in
        print("ERROR: \(error)")
        // and stop if there's an error.
        task.cancel()
        server.close(promise: nil)
    }
}
try server.closeFuture.wait()


text:
Q: Unify checkbox for all browser CSS Styling I need some help to create unify checkbox in across all the browsers.
my application is using a theme which make the checkbox look ugly.
where can I globally set browser properties so checkbox will appear same across diff platforms
http://jsfiddle.net/khan777/LnL7b/109/
CSS
.mycheckbox:checked {
    background: url(icon.png)no-repeat center center;
    background-size: 100%;
}

Here's how ugly it looks in Chrome

A: If what you're referring to is "ugly" is the transparent background color once the box is checked, add the background color to your property in front of the URL:
.MyCheckBox:checked {
    display : inline-block;
    background: #fff url(http://vignette3.wikia.nocookie.net/roblox/images/5/57/Very-Basic-Checkmark-icon.png/revision/latest?cb=20131125154354) no-repeat center center;
    background-size: 100%;
}

If you meant something else, please add details.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What does the following mean with respect to enumerations in C programming? In a book I'm reading, enumeration constants have been introduced before arrays. Use of arrays has been demonstrated only through a couple examples. Following is stated :
enum corvid { magpie, raven, jay, corvid_num};

char const * const bird [ corvid_num ] =
{
  [raven] = "raven",
  [magpie] = "magpie",
  [jay] = "jay",
};

for ( unsigned i = 0; i < corvid_num ; ++i)
  printf ("Corvid %u is the %s\n", i, bird[i]);

This declares a new integer type enum corvid for which we know four different values.

Takeaway - Enumeration constants have either an explicit or a positional value

As you might have guessed, positional values start from 0 onward, so in our example
we have raven with value 0, magpie with 1, jay with 2, and corvid_num with 3. This last
3 is obviously the 3 we are interested in.

Question 1:
Does [magpie] = "magpie" imply that magpieth position refers to value "magpie".
Question 2:
According to loop, how is bird[0] equal to "raven" , since this is explicit and not a positional value. Also after the first iteration is [i + 1] gonna be equal to [magpie]. In all why is loop variable's type unsigned and not corvid or enum corvid?
I think I have misunderstood enumeration constants.
Also from,

As you might have guessed, positional values start from 0 onward, so in our example we have raven with value 0, magpie with 1, jay with 2, and corvid_num with 3. This last 3 is obviously the 3 we are interested in.

Is author right to say that raven should have value 0 and not magpie, if this is a typo, entirety of my confusion will dispense.

A: In the declaration char const * const bird [ corvid_num ]  the item between [ ] is the size of the array. In the initializer list, [ raven ] = " raven ", the item between [ ] is a so-called designated initializer, used to initialize a particular item in the array.

Question 1 : Does ' [ magpie ] = " magpie "' imply that 'magpie'TH position refers to value "magpie".

Yes.

Question 2 : According to loop, how is bird [0] equal to "raven" , since this is explicit and not a positional value.

Because enums are named constants. If an enumeration constant (raven etc) isn't given a number explicitly, it is given one implicitly, starting at 0. raven in your example is the second item in the enum, so it gets value 1 and whenever you type raven in the source it will be equivalent to typing 1.

As you might have guessed, positional values start from 0 onward, so in our example we have raven with value 0, magpie with 1, jay with 2, and corvid_num with 3. This last 3 is obviously the 3 we are interested in.

This is an error in Gustedt - Modern C. Errata might exist? The output from the example code is:
Corvid 0 is the magpie
Corvid 1 is the raven
Corvid 2 is the jay

Notably, if we had not used designated initializers but just done this:
char const * const bird [ corvid_num ] =
{
    "raven",
    "magpie",
    "jay",
};

Then the output would instead have become
Corvid 0 is the raven
Corvid 1 is the magpie
Corvid 2 is the jay

A: Each enum case gets the value of the previous case plus one, unless explicitly overridden, and the first case gets the value zero. So here magpie is 0, raven is 1, etc. (The quoted part saying otherwise is wrong.) The final case corvid_num is the count of other cases in the array, since the + 1 of that case accounts for the zero case in the beginning.
The array initialisation is using C99 designated initializers, which allows assigning values to specific indices and in any order, i.e., [raven] = "raven" initialises the index raven (here 1). It would be possible to just traditionally list each value in order, but doing it this way allows reordering the enum cases without having to sync the changes with the array.


text:
Q: Eclipse PreferencePage "Apply" and "OK" greyed-out I am a newcomer to Eclipse PreferencePages and am currently creating a new FieldEditorPreferencePage for my project. However, having FileFieldEditors() or DirectoryFieldEditors() greys-out the "Apply" and "OK" buttons in my custom preference page. On the other hand, the other FieldEditors (Boolean- and Combo-) do not disable the "Apply" and "OK" buttons.
Furthermore, changing everything to Xtext's LanguageRootPreferencePage seems to work as well (though I'd prefer not to use it as I want the custom preference page to show up in it's own tab).
For example:
//Simplified example of code
public class XPreferencePage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage, IWorkbenchPropertyPage {
   public XPreferencePage() {
      super(FieldEditorPreferencePage.GRID);
      setDescription("something");
   }

   protected void initialize() {
      super.initalize();
      //IPropertyChangeListeners go here
   }

   protected void createFieldEditors() {
      //"Apply" and "OK" works here
      g = new BooleanFieldEditor(SConstants.GENERATOR, "Generate Bindings", getFieldEditorParent());
      addField(g);

      //"Apply" and "OK" is greyed-out starting here
      gp = new FileFieldEditor(SConstants.GENERATOR_PATH, "Generator Path:", false, 0, getFieldEditorParent());
      gp.setEmptyStringAllowed(true);
      addField(gp);
      ...
   }
...
}

Is there anyway to fix this? I followed the tutorial from Eclipse Article-Field-Editors but it doesn't seem to work for me. Reading online says it can be due to negative IntegerField (which I don't have) or that I'm trying to change the default settings (which I don't have either).
I am using Eclipse Mars 4.5.0.
UPDATE: The code above (partially) worked for FileFieldEditors. However, for some reason I need to click FileFieldEditor field and check and uncheck the checkbox directly above the FileFieldEditor for each FileFieldEditor in the preference page before the "Apply" and "OK" buttons are available again.
Furthermore, I have also implemented a IPropertyChangeListener which deactivates certain fields when certain checkboxes are unchecked which means this "check and uncheck" workaround would not work for me. I have also tried setting the default focus to one of my checkboxes but that didn't work

A: FileFieldEditor(String name, String labelText, Composite parent) defalult validates the path when the text widget loose the focus that is what you are giving invalid as default value.
For e.g. if you give C:\\User\\XXX then this path should physically exist then and only it will not grey out ok and apply button.
You can also use below constructor by setting your validation stratergy.
FileFieldEditor(String name, String labelText,boolean enforceAbsolute, int validationStrategy, Composite parent)

value of validationStrategy

*

*1 for the editor performs validation only when the text widget
loses focus.

*0 for the editor performs validation after every key
stroke.


text:
Q: My custom font with an extended character set gets messed up when I convert it for for @font-face I have been making a custom font that as well as having the alphabet and punctuation, also contains lots of icons. It's important to the project that they are in the same font file. I have been using an Latin extended 2 encoding to fit it all in. When i try and convert it with Font Squirrel or font2web it drops half of the character set - despite me specifying the encoding in the advanced options.
Font squirrel does mention in its documentation that it wont convert many extended characters.
My questions are: Is there a way to make FontSquirrel work properly? Could I be missing something? OR - how can i create these web font files (woff, eof etc) using software?
Thanks so much!
Caroline


text:
Q: formula to find specific cell with data within range of cells I have a row of cells that I created an if scenario in that will give either a blank cell response or a address that is required if the column next to it lists a specific person in this survey workbook...only 1 cell will have data and it will be for that individual chosen, and all others will be blank at all times as each survey workbook is unique...now, I have another cell that I need for it to copy the address that will be listed at the time for this worksheet.....what formula would I use to retrieve that address listed from the cells?

A: If all the cells are empty in a certain range apart from one, if you concatenate all the cell values in that range, you will have the answer.
For example, if you had the following cells:
[      ]
[      ]
[      ]
[ABC   ]
[      ]

If you concatenate all these cells, you would end up with:
[ABC   ]


text:
Q: permutation representation isomorphism Consider the symmetric group $S_n$ and let $H$ be the subgroup that fixes $n$ (so its isomorphic to $S_{n-1}$)
Show the representation defined by $S_n$ acting on $S_n \backslash H$ is isomorphic to the $n$-dimensional permutation representation of $S_n$.
So here's what I got,
We already know that $\vert S_n / H \vert = n$
So I want to go by saying $\exists$ two group homomorphisms $\rho_1,\rho_2$ s.t.
$\rho_1: S_n \rightarrow \mathrm{Aut}(k^n)$ (Where Aut($k^n$) is really GL$_n(k)$, $k$ is some field.
And
$\rho_2: S_n \rightarrow \mathrm{Aut}(S_n / H)$
Then could I let $f: k^n \rightarrow S_n /S_{n-1}$
be defined by taking $\overline{v} \in k^n$ and mapping it to left coset $\overline{v}S_{n-1}$ and show this map is well defined and that
$f(\rho_1(\sigma)\overline{v})=\rho_2(\sigma)f(\overline{v})$ for $\sigma \in S_n$, $\overline{v} \in k^n$
Then do I just need to find a vector space isomorphism that preserves the $G$-action? Are my maps correct? Am I good so far/going the right direction? Thats really all I want to know. (Im taking rep theory and have not taken group/ring theory in about a decade)


text:
Q: objMailItem.Attachments.add and %temp% location How do I add an attachment in Outlook from Windows' %temp% folder?
Somewhere in the script I have:
Dim tempfolder
Set tempfolder = objFSO.GetSpecialFolder(TemporaryFolder)

(...)
objMailItem.Attachments.add tempfolder & "\file.zip"

but it does not work. Any ideas?
Thanks a million.

A: You have to put in value 2 not the constant temporaryfolder. Remember VBS is late bound so their are no constants from objects. You have to look it up and put the value in.


text:
Q: Convert numbers toTrue values in pandas column There is a lot of information how to convert bool values to numbers 1 an 0, but I have not found how to do the opposite conversion:
My DataFrame:
col1 col2
1    NaN
2    0.2222
3    NaN
4    4.555

Expected output:
col1 col2
1    NaN
2    True
3    NaN
4    True

Numbers became True values.

A: df.loc[~df['col2'].isnull(),'col2']=True

A: Do mask
df.col2.mask(df.col2.notna(), True, inplace=True)
df
Out[41]:
   col1  col2
0     1   NaN
1     2  True
2     3   NaN
3     4  True


text:
Q: Dynamic array of int pointers causing segmentation fault I found a segmentation fault in my C code and could not find a good explanation or solution for it after searching.
This first code gives me segmentation fault after printing 0.
#include <stdlib.h>
#include <stdio.h>
int main() {
    int **defs = malloc(16 * sizeof *defs);
    int i;
    for (i = 0; i < 16; i++) {
        printf("%d\n", i);
        *defs[i] = i;
    }
    free(defs);
    return 0;
}

This second code works fine.
#include <stdlib.h>
#include <stdio.h>
int main() {
    int *defs = malloc(16 * sizeof defs);
    int i;
    for (i = 0; i < 16; i++) {
        printf("%d\n", i);
        defs[i] = i;
    }
    free(defs);
    return 0;
}

These are just examples, not my actual code. I also tried doing pointer arithmetic but same result.
Could someone please explain this? Thank you.

A: In first code you have not allocated each of the int* memory blocks.
So, before assigning values to defs[i], you have to populate it with memory of type int*.
defs[i] = (int*)malloc(sizeof(int) * number_of_elements);

And then defs[i][some_index] = value.


text:
Q: dynamically set css file name in _layout master page in Razor Mvc I have a css file referenced in my _layout.cshtml
<link rel="stylesheet" type="text/css" href="//css/styles-640.css" />

there are 2 different versions (640 and 720) for displaying the page in different sizes
The size is a value in the querystring
How can I read the value from the querystring and dynamically inject it into the filename of the .css file?
This is in the master page (_layout.cshtml) and it obviously has lots of different ViewModels depending on which view is being rendered

A: @if(Request["size"] == 640) {
    <link rel="stylesheet" type="text/css" href="//css/styles-640.css" />
} else {
    <link rel="stylesheet" type="text/css" href="//css/styles-720.css" />
}

A: It's very easy, Use condition @if in _layout.cshtml. Don't remember call cast function.
Request.QueryString["big"] and Request["big"] are same
@if (Request.QueryString["big"].AsBool()==true)
{
    <link rel="stylesheet" type="text/css" href="//css/styles-720.css" />

}
else
{
    <link rel="stylesheet" type="text/css" href="//css/styles-640.css" />
}


text:
Q: Executing an sh script on Ubuntu boot I've been trying for some time to execute my script, UbuntuBootScript.sh, every time Ubuntu boots up.
The script is located at the following path: /home/network/scripts/UbuntuBootScript.sh
I have attempted at telling ubuntu to run the script every time it boots, through the /etc/rc.local directory, who's content currently is:
#!/bin/sh -e
/home/network/scripts/UbuntuBootScript.sh
exit 0

Content of UbuntuBootScript.sh is:
#!/bin/bash
sh openWindows.sh
sh startServers.sh
exit 0

Both called scripts function correctly if executed individually.
Up on rebooting ubuntu, UbuntuBootScript.sh seems to not be executed, since the desired functionality does not occur.
It looks like either something is not well written on rc.local, or the boot script rc.local is somehow disabled?, because the script itself DOES work if manually executed.
I need to fix this issue. Assistance is appreciated. Thanks in advance!

A: An easy way to run commands at startup is to add them to /etc/rc.local but you need to make these commands executable your best bet is to use this script, what this script does is adds a link to the selected file in /bin/ allowing for it to be executed where you want.
What you should do is download the script and place it in a directory, it has to be ~/Scripts and then open a terminal and then run cd ~/Scripts then sudo chmod +x makeex.sh and then sudo ln -r -s makeex.sh /bin/
And then cd into whatever directory UbuntuBootScript.sh is stored in and run makeex.sh UbuntuBootScript.sh and then edit /ect/rc.local and add UbunutBootScript.sh to it.


text:
Q: How to change checkbox value in contact form checkbox? I have created a message form in my website, now I am adding a text box to it.
I am getting the checkbox value is ON in the email if checkbox checked blank if unchecked.
Like this

I have to make the text Checkbox checked if Checked and Checkbox Unchecked if unchecked instead of Blank & ON Value.
Here is my Contact Form HTML

     <form id="contact-form" method="post" action="php/contact-form-handler.php">
        <input name="name" type="text" class="form-control" placeholder="Your Name" required="required" />

        <input name="email" type="email" class="form-control" placeholder="Your Email" required="required" />
        <input type="checkbox" class="opt-in-checkbox" name="checkbox">Check here to receive email updates
        <input name="subject" type="text" class="form-control" placeholder="Subject" required="required" />
   <textarea name="message" class="form-control" placeholder="Message" row="10" required="required" /></textarea>

            <input type="submit" class="from-control submit" value="SEND MESSAGE" />
  </form>

Here is the PHP code

<?php
 $name = $_POST['name'];
 $visitor_email = $_POST['email'];
 $subject = $_POST['subject'];
 $message = $_POST['message'];
 $checkbox = $_POST['checkbox'];

 $email_from = 'xxx@gmail.com';

 $email_subject = "New Form Submission";

 $email_body = "User Name: $name\n".
     "User Email: $visitor_email\n".
      "Checkbox: $checkbox\n".
          "Subject: $subject\n".
           "User Message: $message\n";

 $to = "yyy@gmail.com";

 $headers = "From: $email_from \r\n";

 $headers .= "Reply-To: $visitor_email \r\n";

 mail($to,$email_subject,$email_body,$headers);

 header("Location: /contact-us.html");
?>

A: Try
$checkbox = isset($_POST['checkbox']) ? "checked" : "unchecked";

A: You just forgotte to add condition.
Here is latest code please check carefully and then you can implement in your current code.
if(!empty($_POST)) {
    $name = $_POST['name'];
    $visitor_email = $_POST['email'];
    $subject = $_POST['subject'];
    $message = $_POST['message'];
    $checkbox = 'unchecked';
    if( isset($_POST['checkbox']) && $_POST['checkbox'] == true){
       $checkbox = 'checked';
    }

    $email_from = 'xxx@gmail.com';
    $email_subject = "New Form Submission";
    $email_body = "User Name: $name\n".
                    "User Email: $visitor_email\n".
                        "Checkbox: $checkbox\n".
                            "Subject: $subject\n".
                                "User Message: $message\n";
    $to = "yyy@gmail.com";
    $headers = "From: $email_from \r\n";
    $headers .= "Reply-To: $visitor_email \r\n";
    mail($to,$email_subject,$email_body,$headers);
    header("Location: /contact-us.html");
}


text:
Q: How to implement list comprehensions when there are multiple nested if conditions I am always confused when it comes to list comprehensions especially with these nested if-else. How can I implement this part of the code using list comprehension
for i in range(len(s1)):
   if i % 2 == 0:
      if ord(s1[i]) == 122:
         s3 += chr(97)
      else:
         s3 += chr(ord(s1[i])+1)
   else:
      if ord(s2[i]) == 122:
          s3 += chr(97)
      else:
          s3 += chr(ord(s2[i])+1)

this is the full code for reference
s1 = input()
s2 = input()
n = int(input())
lst = []
for i in range(n):
    s3 = ''
    for i in range(len(s1)):
        if i % 2 == 0:
            if ord(s1[i]) == 122:
                s3 += chr(97)
            else:
                s3 += chr(ord(s1[i])+1)
        else:
            if ord(s2[i]) == 122:
                s3 += chr(97)
            else:
                s3 += chr(ord(s2[i])+1)
    lst.append(s3)
    s1 = s2
    s2 = s3
print(lst[n-3])

A: Although I have no clue why you're doing it, rewriting that code as a comprehension is fairly straightforward:
s3 = ''.join(
    chr(97) if ord(t[i % 2]) == 122 else chr(ord(t[i % 2])+1)
    for i, t in enumerate(zip(s1, s2))
)

A: Writing comprehensions basically means that you move the append line, in this case string concatenation, to the front and everything else stays in the same order. I think Grismar's answer is better, but here is how you do it specifically as you asked.
''.join(
    chr(97) if ord(s1[i]) == 122 else chr(ord(s1[i])+1) if i % 2 == 0
    else chr(97) if ord(s2[i]) == 122 else chr(ord(s2[i])+1)
    for i in range(len(s1))
)

See below:
>>> def f(s1, s2):
...     s3 = ''
...     for i in range(len(s1)):
...         if i % 2 == 0:
...             if ord(s1[i]) == 122:
...                 s3 += chr(97)
...             else:
...                 s3 += chr(ord(s1[i])+1)
...         else:
...             if ord(s2[i]) == 122:
...                 s3 += chr(97)
...             else:
...                 s3 += chr(ord(s2[i])+1)
...     return s3
...
>>> f('123', '456')
'264'
>>> def g(s1, s2):
...     return ''.join(
...         chr(97) if ord(s1[i]) == 122 else chr(ord(s1[i])+1) if i % 2 == 0
...         else chr(97) if ord(s2[i]) == 122 else chr(ord(s2[i])+1)
...         for i in range(len(s1))
...     )
...
>>> g('123', '456')
'264'

P.S. this level of nested if statements is way too complicated to include in code you share with other people (including your future self). Simplify, simplify, simplify!


text:
Q: Getting Internet to run with Inspiron 1525 in Linux Mint 11 I have tried installing the drivers with that one click option they promote but it doesn't pull up the broadcom drivers it needs.

A: Had a huge problem with that way back when. The easy way out is to go and buy another WiFi adapter to use over USB. But that would be ugly.
Try plugging the computer into an Ethernet port (you have tried that, right?). Then follow this guide. It's basically what the utility does but since you're doing it yourself it'll be easier to see what (if anything) goes wrong.
Have fun.


text:
Q: How to add data to a TrieMap[Long,List[Long]] in Scala i have this:
val vertexIdListPartitions: TrieMap[Long, List[Long]] = TrieMap()

i need to add List(3) at vertexIdListPartitions(3).
I try to do this with:
vertexIdListPartitions(3)++List(3)

but it doesn't work.
Please help me.
Thanks

A: Mutable collections have the update() method for this.
vertexIdListPartitions.update(3L, List(3))  //res0: Unit = ()
vertexIdListPartitions  //res1: TrieMap[Long,List[Long]] = TrieMap(3 -> List(3))


text:
Q: Does holomorphicness of left and right multiplication imply holomorphicness of multiplication? Let $G$ be a complex group, i.e. a complex manifold with a group structure. Assume that for each $g\in G$, the map
$$G\rightarrow G,h\mapsto gh^{-1}$$
is holomorphic. Can it imply that $G$ is a complex Lie group? Or equivlently, is the map
$$G\times G\rightarrow G,(g,h)\mapsto gh^{-1}$$
also holomorphic?
Link to Does smoothness of left and right multiplication imply smoothness of multiplication?


text:
Q: Android : Adding close button into achartengine chart layout In my android app it will create a pie chart when a button is clicked. This is my code segment for button clicked.
btnpieChart.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        SelectDBAdapter selectDBAdapter = SelectDBAdapter
                                .getDBAdapterInstance(getActivity());
                        try {
                            selectDBAdapter.openDataBase();
                            chartDataMap = selectDBAdapter.getPieChartData(strBusinessUnit,
                                    currentPeriod, currentYear);
                        } catch (Exception e) {
                            selectDBAdapter.close();
                            e.printStackTrace();
                        } finally {
                            selectDBAdapter.close();
                        }
                        if (chartDataMap.size() > 0) {
                            Intent chrtIntent = new Intent(getActivity(),
                                    PieChart.class);
                            chrtIntent.putExtra("chartMap", chartDataMap);
                            startActivity(chrtIntent);
                        } else {
                            Toast.makeText(getActivity(), "No Achievement Progress", Toast.LENGTH_SHORT).show();
                        }

                    }
                });

And this is my PieChart.java class.
package xont.virtusel.v4.controller;

//imports

public class PieChart extends Activity {
private ArrayList<String> lstBrandNames = new ArrayList<String>();
private ArrayList<Double> lstAchievedVals = new ArrayList<Double>();
private GraphicalView mChartView = null;

protected void onResume() {
    super.onResume();
}

public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
}

public void onBackPressed() {
    return;
}

public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        this.finish();

        return true;
    }
    return false;

}

public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.complains, menu);
    return true;
}

public boolean onOptionsItemSelected(android.view.MenuItem item) {
    switch (item.getItemId()) {
    case R.id.menu_cancel:
        this.finish();
        return true;

    default:
        return super.onOptionsItemSelected(item);
    }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.pie_chart);

    HashMap<String, Double> chrtMap = (HashMap<String, Double>) getIntent().getSerializableExtra("chartMap");
        for (Map.Entry<String, Double> entry : chrtMap.entrySet()) {
            //System.out.println(">>>> " + entry.getValue());
            if (entry.getValue() > 0) {
                lstBrandNames.add(entry.getKey());
                lstAchievedVals.add(entry.getValue());
            }
        }

        if (lstBrandNames.size() == 0 || lstAchievedVals.size() == 0) {
            Toast.makeText(getApplicationContext(), "No Achievement Progress", Toast.LENGTH_SHORT).show();
            finish();
        } else {

            ArrayList<Double> distribution = calc_Percentage(lstAchievedVals);
            System.out.println("distribution === " + distribution);
            lstBrandNames = set_lables(lstBrandNames, distribution);

            CategorySeries distributionSeries = new CategorySeries(
                    "Your Achievement Progress");
            for (int i = 0; i < distribution.size(); i++) {
                distributionSeries.add(lstBrandNames.get(i),
                        distribution.get(i));
            }

            DefaultRenderer defaultRenderer = new DefaultRenderer();
            defaultRenderer.setApplyBackgroundColor(true);
            defaultRenderer.setBackgroundColor(Color.WHITE);
            defaultRenderer.setLabelsTextSize(15);
            defaultRenderer.setInScroll(true);

            for (int i = 0; i < distribution.size(); i++) {

                SimpleSeriesRenderer seriesRenderer = new SimpleSeriesRenderer();
                Random rnd = new Random();
                int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256),
                        rnd.nextInt(256));
                seriesRenderer.setColor(color);
                seriesRenderer.setDisplayChartValues(true);
                seriesRenderer.setShowLegendItem(false);
                defaultRenderer.addSeriesRenderer(seriesRenderer);

            }

            defaultRenderer.setLabelsColor(Color.BLACK);
            defaultRenderer.setChartTitle("Your Achievement Progress");
            defaultRenderer.setChartTitleTextSize(25);
            defaultRenderer.setZoomButtonsVisible(true);
            defaultRenderer.setShowLabels(true);

            mChartView = ChartFactory.getPieChartView(this,
                    distributionSeries, defaultRenderer);
            LinearLayout layout = (LinearLayout) findViewById(R.id.chart_container);
            layout.removeAllViews();
            layout.addView(mChartView);
        }
}

public static ArrayList<Double> calc_Percentage(ArrayList<Double> list) {

    ArrayList<Double> lstPercentage = new ArrayList<Double>();

    double total = 0;
    double precentage;
    for (int i = 0; i < list.size(); i++) {
        total = total + list.get(i);
    }
    System.out.println(total);
    for (int j = 0; j < list.size(); j++) {
        precentage = (list.get(j) / total) * 100;
        lstPercentage.add(precentage);
    }

    return lstPercentage;
}

public static ArrayList<String> set_lables(ArrayList<String> lstBrandNames,
        ArrayList<Double> distribution) {
    String G_lable;
    DecimalFormat df = new DecimalFormat("#.00");
    ArrayList<String> lstLabels = new ArrayList<String>();
    for (int i = 0; i < lstBrandNames.size(); i++) {
        G_lable = lstBrandNames.get(i) + " : "
                + df.format(distribution.get(i)) + "%";
        lstLabels.add(G_lable);
    }
    return lstLabels;

}

}
Here is my pie_chart.xml file.
I want to disable the default Back key function of the device and introduce the close button on top of the pic chart. I've added a menu in my PieChart class but no luck. Why it is not adding the menu like other activities? I've introduced my pie chart class in manifest file as follows.
<activity android:name=".PieChart" android:theme="@android:style/Theme.Dialog"  android:label="Progress Chart"> </activity>

How should I solve this issue ? Any suggestions are greatly appreciated.

A: try
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        this.finish();

        return true;
    }
    return false;

}

A: try this
  @Override
public boolean onCreateOptionsMenu(Menu menu) {
    // TODO Auto-generated method stub

    getMenuInflater().inflate(R.menu.main, menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // TODO Auto-generated method stub

    switch (item.getItemId()) {
    case R.id.exit:
        finish();
        moveTaskToBack(true);
        return true;

    default:
        return super.onOptionsItemSelected(item);
    }

}

A: By overriding onBackPressed, you can effectively disable the back button :
@Override
public void onBackPressed() {
    // Do nothing, back button is de-activated.
}

The way you create your menu looks fine to me.

A: try this
it worked for me
  @Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    // TODO Auto-generated method stub
//  return super.onKeyDown(keyCode, event);

    if (keyCode ==event.KEYCODE_BACK) {
        return true;
    }
    return false;
}


text:
Q: Consulta Access via VBA Estou com uma base em Access e estou com problemas no resultado da QUERY.
Quando executo essa mesma QUERY no access, ela roda normalmente, mas quando jogo no VBA ela não dá erro, mas não retorna nenhum registro no RECORSET.
Abaixo a QUERY que estou usando:
Set BD = New ADODB.Connection
BD.Open ConectaBD
sWHERE = "WHERE (((BASE_PREMIO.UF)=""SP"") AND ((BASE_PREMIO.cliente)=""CAASP"") AND ((BASE_PREMIO.GrupoPlano)=""ESPECIAL"") AND ((BASE_PREMIO.Região)=""SUDESTE"") AND ((BASE_PREMIO.TpEntidade)=""FECHADA"") AND ((BASE_PREMIO.Corretor) Like ""*""))"
QUERY = "SELECT BASE_PREMIO.REFERENCIA, Sum(BASE_PREMIO.Premio_Sum) AS SomaDePremio_Sum, Sum(BASE_PREMIO.Vidas_Sum) AS SomaDeVidas_Sum, Sum(IIf([DIF_MES_VENDAS_MATURADAS]>2,[PREMIO_SUM],0)) AS [VENDA MATURADA_PREMIO], Sum(IIf([DIF_MES_VENDAS_MATURADAS]>2,[VIDAS_SUM],0)) AS [VENDA MATURADA_VIDAS], Sum(IIf([VENDAS]=""S"",[PREMIO_SUM],0)) AS VENDA_PREMIO, Sum(IIf([VENDAS]=""S"",[VIDAS_SUM],0)) AS VENDA_VIDAS, Sum(IIf([VENDAS]=""N"",[PREMIO_SUM],0)) AS ESTOQUE_PREMIO, Sum(IIf([VENDAS]=""N"",[VIDAS_SUM],0)) AS ESTOQUE_VIDAS "
QUERY = QUERY & "FROM BASE_PREMIO "
QUERY = QUERY & sWHERE
QUERY = QUERY & " GROUP BY BASE_PREMIO.REFERENCIA;"
Set RS = New ADODB.Recordset
RS.Open QUERY, BD

Acho que o problema ocorre porque busco campos com condições específicas. Será que preciso habilitar alguma ferramenta nas referencias do vba? Ou tem outra forma de resolver esse problema?  Obrigada.


text:
Q: Using multi-sampling creates artifacts along mesh edges (DirectX, C#) I'm rendering a mesh in a visual c#, using directx. When turning on anti-aliasing, I got following artifacts along the edges on mesh (see image). Artifacts shows only on edges turned toward the camera and they shows on every mesh I load. I'm using DirectX 9.0 libraries and the problem is present only on my Windows 10 desktop. I use also Windows XP desktop for testing and mesh is displayed correctly there. Also, the level of multisampling seems not to influence the problem (but the problem disappear when mutisampling is set to none)
Here is the initialization of parameters:
PresentParameters presentParameters = new PresentParameters();
presentParameters.BackBufferFormat = Format.Unknown;
presentParameters.Windowed = true;
presentParameters.SwapEffect = SwapEffect.Discard;
presentParameters.AutoDepthStencilFormat = DepthFormat.D24X8;
presentParameters.MultiSample = MultiSampleType.FourSamples;
presentParameters.EnableAutoDepthStencil = true;

I'm grateful for any advice.
Here is the mesh with the edges:

A: The latest windows ( 8 and + ) have seen major changes to swap chains and presentation. Newer direct-x API does not even authorize multisampled swap chains.
You may or may not do something weird here but it is hard to diagnoze without more details. I recommend to you to not create a multisampled swap chain buta regular one, create the multisampled surface separately (color + depth) and resolve the color to your backbuffer. It should solve your problem.


text:
Q: A quotient group obtained from an arbitrary set Let $G$ be a group and let $N$ be a normal subgroup of $G$. In addition suppose that $A$ is a subset of $G$ containing $N$, that is $N\subseteq A\subseteq G$. I wondering if it possible that $A/N$ form a group although $A$ doesn't form subgroup. My guess is that it is impossible, but i don't know how to prove it. Thanks!
p.s. In $A/N$ I mean $\{aN:a\in A\}$.

A: It is certainly possible, with the definition as you have written it -- consider $G = \mathbb Z/4\mathbb Z$, with $N = \{0,2\}$ and $A = \{0,1,2\}$. However, it is generally very unlikely, as there is no reason to assume why it would be so. In particular, for any $G$ you can take $N = \{1\}$, and in that case your question comes down to "is $A$ itself a subgroup"?

A: Let $A'$ be a subgroup of $G/N$ and $\pi$ the projection $G \rightarrow G/N$. Chose any map $\sigma : G/N \rightarrow G$ such that $\pi \circ \sigma = id_N$ (as guaranteed by the axiom of choice). Note that it is easy to chose $\sigma$ such that $A = \sigma(A')$ satisfies your conditions.


text:
Q: Deploying Java Application on Windows System I have created a Client-Server System using Sockets to send files over same network.
Now I have created their respective JARs. I have placed the option in context menu using regedit in my Windows 8

I use Batch script to direct argument from this context menu to Jar file. Here I am failing.
I am using this script to direct arguments

My Jar file recieves nothing as argument and intended purpose of placing it in context menu fails.

A: For deploying Java desktop apps., the best option is usually to install the app. using Java Web Start.  JWS works on Windows, OS X & *nix.

JWS provides many appealing features including, but not limited to, splash screens, desktop integration, file associations, automatic update (including lazy downloads and programmatic control of updates), partitioning of natives & other resource downloads by platform, architecture or locale, configuration of run-time environment (minimum J2SE version, run-time options, RAM etc.), easy management of common resources using extensions..

Launching a rich client app. using a batch script or from the command line seems so ..last millennium.

A: Try to write:
java -jar client.jar %1

or
java -jar client.jar %*

Anyways, remove ""


text:
Q: NoneType Error, Python I'm getting
TypeError: 'NoneType' object is not iterable

on this line:
temp, function = findNext(function)

and have no idea why this is failing. I am using function in while loops:
while 0 < len(function):
    …

but am not iterating through it. All of the returns in findNext(function) are pretty much
return 'somestring',function[1:]

and cannot understand why it thinks I'm iterating on one of those objects.

A: I am guessing that findNext falls off the end without returning anything, which makes it automatically return None.  Kind of like this:
>>> def findNext(function):
...     if function == 'y':
...         return 'somestring',function[1:]
...
>>> function = 'x'
>>> print(findNext(function))
None
>>> temp, function = findNext(function)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not iterable

The solution would be to always return something.

A: The statement:
return 'somestring',function[1:]

is actually returning a tuple of length 2 and tuples are iterables. It would be more idiomatic to write that statement as:
return ('somestring', function[1:])

which makes its tuple nature far more obvious.


text:
Q: How to iterate the array keys in vuejs? My code :

Archives :

{{  }}

Data from the server :
{
  archives: {
    2023: {
      1: ["3", "ABCD"]
    }
  }
}

Expected output :
archives: {
  2023: {
    1: ["3", "ABCD"]
  }
}

2023: {
  1: ["3", "ABCD"]
}

1: ["3", "ABCD"]

0: "3"

1: "ABCD"

I want to display the key on my screen. Here is the key I want to display  (2023 and 1) that I received as key. I don't know how to iterate the key. And also I want to display the value (ABCD, 3).

A: As per my understanding, You have an archives object and you want to print their keys along with the values in a recursive way with the help of v-for. I am assuming the expected output mentioned below.
Input object :
{
  archives: {
    2023: {
      1: ["3", "ABCD"]
    }
  }
}

Expected output :
2023: {
  1: ["3", "ABCD"]
}

1: ["3", "ABCD"]

0: "3"

1: "ABCD"

If my understanding is correct, Here is the live demo :

new Vue({
  el: '#app',
  data: {
    archives: {
      2023: {
        1: ["3", "ABCD"]
      }
    },
    keysArr: []
  },
  mounted() {
    this.iterateObject(this.archives);
  },
  methods: {
    iterateObject(obj) {
      Object.keys(obj).forEach(key => {
        if (typeof obj[key] === 'object') {
          this.keysArr.push({
            [key]: obj[key]
          });
            this.iterateObject(obj[key])
        } else {
            this.keysArr.push({
            [key]: obj[key]
          });
        }
      })
    }
  },
  computed: {
    Objectkeys() {
        return this.keysArr
    }
  }
})

Archives :

{{ item }}

A: You can use Object.keys method which will return the keys of an object as an array. In your case you can recursively call it inside of a function to iterate over nested object
const getKeys = (obj) => {
    Object.keys(obj).forEach((key) => {
        //
        if (type obj[key] == "object") {
            getKeys(obj[keys])
        }
    })
}


text:
Q: Xamarin Android Timer Issue Good morning person,
I created an app that needs a service in the background mounted a time every X. The problem is that it is not available to find a timer that has always ridden in the time that I decided.
I have already tried with: Handler + SendEmptyMessageDelayed, Handler + PostDelayed, ScheduledThreadPoolExecutor, System.Threading.Timer, System.Timers.Timer, Xamarin.Forms.Device.StartTimer.
Everyone has the same functioning without initiation, but after a while begins the wheel at different times. There is no test to run it every 3 minutes, usually it runs twice as well and then starts running every 5 minutes, then every 10 minutes and then every 15 minutes or it dies.
Does anyone know a "safe" timer?
Same example code:
public void StartPeriodicLocationTask()
{
    _timeSpan = TimeSpan.FromSeconds(_token.TempoTransmissao);
    _handler = new Handler(HandlerCallback);
    HandlerCallback(null);

    ScheduledThreadPoolExecutor scheduled = new ScheduledThreadPoolExecutor(3);
    _runnable = new Java.Lang.Runnable(OnRunTask);
    scheduled.ScheduleWithFixedDelay(
        _runnable
        , 0
        , _token.TempoTransmissao
        , TimeUnit.Seconds
    );

    TimerCallback timerDelegate = new TimerCallback(CheckStatus);
    Timer timer = new Timer(
        timerDelegate
        , 0
        , 0
        , (long)_timeSpan.TotalMilliseconds
    );

    System.Timers.Timer timer2 = new System.Timers.Timer();
    timer2.Interval = (long)_timeSpan.TotalMilliseconds;
    timer2.Elapsed += OnTimedEvent;
    timer2.Enabled = true;

    Xamarin.Forms.Device.StartTimer(_timeSpan, () =>
    {
        DebugText debug = new DebugText(
            "Device.StartTimer "
            , 7
        );
        TokenDataBase databaseRunTask = TempDataSource();
        databaseRunTask.SaveDebugTextAsync(debug);
        return true;
    });
}

public static void OnRunTask()
{
    DebugText debug = new DebugText(
        "ScheduledThreadPoolExecutor "
        , 3
    );
    TokenDataBase databaseRunTask = TempDataSource();
    databaseRunTask.SaveDebugTextAsync(debug);
}

public static void HandlerCallback(Message obj)
{
    DebugText debug = new DebugText(
        "HandlerOnRunTask"
        , 4
    );
    TokenDataBase databaseRunTask = TempDataSource();
    databaseRunTask.SaveDebugTextAsync(debug);
}

public static void CheckStatus(Object state)
{
    DebugText debug = new DebugText(
        "System.Threading.Timer"
        , 5
    );
    TokenDataBase databaseRunTask = TempDataSource();
    databaseRunTask.SaveDebugTextAsync(debug);

}

private void OnTimedEvent(
    object sender
    , System.Timers.ElapsedEventArgs e
)
{
    DebugText debug = new DebugText(
        "System.Timers.Timer"
        , 6
    );
    TokenDataBase databaseRunTask = TempDataSource();
    databaseRunTask.SaveDebugTextAsync(debug);

}

Result:


text:
Q: RxJava and retrofit and combining results I'm pretty new to RxJava and am struggling with how to compose Observables.
I need to make 2 requests (independently) and retrieve the 2 models from the 2 REST services.
The next step is to create a third model from the prior 2 models.
Here are my 2 Observables and a Function:
Observable<ProfileModel> userProfile(@Path("token") String token);
Observable<OnDemandRules> getRules();
Func2<OnDemandRules, ProfileModel, UserDetails> createUserDetails(final ProfileModel profileModel, final OnDemandRules onDemandRules)

I guess I need to create another Observer but I'm not sure how.

A: You can use zip(zipWith) to combine results from different Observables, such as
userProfile(...).zipWith(getRules, createUserDetails)


text:
Q: Kotlin + SimpleXMLElement + Map sublist element I'm developing an Android App with Kotlin. I need to consume an API that returns an XML to a request.
For example the returned XML is:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
   <soap:Body>
      <ListaEmpresasResponse xmlns="http://example.com/">
         <ListaEmpresasResult>
            <IdEstado>001</IdEstado>
            <Mensaje/>
            <Empresas>
               <Empresa>
                  <IdEmpresas>1</IdEmpresas>
                  <Nombre>Test 1</Nombre>
               </Empresa>
               <Empresa>
                  <IdEmpresas>2</IdEmpresas>
                  <Nombre>Test2</Nombre>
               </Empresa>
               <Empresa>
                  <IdEmpresas>4</IdEmpresas>
                  <Nombre>Test 3</Nombre>
               </Empresa>
               <Empresa>
                  <IdEmpresas>5</IdEmpresas>
                  <Nombre>Test 4</Nombre>
               </Empresa>
            </Empresas>
         </ListaEmpresasResult>
      </ListaEmpresasResponse>
   </soap:Body>
</soap:Envelope>

I'm able to parse the IdEstado and Mensaje fields but i need to create a list with the elements called "Empresa".
I have file called mapper.kt
interface Mapper<in R, out T> {

    fun transform(input: R): T
    fun transformList(inputList: List<R>): List<T>

}

I have a file called DatosTrabajoResponseEmpresaEntityMapper.kt
import com.example.smt.data.model.datostrabajo.DatosTrabajoResponseEmpresaEntity
import com.example.smt.data.model.datostrabajo.DatosTrabajoResponseEmpresaEntityEmpresa
import com.example.smt.data.model.datostrabajo.DatosTrabajoResponseEmpresaEnvelope
import com.example.smt.data.model.datostrabajo.Empresa
import kotlinx.android.synthetic.main.activity_datostrabajo.view.*

class DatosTrabajoResponseEmpresaEntityMapper: Mapper<DatosTrabajoResponseEmpresaEnvelope, DatosTrabajoResponseEmpresaEntity> {

    override fun transform(input: DatosTrabajoResponseEmpresaEnvelope): DatosTrabajoResponseEmpresaEntity {
        return DatosTrabajoResponseEmpresaEntity(
            input.body!!.listaEmpresasResponse!!.listaEmpresasResult!!.resultCode,
            input.body!!.listaEmpresasResponse!!.listaEmpresasResult!!.message,
            null<-- This is where i should parse the sublist where i'm not able to.
        )
    }

    override fun transformList(inputList: List<DatosTrabajoResponseEmpresaEnvelope>): List<DatosTrabajoResponseEmpresaEntity> {
        return inputList.map { transform(it) }
    }

}

class DatosTrabajoResponseEmpresaEntityMapperEmpresa: Mapper<Empresa, DatosTrabajoResponseEmpresaEntityEmpresa>{
    override fun transform(input: Empresa): DatosTrabajoResponseEmpresaEntityEmpresa {
        return DatosTrabajoResponseEmpresaEntityEmpresa(
            input.idEmpresas,
            input.nombre
        )
    }

    override fun transformList(inputList: List<Empresa>): List<DatosTrabajoResponseEmpresaEntityEmpresa> {
        return inputList.map { transform(it) }
    }
}

My response file DatosTrabajoResponseEmpresa.kit where i have the structure defined is:
import org.simpleframework.xml.Element
import org.simpleframework.xml.Namespace
import org.simpleframework.xml.NamespaceList
import org.simpleframework.xml.Root
import org.simpleframework.xml.ElementList

@Root(name = "soap:Envelope")
@NamespaceList(
    Namespace(prefix = "soap", reference = "http://schemas.xmlsoap.org/soap/envelope/"),
    Namespace(prefix = "xsi", reference = "http://www.w3.org/2001/XMLSchema-instance"),
    Namespace(prefix = "xsd", reference = "http://www.w3.org/2001/XMLSchema")
)
class DatosTrabajoResponseEmpresaEnvelope {
    @field:Element(name = "Body", required = false)
    var body: DatosTrabajoResponseEmpresaBody? = null
}

@Root(name = "soap:Body", strict = false)
class DatosTrabajoResponseEmpresaBody {
    @field:Element(name = "ListaEmpresasResponse", required = false)
    var listaEmpresasResponse: ListaEmpresasResponse? = null
}

@Root(name = "ListaEmpresasResponse", strict = false)
class ListaEmpresasResponse {
    @field:Element(name = "ListaEmpresasResult", required = false)
    var listaEmpresasResult: ListaEmpresasResult? = null
}

@Root(name = "ListaEmpresasResult", strict = false)
class ListaEmpresasResult {
    @field:Element(name = "IdEstado", required = false)
    var resultCode: String? = null

    @field:Element(name = "Mensaje", required = false)
    var message: String? = null

    @field:ElementList(name = "Empresas", required = false)
    var empresas: List<Empresa>? = null

}

@Root(name = "Empresa", strict = false)
class Empresa {
    @field:Element(name = "IdEmpresas", required = false)
    var idEmpresas: Int? = null

    @field:Element(name = "Nombre", required = false)
    var nombre: String? = null
}

And at last this is my entity file DatosTrabajoResponseEmpresaEntity.kt:
import android.annotation.SuppressLint
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize

@SuppressLint("ParcelCreator")
@Parcelize
data class DatosTrabajoResponseEmpresaEntityEmpresa(
    val idEmpresas: Int?,
    val nombre: String?
) : Parcelable

@SuppressLint("ParcelCreator")
@Parcelize
data class DatosTrabajoResponseEmpresaEntity(
    val resultCode: String?,
    val message: String?,
    val empresas: List<DatosTrabajoResponseEmpresaEntityEmpresa?>
) : Parcelable

At the end what i expect is to have an attribut in my entity with the list List my problem is that i tried to parse it but not able. I would appreciate any help.

A: I think i found the solution:
input.body!!.listaEmpresasResponse!!.listaEmpresasResult!!.empresas!!.map { it  }.map{ DatosTrabajoResponseEmpresaEntityEmpresa(it.idEmpresas, it.nombre) }

A: If you can afford to use beautifulsoup for java/kotlin, it's a lot easier. I used it to parse the xml files from openstreetmaps in a very simple way, like python. The name of the library is Jsoup.
In this link (https://jsoup.org/download) you can see how to add it by graddle, maven and the jar to download. The usage is pretty straight-forward. This is an example from this (http://www.gitshah.com/2018/02/using-jsoup-with-kotlin-to-parse-html.html) tutorial:
import org.jsoup.Jsoup
import org.junit.Test

class JsoupTest {

    @Test
    fun shouldParseHTML() {
        //1. Fetching the HTML from a given URL
        Jsoup.connect("https://www.google.co.in/search?q=this+is+a+test").get().run {
            //2. Parses and scrapes the HTML response
            select("div.rc").forEachIndexed { index, element ->
                val titleAnchor = element.select("h3 a")
                val title = titleAnchor.text()
                val url = titleAnchor.attr("href")
                //3. Dumping Search Index, Title and URL on the stdout.
                println("$index. $title ($url)")
            }
        }
    }
}

Don't forget to state that you want to use a xml parser, like it's said here (http://tonyjunkes.com/blog/parsing-xml-with-jsoup-in-cfml/).
doc = Jsoup.parse(rawXML, "", Parser.xmlParser());

You can validate the xml with a validator and a scheme using javafx like here (https://turreta.com/2018/06/24/kotlin-validate-xml-against-xsds/).
val factory: SchemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema")

val schemaLocation = File("/somewhere/xsd/myschema.xsd")
val schema = factory.newSchema(schemaLocation)
val validator = schema.newValidator()
val source = StreamSource("/somewhere/test-data/myxml-test.xml")

println("Validation Starts now!")

val start = System.currentTimeMillis()
try {
    validator.validate(source)
    println(" XML is valid.")
} catch (ex: SAXException) {
    println(" XML not valid because " + ex.message)
}

println("Validation complete!")

println("Time (ms): " + (System.currentTimeMillis() - start))

You can also use Jackson as stated here and as a bonus you get everything in dataclasses (https://medium.com/@foxjstephen/how-to-actually-parse-xml-in-java-kotlin-221a9309e6e8). This is the jackson's repository: https://github.com/FasterXML/jackson.


text:
Q: Some Buttons and Hover Effect Disabled I created an onboarding walkthrough tour for use in a SaaS App that is being loaded with A/B testing software. The tour automatically begins on initial page load. The user can close the tour at any time. I have used localStorage so the browser will recall at what point the user exits the page and that tour will start again at the further point in the tour. I also have a "replay" button that is disabled when the tour is running and enabled when the tour is finished or closed. The replay button's selector is ".tstour-replay". I am animating the movement of the tour steps by adding a class that is using CSS3 @keyframes rules and then delaying the removal of the class so that the animation will repeat if the user goes back and uses that Next animation again. Those are referred to as "popover-ani1", "popover-ani2" and so on.
I am having an issue that is not consistently happening so I cannot find a pattern that explains why it's happening. Sometimes, the Next and Back buttons of the individual tour modals, referred to in the code as #popoverid1, #popoverid2, and so on or #popoverback1, #popoverback2, and so on, will be disabled. They do not respond to clicks and they both have CSS hover effects that do not work properly. However, the close button, .popover-close, always works. I cannot figure out why sometimes the Next and Back buttons are just completely unclickable and lose their interactivity while the Close button is always fine.
I am fairly new to JavaScript and jQuery.
Here's my JavaScript code:
    function tourFunction() {

    $(".tstour-replay").addClass("tstour-replay-disable");
    $("#tstour-start").click(function(){
      //if clicked, do nothing
    });

  $("#popoverid1").click(function() {
    $(".popover1").addClass("popover1-ani").delay(200).fadeOut(50);
    $(".popover2").delay(250).fadeIn(50);
         setTimeout(function() {
         $(".popover1").removeClass("popover1-ani");
            }, 250);
});

 $("#popoverid2").click(function() {
   $(".popover2").fadeOut(50);
    $(".popover3").delay(50).fadeIn(50);
});

$("#popoverback2").click(function() {
  $(".popover2").addClass("popoverback2-ani").delay(200).fadeOut(50);
    $(".popover1").delay(250).fadeIn(50);
   setTimeout(function() {
         $(".popover2").removeClass("popoverback2-ani");
            }, 250);
});

$("#popoverid3").click(function() {
  $(".popover3").addClass("popover3-ani").delay(200).fadeOut(50);
    $(".popover4").delay(250).fadeIn(50);
          setTimeout(function() {
         $(".popover3").removeClass("popover3-ani");
            }, 250);
});

$("#popoverback3").click(function() {
  $(".popover3").addClass("popoverback3-ani").delay(200).fadeOut(50);
      $(".popover2").delay(250).fadeIn(50);
   setTimeout(function() {
         $(".popover3").removeClass("popoverback3-ani");
            }, 250);
});

$("#popoverid4").click(function() {
  $(".popover4").addClass("popover4-ani").delay(200).fadeOut(50);
    $(".popover5").delay(250).fadeIn(50);
          setTimeout(function() {
         $(".popover4").removeClass("popover4-ani");
            }, 250);
});

$("#popoverback4").click(function() {
  $(".popover4").addClass("popoverback4-ani").delay(200).fadeOut(50);
    $(".popover3").delay(250).fadeIn(50);
  setTimeout(function() {
         $(".popover4").removeClass("popoverback4-ani");
            }, 250);
});

$("#popoverid5").click(function() {
  $(".popover5").addClass("popover5-ani").delay(200).fadeOut(50);
    $(".popover6").delay(250).fadeIn(50);
          setTimeout(function() {
         $(".popover5").removeClass("popover5-ani");
            }, 250);
});

$("#popoverback5").click(function() {
  $(".popover5").addClass("popoverback5-ani").delay(200).fadeOut(50);
    $(".popover4").delay(250).fadeIn(50);
  setTimeout(function() {
         $(".popover5").removeClass("popoverback5-ani");
            }, 250);
});

$("#popoverid6").click(function() {
  $(".popover6").addClass("popover6-ani").delay(200).fadeOut(50);
    $(".popover7").delay(250).fadeIn(50);
          setTimeout(function() {
         $(".popover6").removeClass("popover6-ani");
            }, 250);
});

$("#popoverback6").click(function() {
  $(".popover6").addClass("popoverback6-ani").delay(200).fadeOut(50);
   $(".popover5").delay(250).fadeIn(50);
  setTimeout(function() {
         $(".popover6").removeClass("popoverback6-ani");
            }, 250);
});

}

function tourReplay() {
   $(".tstour-replay").removeClass("tstour-replay-disable");
     $("#tstour-start").click(function() {
          $(".tstour-replay").addClass("tstour-replay-disable");
            $(".popover1").fadeIn("fast");

  });
}

function disableTourReplay() {
   $(".tstour-replay").removeClass("tstour-replay-disable");
   $("#tstour-start").click(function() {
       //if clicked, do nothing
   });

}

//END FUNCTIONS

$(".popover-btn-start").click(function() {
  $(".tour-container").fadeOut();
  $(".popover7").fadeOut();
  $(".tstour-replay").removeClass("tstour-replay-disable");
       $("#tstour-start").click(function() {
             //if clicked, do nothing
       });
     tourReplay();
});

$(".popover-close").click(function(){
    $(".tour-container").fadeOut();
    $(".popover").fadeOut();
     tourReplay();
});

//BEGIN FUNCTION TRIGGERS

var trigger_flag = localStorage.getItem('tstour');

if (!trigger_flag) {

      disableTourReplay();
      $(".popover1").fadeIn("fast");
        tourFunction();

} else if (trigger_flag == '1') { //clicked next1

     disableTourReplay();
     $(".popover2").fadeIn("fast");
         tourFunction();

} else if (trigger_flag == '2') { //clicked next2
     disableTourReplay();
     $(".popover3").fadeIn("fast");
       tourFunction();

} else if (trigger_flag == '3') { //clicked next3
      disableTourReplay();
     $(".popover4").fadeIn("fast");
         tourFunction();

} else if (trigger_flag == '4') { //clicked next4

    disableTourReplay();
     $(".popover5").fadeIn("fast");
       tourFunction();

} else if (trigger_flag == '5') { //clicked next5

     disableTourReplay();
     $(".popover6").fadeIn("fast");
       tourFunction();

} else if (trigger_flag == '6' || '7') {  //got to last popover, finished tour or closed out
    tourReplay();
}

//END FUNCTION TRIGGERS

//BEGIN LOCAL STORAGE SET

$(document).on("click", "#popoverid1", function(e){
    localStorage.setItem('tstour', '1');
});

$(document).on("click", "#popoverid2", function(e){
    localStorage.setItem('tstour', '2');
});

$(document).on("click", "#popoverid3", function(e){
    localStorage.setItem('tstour', '3');
});

$(document).on("click", "#popoverid4", function(e){
    localStorage.setItem('tstour', '4');
});

$(document).on("click", "#popoverid5", function(e){
    localStorage.setItem('tstour', '5');
});

$(document).on("click", "#popoverid6", function(e){
    localStorage.setItem('tstour', '6');
});

$(document).on("click", ".popover-btn-start", function(e){
    localStorage.setItem('tstour', '7');
});

$(document).on("click", ".popover-close", function(e){
    localStorage.setItem('tstour', '7');
});

And here is the HTML

How Does This Work?

Employees On Your Calendar

Here's Jane Deaux, a sample employee. I preloaded some events for her in your calendar.

1 of 6

Next

Calendar Events

Notice Jane's name on the calendar. Each listing is a scheduled or pending calendar event.

Hover your mouse over her name to quickly see the event details.

2 of 6

Back

Next

Add a New Calendar Event

Double-click on any day to create a new calendar event. Use Jane to try it out and deduct hours from her time-off banks.

Give it a try. I'll wait right here until you're done.

3 of 6

Back

Next

Create More Calendar Events

Great job! You can also click this icon to create more calendar events.

4 of 6

Back

Next

Customize Your Calendar

Visit Preferences to customize your calendar event codes, create time-off plans, and much more.

5 of 6

Back

Next

Add More Employees

When you're ready, add more of your employees and create calendar events for them.

The more employees you load and track, the easier it is to avoid scheduling conflicts.

6 of 6

Back

Next

Ready to Take Back Your Time?

Start Tracking!

      I Need Some Help


text:
Q: Does age affect a Transformer's healing (repairing) capacity? In humans, the younger heal faster than the elderly. Is this also the case with Transformers?
Is there any evidence that younger Autobots/Decpticons heal (repair?!) quicker than their older friends?
I came up with this question from this post on a discussion regarding Bumblebee's recovery after the events of the first Transformers film. Bumblebee loses his legs in the first film, and yet is completely healed in the second part. However, Jazz, doesn't quite recover from a similar fate.
Also, in Revenge of The Fallen we can see that JetFire is in a really bad shape, seemingly because of his age.
The link to the discussion: How did Bumblebee heal after the events of Transformers the film.

A: It does. There is lack of evidence in the movies (and in the comics), since the healing process for a transformer is unclear.
Nevertheless, by the research you have done to get to that discussion, you probably know a little bit about the Transformers' healing process and about Transformers' technology.
Since the Transformers are  mechanical but living creatures (techno-organic?), their parts (the nanobots that act like their healing or immune system) and processes (programming and data) are subject to decay with time, thus becoming less efficient.
Of course their technology is highly advanced, so they have extraordinary lifespans, and highly efficient healing/auto-reparing capabilities. It wouldn't be until a Transformer is really old or gets seriously damaged that this process should get affected. When their own auto-healing mechanism is not enough, or to keep it in shape, they need to rely on their doctors, such as Ratchet.


text:
Q: Accessing an array with a negative number! I am converting an extremely large and very old (25 years!) program from C to C++.
In it there are many (very very many) places where I access a global one dimensional UBYTE array using a variety of integer indexes. Occasionally this index may be negative.
I sometimes, but not always, trapped this case and made sure nothing went wrong, but as a belt and braces measure I actually went to the trouble of making sure that there was another chunk of memory immediately preceding the array and filled it with the right values such that if I accidentally omitted to trap the negative number condition then a correct answer would still be fetched in the array access. This actually worked fine for many many years.
But now under C++ it seems that accessing an array with a negative number behaves differently and now I have a program behaving badly. I fixed one case of an unhandled negative number and the program appears to be working fine, but I am nervous that I have not trapped all the negative numbers and there may be problems ahead.
So my question now is, is there a way, at runtime, for me to detect any instances of accessing arrays with negative indexes? I'll be impressed if anyone can come up with an answer. If you're pretty certain it can not be done in any automated way then telling me that is valuable information too.
I should just add that I'm not really a C++ programmer (yet). So far all I've done is the absolute bare minimum (almost nothing) to get the program to compile under a C++ compiler. So if your answer involves fancy "experts only, C++ solutions", then please try and explain in words of one syllable or give me a link so I can look it up.

A: Do you know the bounds of the indices?
Reading the comment under Siyfion's answer, it seems like negative indices are allowed in your problem domain, and so there's no point in trying to force all indices to be positive. A better solution is to allow negative indices without breaking any language rules (which your C version also did btw. You were just lucky it didn't explode ;))
So if you know that the indices you're going to use are in the range -x to y, simply create an array of size x+y, and use a pointer to the xth element when accessing the array.
For example, assuming you need an array with indices -4 to 5:
int arr[10];
int* ptr = arr+4;
// use ptr when you need to index into the array:

ptr[-4]; // is valid, reads arr[0]
ptr[5]; // is valid, reads arr[9]

Of course the same could (and should) have been done in C.
Another piece of advice would be to not access the raw array directly. Define simple accessor functions instead. (for example, but not necessarily, by putting the array in a class. If you do put it in a class, you can overload operator[] so it'll even look like an array still)
The overhead of this is precisely zero (not "nearly zero, or "so close to zero you won't notice the difference", but zero. The generated code will be exactly the same as if you'd accessed the array directly), as the compiler will inline short functions, but it also allows you to insert extra checks so that you can verify in debug builds that you never go past the bounds of the array.

A: Some kind of memory usage checker might work, particularly if you can force the array to its own page. I'd use valgrind on Linux, not sure what you'd use on Windows - purify?

A: Wrap it. In alternative, check if your compiler supports boundary checking.
Worst case scenario, I would not put valid values in your array at negative numbers. I would put blatantly wrong values, so that you get a clearly wrong value when this occurs. You will not pinpoint the issue without a debugger, but at least you have a clear warning that somewhere, some code is doing it.

A:
Is there a way, at runtime, for me
  to detect any instances of accessing
  arrays with negative indexes?

Replace your global array by std::vector. Replace use of the array[index] syntax by
vector.at(index)

This does exactly what you ask for: it adds runtime array bound checks.

A: Can you replace the global one-dimensional ubyte array with an object with overloaded operator[]?  Using the absolute value of the int input might solve some of your issues.
Edit: Depending on the usage pattern of your array (no pointer shenanigans), using an object with overloaded operator[] could actually be entirely transparent to the users of the array, hence my suggestion.

A: the only way i can think of would be to wrap the array in a method that checks the index is positive.

A: Personally I'd try to sort out why any of your indices could ever be negative; it's obvious that they will return an incorrect value so surely you shouldn't let the index to go negative?
Fix the code that allows them to go negative rather than trying to make a square plug fit into a circular hole (so to speak) ;)

A: One thing you can do is you can check till what minimum value your indexes are going, and start filling your array from that index.
a[-i] = *(a - i)
so start with (a-i) as your base address instead of (a) so you will just shift your array and get desired values.

A: Look this example by MSDN:
Positive and Negative Subscripts


text:
Q: Telegram Bot sends same message many times PHP I am writing a telegram to the php bot, it works fine, but it sends the same message many times, it needs to be sent once, can anyone help me? here is my code
function chat_telegram( )
{
    $token = <token>;
    $telegram = "https://api.telegram.org/bot" . $token;
    $query = http_build_query([
        'chat_id' => <chat_id>,
        'text' => 'I love pizza'
    ]);

    $response = file_get_contents( $telegram . '/sendMessage?' . $query );
    return $response;
}


text:
Q: Flutter: StreamBuilder into ListView doubling list items when adding to it So I have a StreamBuilder which runs a query to Cloud Firestore for a list of documents. I then make each document into an item in my ListView and that works fine.
I am trying to edit the code because I want to add a search filter. I don't want to re-call data from Cloud Firestore each time a user is filtering the list.
So I decided to load all the data from Cloud Firestore into a list then use that list to build the ListView:
    builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
      //widget build for complated call
      if (snapshot.hasData) {
        for (var i = 0; i < snapshot.data!.docs.length; i++) {
          DocumentSnapshot doc = snapshot.data!.docs[i];
          GearItem tempItem = GearItem(
            doc['itemName'],
            doc['itemTemperatureRating'],
            doc['itemType'],
            doc['itemVolume'],
            doc['itemWeight'],
            doc['itemWeightFormat'],
            doc['manufacturer'],
            doc['packCategory'],
            doc.reference.id,
            doc['itemTempFormat'],
            doc['itemVolumeFormat'],
            doc['link'],
          );
          _listViewItems.add(tempItem);
        }

        //todo: cange ListView Builder to use new list
        return ListView.builder(
            itemCount: _listViewItems.length,
            itemBuilder: (context, index) {

This works initially. While the stream is open if I add an item to the list then I get the list loaded twice on itself and double all the items.
I cant figure out why the items get re-added to the _listViewItems list when the stream auto updates.
Updated:
Stream section of StreamBuilder:
stream: db
    .collection('GearLockerItems')
    .where('userId', isEqualTo: userID)
    .orderBy('itemName')
    .snapshots(),

Appreciate if someone can advise. Thank you in advance!

A: Every time there's a change to the data in Firestore, the stream fires an event with a QuerySnapshot that contains all data for that query/collection in the database.
The best option is to process snapshot.data!.docChanges, which allows you to see what changed between this QuerySnapshot and the previous one.
A much simpler fix is to keep processing the snapshot.data!.docs as you already, but clear _listViewItems before you process the new snapshot:
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
  // clear previous results
  _listViewItems.clear(); //

  //widget build for complated call
  if (snapshot.hasData) {
    for (var i = 0; i < snapshot.data!.docs.length; i++) {
      ...

      _listViewItems.add(tempItem);
    }
    ...


text:
Q: Notify when dropbox file is uploaded in PHP I have a Dropbox upload script, which works fine, however, I need to let the mail recipient know that a file has been/hasn't been uploaded to dropbox. Below is the code I am using...
<?
 if( ($_SESSION['security_code']==$_POST['security_code']) &&   (!empty($_POST['security_code'])) ) {
 mail("test@email.co.uk","Website Print Shop Enquiry","Form data:

 Contact Name: " . $_POST['field_1'] . "
 Company (if applicable): " . $_POST['field_2'] . "
 Address (optional): " . $_POST['field_3'] . "
 Postcode: " . $_POST['field_4'] . "
 Phone: " . $_POST['field_5'] . "
 Email: " . $_POST['field_6'] . "
 Dropbox File Uploaded?: " . >>RESULT HERE<< . "
 Details of enquiry: " . $_POST['field_7'] . " ",$headers);

 if ($_POST) {
   require 'DropboxUploader.php';

    try {
      // Rename uploaded file to reflect original name
       if ($_FILES['file']['error'] !== UPLOAD_ERR_OK)
         throw new Exception('File was not successfully uploaded from your computer.');

         $tmpDir = uniqid('/tmp/DropboxUploader-');
       if (!mkdir($tmpDir))
         throw new Exception('Cannot create temporary directory!');

       if ($_FILES['file']['name'] === "")
         throw new Exception('File name not supplied by the browser.');

       $tmpFile = $tmpDir.'/'.str_replace("/\0", '_', $_FILES['file']['name']);
       if (!move_uploaded_file($_FILES['file']['tmp_name'], $tmpFile))
         throw new Exception('Cannot rename uploaded file!');

       // Enter your Dropbox account credentials here
        $uploader = new DropboxUploader('username is here', 'password is here');
        $uploader->upload($tmpFile, $_POST['dest']);

      } catch(Exception $e) {
       }

// Clean up
     if (isset($tmpFile) && file_exists($tmpFile))
         unlink($tmpFile);

     if (isset($tmpDir) && file_exists($tmpDir))
         rmdir($tmpDir);
      }

  include("confirm-print.htm");
 }
else {
  echo "Invalid Captcha String. Please use the back button in your browser and try again, thank you.";
 }

?>

Trying to find what variable I need to access in order to show whether a file has been uploaded or not. The DropboxUploader.php file concerned is at https://github.com/jakajancar/DropboxUploader/blob/master/DropboxUploader.php Thanks for any help!

A: Look at line 92 in DropboxUploader.php If upload is unsuccessful, then exception is thrown with message "Upload failed!".
I suggest modify this file and change Exception class to something more specific like DropboxUploadException (of course define this exception subclass first). Then modify your code like this:
try
{
    // Your old code until "$uploader->upload($tmpFile, $_POST['dest']);"
    try
    {
        $uploader->upload($tmpFile, $_POST['dest']);

        $upload_success = true;
    }
    catch(DropboxUploadException $e)
    {
        $upload_success = true;
    }

    // At the very end move your mail() function call and you can use $upload_success
    // variable to display file upload success or failure
}
catch(Exception $e)
{
    // Generic exception handling
}

A: Sorted it! Used an if statement at the top of the PHP file...
if($_FILES['file']['name']==""){
        $result = "None"; //no file was uploaded
    }
    else
    {
        $result = "Yes";
    }


text:
Q: Android Facebook 4.0.1 invalid key hash error I have followed exactly what is told on facebook developer page for login by facebook in android. And my code works well. However When user log out and try to log in by facebook again it gives invalid key hash error. I dont know what is wrong with my code.
Manifest.xml
<application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:theme="@android:style/Theme.NoTitleBar" >
        <activity
            android:name="com.example.helltop.MainActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".GameActivity"
            android:screenOrientation="portrait"></activity>
        <activity
            android:name=".HelpActivity"
            android:screenOrientation="portrait"></activity>
        <activity android:name="com.facebook.FacebookActivity"
          android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
          android:theme="@android:style/Theme.Translucent.NoTitleBar"
          android:label="@string/app_name" />
         <meta-data android:name="com.facebook.sdk.ApplicationId"
                android:value="@string/facebook_app_id" />

        <meta-data
            android:name="com.facebook.sdk.ApplicationName"
            android:value="@string/facebook_app_name" />

        <provider android:authorities="com.facebook.app.FacebookContentProvider137..."
          android:name="com.facebook.FacebookContentProvider"
          android:exported="true"/>

    </application>

Login Activity
    CallbackManager callbackManager;
    LoginButton btnFbLogin;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        FacebookSdk.sdkInitialize(getApplicationContext());
        callbackManager = CallbackManager.Factory.create();

        setContentView(R.layout.loginactivity);

        btnFbLogin = (LoginButton) findViewById(R.id.btn_fblogin); btnFbLogin.setOnClickListener(this);btnFbLogin.setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, 0, 0);

        LoginManager.getInstance().registerCallback(callbackManager,
                new FacebookCallback<LoginResult>() {
                    @Override
                    public void onSuccess(LoginResult loginResult) {
                        fbLoginGetUserData(loginResult.getAccessToken());
                    }
                    @Override
                    public void onCancel() {
                        Toast.makeText(LoginActivity.this, "Facebook Login Canceled!" , Toast.LENGTH_SHORT).show();
                    }
                    @Override
                    public void onError(FacebookException error) {
                        Toast.makeText(LoginActivity.this, "ERROR : " + error.getMessage() , Toast.LENGTH_SHORT).show();
                    }
                });
        btnFbLogin.setReadPermissions(Arrays.asList("public_profile", "email", "user_birthday"));
        profileTracker = new ProfileTracker() {
            @Override
            protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {

            }
        };
    }

private void fbLoginGetUserData(AccessToken accessToken) {

        GraphRequest request = GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() {

            @Override
            public void onCompleted(JSONObject object, GraphResponse response) {
                if(response.getError() != null){
                    showAlert(response.getError().getErrorCode() + " : " + response.getError().getErrorMessage(), "Facebook Error!");
                } else {
                    // Get the data here
                }
            }
        });

        Bundle parameters = new Bundle();
        parameters.putString("fields", "id,first_name,last_name,link,birthday,email,gender,middle_name");
        request.setParameters(parameters);
        request.executeAsync();
    }

Here how I created my release keystore and hash key of my app for facebook.
keytool -genkey -alias myreleasekey-keyalg RSA -keystore %USERPROFILE%\.android\myapprelease.keystore -keysize 2048 -validity 10000

keytool -exportcert -alias myreleasekey -keystore ~/myapprelease.keystore | "C:\OpenSSL\bin\openssl" sha1 -binary | "C:\OpenSSL\bin\openssl" base64

A: public class MyApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        printHashKey();
    }

    public void printHashKey(){

        try {
            PackageInfo info = getPackageManager().getPackageInfo(
                    "com.parakhidevelopers.happydays",
                    PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                Log.d("Key Hash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
            }
        } catch (PackageManager.NameNotFoundException e) {

        } catch (NoSuchAlgorithmException e) {

        }
    }
}


text: Q: Sound problem Ubuntu 22.04 There is only dummy output in my azure Ubuntu vm.Can not open alsamixer.Shows no sound card to be configured in pavucontrol.How to solve.Please help.Using Ubuntu 22.04 but Ubuntu 20.04 also has that problem.


text:
Q: Seeded random number Ive been wondering for some time. Is there a good (And fast) way to make an number random while its seeded?
is there a good algorithm to convert one number into a seemingly random number.
A little illustration:
specialrand(1) = 8
specialrand(2) = 5
specialrand(3) = 2
specialrand(4) = 5
specialrand(5) = 1
specialrand(1) = 8
specialrand(4) = 5
specialrand(1) = 8

It would be very nice if the output could also be huge numbers.
As a note: I don't want to fill a array and randomize the numbers because I want to be able to feed it huge difference of numbers because I want the same output whenever I restart the program

A: You're not looking for a seeded random number. Instead what I think you're looking for is a hashing function. If you put in the same input and get the same output, that's not random.
If you're looking to generate a sequence of random numbers for a run, but have the same sequence generate from run to run, you can use a random number generator that generates the same sequence given the same seed value.
Thats how most basic pRNG's work. There are more cryptographically secure RNG's out there, but your standard Math.rand() should work to accomplish your needs.

A: Maybe pseudorandom number generators are what you are looking for.
For example the XORshift.
uint32_t xor128(void) {
   static uint32_t x = 123456789;
   static uint32_t y = 362436069;
   static uint32_t z = 521288629;
   static uint32_t w = 88675123;
   uint32_t t;

   t = x ^ (x << 11);
   x = y; y = z; z = w;
   return w = w ^ (w >> 19) ^ (t ^ (t >> 8));
}

You could create something like this:

*

*take a seed

*specialrand(5) is a function which takes the fifth random number from this seed

*or specialrand(5) is a function which gets the first random number from the seed+5

Maybe this is enough for your purpose.

A: Try setting a key or set of keys then writing a function with an equation to return a new number based on that key:
a very basic example would be:
function specialrand(value) {
key = array (1,2,4,6,8);
  for (k in key) {
      if (k%2 === 0) {
      value -= key[k] * value;
      } else {
      value += key[k] / value;
      }
  }
 return value;
}

however you could create a highly complex equation to generate your 'random' number and ensure you return the same number each time.

A: You can use Date functionality
Math.valueOfSeed = function(n)
    {
        return Number(new Date(n%9999, n%12, n%30, n%24, n%60, n%60, n%1000));
    };

alert(Math.valueOfSeed(1) + " = " + Math.valueOfSeed(1));
alert(Math.valueOfSeed(2) + " = " + Math.valueOfSeed(2));
alert(Math.valueOfSeed(15) + " = " + Math.valueOfSeed(15));
alert(Math.valueOfSeed(5555) + " = " + Math.valueOfSeed(5555));
alert(Math.valueOfSeed(21212121) + " = " + Math.valueOfSeed(21212121));
alert(Math.valueOfSeed(6554654654) + " = " + Math.valueOfSeed(6554654654));

test is here


text:
Q: Inverting a fraction I'm doing a complex analysis question and it is as follows

$$\int\limits_{c}\frac{1}{z(e^z-1)}dz$$

Using Maclaurin Series I simplified this expression upto this point:

$$f(z) = \frac{1}{z(e^z-1)} = \frac{1}{z^2+\frac{z^3}{2!}+\frac{z^4}{3!}+ \cdots}$$

To use the residue theorem I need to get $z^{-1}$ terms. Some guy at my class inverted (flipped) this. Can I have a little guidance how to get the $z^{-1}$ from this? :)
This is the flipped version of this fraction I found:

$$\frac{1}{z^2}\left(1-\left(\frac{z}{2!}+\frac{z^2}{3!}+\frac{z^3}{4!}\right)+\left(\frac{z}{2!}+\frac{z^2}{3!}+\frac{z^3}{4!}+\cdots\right)+\cdots\right)$$

Is this correct? Then how to get this?

A: $$f(z)=\left(\frac1{z^2}\right)\left(1+\frac z2+\frac{z^2}6+\cdots\right)^{-1}\\
=\left(\frac1{z^2}\right)\left(1-(\frac z2+\frac{z^2}6+\cdots)+(\frac z2+\frac{z^2}6+\cdots)^2-\cdots\right)\\
=z^{-2}(1-\frac z2+\frac {z^2}{12}+...)$$

A: There is no $z^{-1}$ term.  You should be able to show that $\lim_{z\to 0} z^2\frac 1{z(e^z-1)}$ is finite, so your integrand has a second order pole.


text:
Q: How to change the opacity of elements in css? I could probably figure out a way to do this in JS but im wondering if theres a way to do it in CSS.
What i have is a page of elements, rectangles to be exact and on hover I want to change the opacity of them. Currently i have this  :
.rectangle:hover{
    opacity:0.2;
}

Works great. But what i want to happen is on hover I want the one i hover over to have opacity full (1.0) and the rest to change to lower opacity (0.5). Something like this :
.rectangle:hover{
   opacity:1.0
      rectangle:nohover{
         opacity:0.5;
      }
}

I only want the opacity to change when on hover so setting the rectangles to have opacity 0.5 from the start is not what i need.

A: Try this:

.rectangle {
    width: 50px; height: 50px; background: red; border: 1px solid blue; margin: 5px;
}
.container { float:left }
.container:hover .rectangle {
    opacity: 0.2
}
.container:hover .rectangle:hover {
    opacity: 0.5
}

A: Please try adding a wrapping div.
.wrap:hover .rectangle{
  opacity:0.5;
}
.wrap:hover .rectangle:hover{
  opacity: 1;
}

A: You can do this if all the rectangle share a common parent.
#parent .rectangle {
    opacity: 0.2;
}

#parent:hover .rectangle {
    opacity: 0.5;
}

#parent:hover .rectangle:hover {
    opacity: 1;
}

A: edit: too slow :p
html

css
.rectangle {
  opacity:0.7;
}
.container:hover .rectangle {
  opacity:0.5;
}
.container:hover .rectangle:hover {
  opacity:1.0;
}

this should do the trick, as long as all rectangles have the same parent, and there's no other objects in the container

A: .rectangle{
   opacity : 0.5;
 }
.rectangle:hover{
   opacity : 1;
}


text:
Q: How to search on google map by city with gmaps4rails 2 and rails 4 I am using gmaps4rails v2 + rails 4 + ruby 2.0
and i want to implement search functionality on map
user will search by city and one marker should come on the map.
Is it possible with gem ? or what? any suggestion


text:
Q: Cannot access my website from outside my localhost I have test website on my system (MacBook Pro with Mac OSX Lion). The website is served by nginx listening on port 8000. The listen configuration is listen 8000 default, so it should be open to accept request on any ip.
I can access the server from localhost but I cannot even access it from other systems in the same LAN. I configured OSX firewall to allow incoming for nginx. In the firewall log I see no 'deny' reports, and also I see no 'allowed' reports. So, I suspect the connection is getting blocked even before reaching the firewall.
To test if my LAN is working fine, I installed nginx on another system in tha LAN. I could access that from my Mac. So, LAN is configured properly. What else could be the problem?

A: Try to ping your machine from another one. Also, try your IP:port combination, e.g. 192.168.1.1:8000 from another one to hunt down the problem.

A: Are both computers on the same network? If not, it can be a firewall inside betwen the two computers.
Does the computer you are trying to ping from have a firewall enabled? Can you ping google or any other computer in the same network for example from that computer?
Are you sure 192.168.1.1 is your MAC IP? (You can get this from Network Preferences or File Sharing in Sharing or using ifconfig on a terminal window)
After you get the right IP, try pingin from another computer in the same network.
Hope it helps.


text:
Q: Is there a way to define new HTML elements without document.registerElement()? In some browsers you can define new HTML elements with custom functionality and so on using the really uncompatible Document.registerElement() API. Is there a way to avoid using this API and create new HTML elements compatible with many browsers?

A: Uh, yes. Using the DOM standard:
document.createElement("element type")

You can (but I don't know why you would) use this to create non-standard elements. After that, they are just JavaScript objects, so you can customize them as you would any other object.

In an HTML document, the Document.createElement() method creates the
  HTML element specified by tagName, or an HTMLUnknownElement if tagName
  isn't recognized.

// Causes an HTMLUnknownElement to be created
var e = document.createElement("custom");

// Supports basic element interface
e.innerHTML = "I'm in a new <custom> element.";

// But, is a JS object like any other and so customized
// as such:
e.custom = function(){
  alert("custom operation");
};

// Is an element node (although invalid), so can be inserted into the DOM
document.body.appendChild(e);

// But, has custom functions:
e.custom();

A: Document.registerElement is deprecated now. Try this: https://developer.mozilla.org/en-US/docs/Web/API/CustomElementRegistry/define


text:
Q: I'm new to C and I am having a hard time with function computations Basically we had an exercise to create a function that computes the monthly charge of an electricity bill wherein the first 100000 kwh will charge 0.05 then the exceeding kwh will charge 0.03 I did not complete the exercise and decided to practice this problem but I'm stuck.
#include <stdio.h>
#define Aircon 261
#define Fan 12
#define TV 27
#define Ref 117

float computeTotalCharges(int usage, int consumption);

void main(){

    int qAircon, qFan, qTV, qRef, hAircon, hFan, hTV, hRef, usageHrs, kwh;
    float monthlyCharges;

    printf("Input qty of Aircon in Household: ");
    scanf("%d", &qAircon);
    printf("Input usage hrs per day: ");
    scanf("%d", &hAircon);
    printf("\nInput qty of Fan in Household: ");
    scanf("%d", &qFan);
    printf("Input usage hrs per day: ");
    scanf("%d", &hFan);
    printf("\nInput qty of TV in Household: ");
    scanf("%d", &qTV);
    printf("Input usage hrs per day: ");
    scanf("%d", &hTV);
    printf("\nInput qty of Refrigerator in Household: ");
    scanf("%d", &qRef);
    printf("Input usage hrs per day: ");
    scanf("%d", &hRef);

    usageHrs = (qAircon * hAircon) + (qFan * hFan)
                + (qTV * hTV) + (qRef * hRef);

    kwh = ((qAircon * hAircon) * Aircon)+ ((qFan * hFan) * Fan)
            + ((qTV * hTV) * TV) + ((qRef * hRef) * Ref);

    monthlyCharges = computeTotalCharges(usageHrs, kwh);

    printf("\nDescription\t\t\t    Qty\t    Hrs/Day\n");
    printf("Aircon \t\t\t\t%6d \t  %6d\n", qAircon, hAircon);
    printf("Fan \t\t\t\t%6d \t  %6d\n", qFan, hFan);
    printf("TV \t\t\t\t%6d \t  %6d\n", qTV, hTV);
    printf("Refrigerator \t\t\t%6d \t  %6d\n\n", qRef, hRef);
    printf("Total Usage(Hrs): \t\t\t  %6d\n", usageHrs);
    printf("Total Consumption(kwh): \t\t  %6d\n", kwh);
    printf("Total Charges: \t\tPesos \t\t %4.2f", monthlyCharges);
}

float computeTotalCharges(int usage, int consumption){

    int usageHrs1, kwh1;
    float monthlyBill;

    usageHrs1 = usage * 30;
    kwh1 = consumption * 30;
    monthlyBill = (kwh1 >= 100000) ? (100000 * 0.05) + ((kwh1 - 100000) * 0.03)
                                            : kwh1 * 0.05;

    return monthlyBill;
}

I only understood the how to compute if the consumption exceeds 100k part but for the computations of the usage and consumption I tried a lot of computations but I don't return a value for the monthly consumption and usage.
Edit: I put in my whole code. We were only allowed to use the ternary operator for the condition in the function and now I can't seem to return the value for usage and consumption when multiplied by 30.

A: As a beginner avoid shorthand "tricky" expressions (when you get more experience you will avoid them too). Split the expression into many logical lines which are easy to read and understand. Compiler will most likely emit the same or even better code.
double computeTotalCharges(double usage){

    double monthlyBill = 0.00;

    if(usage > 100000.0)
    {
        monthlyBill += (usage - 100000.0) * 0.03;
        usage = 100000.0;
    }
    monthlyBill += usage * 0.05;
    return monthlyBill;
}

A: Modify your function as below
float computeTotalCharges(int usage, float consumption)
{

       float monthlyBill = 0;
       if(consumption > 100000)
       {
           monthlyBill =  (consumption - 100000) * 0.03;
           consumption = 100000;
       }
       monthlyBill = monthlyBill + (consumption * 0.05);

      return monthlyBill;
}


text:
Q: Not able to connect to USB modem on Ubuntu 14.04 using wvdial I am using wvdial to connect to my MTS Ultra Modem on Ubuntu 14.04
I get this output on sudo wvdial mts
Cannot open /dev/ttyUSB0: No such file or directory

Here is my lsusb output :
Bus 002 Device 006: ID 05ac:0252 Apple, Inc. Internal Keyboard/Trackpad (ANSI)
Bus 002 Device 005: ID 05ac:8242 Apple, Inc. Built-in IR Receiver
Bus 002 Device 009: ID 05ac:821d Apple, Inc.
Bus 002 Device 004: ID 0a5c:4500 Broadcom Corp. BCM2046B1 USB 2.0 Hub (part of BCM2046 Bluetooth)
Bus 002 Device 003: ID 0424:2513 Standard Microsystems Corp. 2.0 Hub
Bus 002 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 003: ID 05ac:8509 Apple, Inc. FaceTime HD Camera
Bus 001 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 003 Device 003: ID 12d1:1446 Huawei Technologies Co., Ltd. E1552/E1800/E173 (HSPA modem)
Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

Here is my dmesg | tail output :
[ 2391.989570] scsi8 : usb-storage 3-1:1.0
[ 2391.989670] usb-storage 3-1:1.1: USB Mass Storage device detected
[ 2391.989756] scsi9 : usb-storage 3-1:1.1
[ 2392.988527] scsi 8:0:0:0: CD-ROM            HUAWEI   Mass Storage     2.31 PQ: 0 ANSI:    2
[ 2392.988966] scsi 9:0:0:0: Direct-Access     HUAWEI   TF CARD Storage  2.31 PQ: 0 ANSI: 2
[ 2392.990894] sr1: scsi-1 drive
[ 2392.991035] sr 8:0:0:0: Attached scsi CD-ROM sr1
[ 2392.991416] sr 8:0:0:0: Attached scsi generic sg2 type 5
[ 2392.991841] sd 9:0:0:0: Attached scsi generic sg3 type 0
[ 2392.994204] sd 9:0:0:0: [sdb] Attached SCSI removable disk

A: I slogged for days when i found it was this simple
First, run this command:
sudo wvdial.conf
This will set up the config file for you
Then run:
sudo wvdial
Shut down your wifi and run your browser and it will work,the problem is that the GUI for the network connections doesn't detect or is not able to connect to the modem but it is actually working.


text:
Q: Android webview fit all content to screen Hi I have a webview and I want it to fit to screen, such that the user does not have to scroll horizontally or vertically
I have searched before, many suggest the following but it only limits the width, user will still have to scroll vertically:
engine = (WebView) (findViewById(R.id.webView1));
engine.loadUrl(www.example.com);
engine.getSettings().setLoadWithOverviewMode(true);
engine.getSettings().setUseWideViewPort(true);

I tried another method, using scaling method, but it won't work..... I got the window width (1024 pixels) and the web content width was also 1024 pixels!! So the scaling did not work.... Is there any method to get the correct scale?
Or....is there any other way?....THANKS!!
// get the window width and height
    Point outSize = new Point();
    getWindowManager().getDefaultDisplay().getSize(outSize);
    width = outSize.x;
    height = outSize.y;
    Log.i("Menuboard", "width: " + Integer.toString(width) + ", height: "
            + Integer.toString(height));

WebViewClient client = new WebViewClient() {

        public void onPageFinished(WebView view, String url) {
            int x = engine.getWidth();
            int y = engine.getHeight();

            Log.i("Menuboard", "web width: " + Integer.toString(x)
                    + ", height: " + Integer.toString(y));

            int scale1 = width * 100/x;
            int scale2 = height * 100/y;

            Log.i("Menuboard", "Scale1: " + Integer.toString(scale1)
                    + ", Scale2: " + Integer.toString(scale2));

            if (scale1 < scale2) {
                engine.setInitialScale(scale1);
                Log.i("Menuboard", "scale1");
            } else if (scale1 > scale2) {
                engine.setInitialScale(scale2);
                Log.i("Menuboard", "scale2: " + Integer.toString(scale2));
            }
        }
    };

    engine = (WebView) (findViewById(R.id.webView1));
    engine.loadUrl(string);
    engine.getSettings().setBuiltInZoomControls(true);
    engine.setPadding(0, 0, 0, 0);
            engine.setWebViewClient(client);

Just some notes:
To scale the webview:
engine = (WebView) (findViewById(R.id.webView1));
engine.loadUrl(www.example.com);
engine.getSettings().setBuiltInZoomControls(true);
engine.setPadding(0, 0, 0, 0);
engine.setInitialScale(50); // 0 - 100 where 100 is full scale

To get window width and height:
Point outSize = new Point();
getWindowManager().getDefaultDisplay().getSize(outSize);
width = outSize.x;
height = outSize.y;

A: Use these following functions in Java:
webview.getSettings().setUseWideViewPort(true);
webview.getSettings().setLoadWithOverviewMode(true);

And these ones in Kotlin:
webView.settings.useWideViewPort = true
webView.settings.loadWithOverviewMode = true


text:
Q: Can we access the ArcMap Image Analysis tools using Python? Esri recently added a new Image Analysis window to ArcMap - it's found under > Windows in the main toolbar:

The Image Analysis window's Processing section simplifies the
  experience of applying complex processing and analysis techniques to
  layers of image and raster data in ArcMap. The tools provide one-click
  options to apply processes, such as clipping, normalized difference
  vegetation index (NDVI) creation, mosaicking, and exporting

Can we access these tools using Python?
Specifically, I want to automate the process of applying a Clip, then adding Functions to the clip, before exporting to a new layer.

A: You could save your functions in a raster function template and apply this template to other rasters using the Edit Raster Function tool (Standard or Advance license needed).