Q: How to send a lexicon to text-to-speech I'd like help with incorporating a new lexicon into the Azure Text-to-Speech API.
https://learn.microsoft.com/en-us/previous-versions/office/developer/speech-technologies/hh378492%28v%3doffice.14%29
I've successfully sent text and have gotten mp3 files that work. Now I'm trying to incorporate a lexicon with difficult pronunciations.
I'm using the Python SDK for Text-to-Speech and have few questions from the documentation.

*

*Is this reference 'lexicon Element SSML (Microsoft.Speech)' outdated?

*What URI do I use?

*When I use the instructions in this document, I get the following error message: Status code: 400. Something went wrong. Check your subscription key and headers. How do I fix or investigate this?

*What format does the lexicon have to be in? I saw an example in the document that referenced a lexicon in a .pls format. How do I create this? Here is the reference:
<?xml version="1.0"?>
<speak
version="1.0"
xmlns="http://www.w3.org/2001/10/synthesis"
xml:lang="en-US">
<lexicon
uri="c:\Test\whatchamacallit.pls"
type="application/pls+xml"/>
 Gimme the whatchamacallit. </speak>

Here's part of the Python that I'm using:
xml_body = ElementTree.Element('speak', version='1.0')
xml_body.set('{http://www.w3.org/XML/1998/namespace}lang', 'en-us')
lexicon = ElementTree.SubElement(xml_body, 'lexicon')
lexicon.set('uri', '/User/.../Desktop/MedLex.pls')
lexicon.set('type', 'application/pls+xml')


Q: Create conditional variables grouping by time and id I have a data frame that contains the product and destination (dest_prod) consumed by individuals (id), observed during different years (year) in the data frame df:
id <- c("1", "1", "1", "1", "2", "2", "2", "2", "3", "3", "3", "3")
year <- c("2000", "2001", "2002", "2003", "2002", "2003", "2004", "2005", "2001", "2002", "2003", "2005")
dest_prod <- c("FRA_coke", "FRA_coke", "USA_coke", "FRA_coke+USA_coke",
               "FRA_coke", "SPA_ham", "FRA_coke+SPA_ham", "GER_coke",
               "CHN_water", "CHN_oil", "CHN_water+CHN_oil+FRA_coke", "CHN_water+CHN_oil+FRA_coke")

df <- data.frame(id, year, dest_prod)

I would like to apply the following logic:

*

*Create a new variable "new_dest" if an individual consumes a prod_dest in year (t) that comes from a new destination (3 first letters of "dest_prod") than in year (t-1).

*Create a new variable "new_prod" if an individual consumes a prod_dest in year (t) that contains a new product (letters after the "_" symbol in "dest_prod") than in year (t-1).

Note!: If there is no observed year before (t) for a given individual or the last observation comes from 2 years or longer, I will assign "NA" value.
The new dataframe looks like df_mod:
new_dest <- c("NA", "0", "1", "1",
             "NA", "1", "1", "1",
             "NA", "0", "1", "NA")

new_prod <- c("NA", "0", "0", "0",
             "NA", "1", "1", "0",
             "NA", "1", "1", "NA")

df_mod <- data.frame(id, year, dest_prod, new_dest, new_prod)

I have tried to use ifelse in dplyr, but it does not work as it is impossible to capture the sense of time and group (id).
Any idea on how to create new_dest and new_prod in dplyr?

A: The first step is to parse the dest_prod column into a usable format:
library(tidyverse)

parsed <- df %>%
  mutate_at(c("id", "year"), as.integer) %>%
  separate_rows(dest_prod, sep = "[+]") %>%
  separate(dest_prod, into = c("dest", "prod"))

parsed
#> # A tibble: 18 × 4
#>       id  year dest  prod
#>    <int> <int> <chr> <chr>
#>  1     1  2000 FRA   coke
#>  2     1  2001 FRA   coke
#>  3     1  2002 USA   coke
#>  4     1  2003 FRA   coke
#>  5     1  2003 USA   coke
#>  6     2  2002 FRA   coke
#>  7     2  2003 SPA   ham
#>  8     2  2004 FRA   coke
#>  9     2  2004 SPA   ham
#> 10     2  2005 GER   coke
#> 11     3  2001 CHN   water
#> 12     3  2002 CHN   oil
#> 13     3  2003 CHN   water
#> 14     3  2003 CHN   oil
#> 15     3  2003 FRA   coke
#> 16     3  2005 CHN   water
#> 17     3  2005 CHN   oil
#> 18     3  2005 FRA   coke

Then:
parsed %>%
  # Add previous year's data in a list column
  nest_join(
    mutate(., year = year + 1L),
    name = "previous",
    by = c("id", "year")
  ) %>%
  # Check if any dest/prod appeared in previous year
  rowwise() %>%
  mutate(
    new_dest = !dest %in% previous$dest,
    new_prod = !prod %in% previous$prod,
  ) %>%
  # Set to missing if previous year was not observed
  mutate(
    across(c(new_dest, new_prod), replace, !nrow(previous), NA)
  ) %>%
  # Aggregate indicators on year level
  group_by(id, year) %>%
  summarise(
    new_dest = any(new_dest),
    new_prod = any(new_prod),
  )
#> # A tibble: 12 × 4
#> # Groups:   id [3]
#>       id  year new_dest new_prod
#>    <int> <int> <lgl>    <lgl>
#>  1     1  2000 NA       NA
#>  2     1  2001 FALSE    FALSE
#>  3     1  2002 TRUE     FALSE
#>  4     1  2003 TRUE     FALSE
#>  5     2  2002 NA       NA
#>  6     2  2003 TRUE     TRUE
#>  7     2  2004 TRUE     TRUE
#>  8     2  2005 TRUE     FALSE
#>  9     3  2001 NA       NA
#> 10     3  2002 FALSE    TRUE
#> 11     3  2003 TRUE     TRUE
#> 12     3  2005 NA       NA

A: If you do want to fight the way dplyr wants to work, here's a non-pivot solution :)
library(dplyr)
library(purrr)
library(stringr)

df %>%
  mutate(year = as.numeric(year)) %>%
  left_join(., mutate(., year = year + 1), by = c('id', 'year'), suffix = c('', '_previous')) %>%
  rowwise() %>%
  mutate(dests = str_extract_all(dest_prod, '\\w{3}_'),
         prods = str_extract_all(dest_prod, '_\\w+'),
         new_dest = max(map_int(dests, \(x) !str_detect(dest_prod_previous, x))),
         new_prod = max(map_int(prods, \(x) !str_detect(dest_prod_previous, x)))) %>%
  select(-c(dests, prods, dest_prod_previous)) %>%
  ungroup()

#> # A tibble: 12 × 5
#>    id     year dest_prod                  new_dest new_prod
#>    <chr> <dbl> <chr>                         <int>    <int>
#>  1 1      2000 FRA_coke                         NA       NA
#>  2 1      2001 FRA_coke                          0        0
#>  3 1      2002 USA_coke                          1        0
#>  4 1      2003 FRA_coke+USA_coke                 1        0
#>  5 2      2002 FRA_coke                         NA       NA
#>  6 2      2003 SPA_ham                           1        1
#>  7 2      2004 FRA_coke+SPA_ham                  1        1
#>  8 2      2005 GER_coke                          1        0
#>  9 3      2001 CHN_water                        NA       NA
#> 10 3      2002 CHN_oil                           0        1
#> 11 3      2003 CHN_water+CHN_oil+FRA_coke        1        1
#> 12 3      2005 CHN_water+CHN_oil+FRA_coke       NA       NA


Q: MYSQL:filter query based on user input Maybe this is a simple question but i am struggled to find the answer.
I am trying to implement a filter feature based on category,subject and medium fields value from the table art.
that means if user select only category the result will be the query
SELECT * FROM ART WHERE category=val
if user select category and subject it should be  SELECT * FROM ART WHERE category=val AND subject=val
and so on
But i don't how i dynamically build this query one approach is write all possible combinations query and  execute based on conditions but i don't think its a good approach

A: $sql=" SELECT * FROM ART where 1=1   ";

if(!empty($category) {
    $sql.=" and category= $value";
}

if(!empty($subject) {
  $sql.=" and subject= $value";
}

if(!empty($medium) {
   $sql.=" and medium= $value";
}

where 1=1 is just to keep the syntax correct else you need to have some login to add where accordingly as you can't add where in all three checks (will make incorrect sql string).
Read about sql injection. Use parameter binding to add parameter, this is just for you to get an idea, this will work but is vulnerable to sql injection

A: Try all the filters in the where condition with OR not AND as shown below
SELECT * FROM ART WHERE category=val OR subject=val OR medium=val;


Q: Decrpyting using pkcs#11 tool I'm trying too encrypt and decrypt using pkcs#11-tool
echo 'Hello word !' | openssl pkeyutl -encrypt -pubin \
                                                   -inkey pub.pem \
                                                   -pkeyopt rsa_padding_mode:oaep \
                                                   -pkeyopt rsa_oaep_md:sha512 \
                                                   -pkeyopt rsa_mgf1_md:sha512 \
                                                   -out encrypted.data

This work find but trying to decrypt it fail
pkcs11-tool --module  /usr/local/lib/softhsm/libsofthsm2.so --decrypt \
                                                   --mechanism RSA-PKCS-OAEP \
                                                   --input-file encrypted.data \
                                                   --label keyp \
                                                   --hash-algorithm SHA512 --pin Jojo

I'm having this error :
Using slot 0 with a present token (0x607f2e7f)
Using decrypt algorithm RSA-PKCS-OAEP
OAEP parameters: hashAlg=SHA512, mgf=MGF1-SHA512, source_type=0, source_ptr=(nil), source_len=0
error: PKCS11 function C_DecryptInit failed: rv = CKR_ARGUMENTS_BAD (0x7)
Aborting.

I'm following this tutorial : https://docs.nitrokey.com/nethsm/guides/pkcs11_with_pkcs11-tool and can't what wrong.


Q: Aligning multiple divs side by side I am trying to align multiple divs side by side.
I have searched stackoverflow and based my code on this: How to align two divs side by side using the float, clear, and overflow elements with a fixed position div/.
I've played around with it, and ended up with this css:
    .frontpageBoxLeft, .frontpageBoxRight {
  border-radius: 5px;
  border-color: lightgrey;
  background: #ffffff;
  height: 150px;
}

.frontpageBoxLeft {
  margin-bottom:15px;
  width: 750px;
  min-height: 100px;
  position: relative;
}

.frontpageBoxRight {
  width: 320px;
  float: right;
  height: 300px;
  position: relative;
  vertical-align: top;
}

.frontpageBoxContainer {
    width: 70%;
    height: 500px;
    position: absolute;
    top:0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
}

and this html:

NEWS FEED

     et eksempel på en kasse1

     et eksempel på en kasse2

     et eksempel på en kasse3

     et eksempel på en anden kasse

The result is this:
div alignment
I would like to be able to put multiple divs on the left side, and multiple divs on the right side.
Right now the code works fine when iam only using one right and one left div, but with multiple divs it act like in the picture.
Best regards.

A: I guess this might help you

div{
  width: 48%;
  height: 100px;
  background-color: red;
  float: left;
  margin: 1%;
}

or this one

div{
  width: 23%;
  height: 100px;
  background-color: red;
  float: left;
  margin: 1%;
}

A:

.frontpageBoxLeft,
.frontpageBoxRight {
  border-radius: 5px;
  border-color: lightgrey;
  background: #ffffff;
  height: 150px;
}

.left-container {
  float: left;
  width: 750px;
}

.frontpageBoxLeft {
  margin-bottom: 15px;
  width: 750px;
  display: inline-block;
  min-height: 100px;
  float: right;
  position: relative;
  outline: 1px solid red;
}

.frontpageBoxRight {
  width: 540px;
  float: right;
  height: 300px;
  position: relative;
  vertical-align: top;
  outline: 1px solid red;
}

.frontpageBoxContainer {
  width: 1300px;
  height: 500px;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
}

NEWS FEED

     et eksempel på en kasse1

     et eksempel på en kasse2

     et eksempel på en kasse3

     et eksempel på en anden kasse

A: Put float: left to the .frontpageBoxLeft selector will solve the problem.

A: *

*Try set the frontpageBoxContainer to position:relative

*Float the left AND the right Containers.

*set left or right Offset to the divs you want to align.


Q: Parse 6-byte IP/Port string to in_addr structure in c I'm trying to build a little bittorrent client to store data in the bittorrent dht.
Since much of the bittorrent functionality is not needed I'm trying to stay as simple as possible, since it only needs to function in a couple of limited use cases.
I'm trying to parse information about new nodes from a message, which I get from a bootstrap node. The information about each node is 26-bytes long. 20-bytes is node ID, 4 bytes IP address and 2 bytes port number. All the info is in binary.
I want to store the ip address and port number in a struct (myNode) which has got an in_addr parameter for the IP and unsinged short for the port.
typedef struct myNode {
   unsigned char id[21];
   struct in_addr ip;
   unsigned short port;
} myNode;

The parsing of the ID works fine. But the parsing of the IP and port fails. Sometimes it works, mostly it does not and never both work at the same time. I think there might be something wrong with the bitwise shift I'm doing, but I don't know what. When I printf the IP in hex after parsing I mostly get something like this:

0xffffed3a

So it seems like the first to shifts are not working. The other bits are correct. What am I doing wrong?
int get_nodes_from_find_node(char *msg, myNode *setme) {
  char *fnstr = "nodes";
  char *pos, *ptr;
  long lenNodes;
  int nrNodes, i = 0, k = 0;

  pos = strstr(msg, fnstr);           // Find nodes section.
  if(pos == NULL) { return -1; }
  pos += strlen(fnstr);

  lenNodes = strtoul(pos, &ptr, 10);  // Save the length of the nodes section in lenNodes
  nrNodes = lenNodes / 26;            // Get number of nodes, about which info is delivered.
  pos = ptr+1;                        // Set pos to first node.

  while(nrNodes > 0) {
    for(k=0;k<20;k++,pos++) {       // First 20 bytes are ID.
        setme[i].id[k] = *pos;
    }
    setme[i].id[20] = '\0';         // Make ID a Null-terminated string.

    setme[i].ip.s_addr = (*pos << 24) | (*(pos+1) << 16) | (*(pos+2) << 8) | *(pos+3);   // Next 4 bytes are IP in network byte order.
    pos += 4;

    setme[i].port = (*pos << 8) | *(pos+1);  // Last 2 bytes are port.
    pos += 2;

    nrNodes--;
    i++;
  }
  return 0;
}

A: Your problem is in (*pos << 24) | (*(pos+1) << 16) | (*(pos+2) << 8) | *(pos+3).
If any of the values in pos[0,...,3] is negative, then the entire expression is negative.


Q: BEM Convention with SASS - Problem to understand I am a beginner in front-end and I try to assimilate the notions of SASS and BEM.
I have great difficulty understanding the naming convention and how it is organized with SASS.
I wrote a product section which contains three div (column) which themselves contain child elements.
I have no idea how to organize the names well. For example the img are children of product__preview, but I'm tempted to name the class product__img .... but it looks like it's not correct? If there are several images in the product section but some of them must be different, how do we handle the names? (product__img seems to be too vague).
Do I need to add a product__preview__img class for special cases?
Can you help me correct this block so that I understand the naming correctly?
Thank you in advance!

Super Mario Odyssey

 Date:  2017

 Story:  Super Mario Odyssey[b] is a platform game developed and published by Nintendo for
            the Nintendo Switch on October 27, 2017. An entry in the Super Mario series, it follows Mario and Cappy,
            a sentient hat that allows Mario to control other characters and objects, as they journey across various
            worlds to save Princess Peach from his nemesis Bowser, who plans to forcibly marry her. In contrast to
            the linear gameplay of prior entries, the game returns to the primarily open-ended, 3D platform gameplay
            featured in Super Mario 64 and Super Mario Sunshine.[1]

 Review:

        <button class="product__btn btn-orange-tiger">Add to cart</button>
        <button class="product__btn btn-orange-tiger">Go to cart</button>
        <button class="product__btn btn-orange-tiger">Keep buying</button>

A: The structure you have now is perfectly fine and valid. Therefore, you would not want to use product__preview__img. You would be defeating the purpose of BEM if you were to create those kind of selectors as you would be creating complex/unorganised code. If you feel the name is vague, you could try product__img-preview as this still ties in with the block element selector and not a stacked block element selector.
One more thing I could suggest since you are using BEM and to utilise it fully, is to change your modifier class names for the buttons you have to product__btn product__btn--orange as it will help keep your code maintainable as you have the block element selector along side a modifier which is the orange button in this case.
.product {
  ...
  &__features {
    ...
  }
  &__btn {
     ...
     &--orange {
       ...
    }
  }
}

As you can see, the deepest nesting level is the modifiers of the block element.


Q: How to configure spring controller to use different objectMapper for the response (serialization) I configured my own ObjectMapper for my SpringBoot application, Let say the object mapper is something like below (simplified):
    @Bean
    @Primary
    public ObjectMapper objectMapper() {
        return new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

Since the ObjectMapper is a singleton, all my REST Controller use that same ObjectMapper.
But, there is some controller that I want to ignore the null value, but I want to keep the rest of my controller to send the null value response.
Is there a way to configure it? So the best result is I can configure something like this:

*

*Controller A,B,C -> ObjectMapper X (ignore null value)

*Controller D -> ObjectMapper Y (ignore empty value)

*Default (all other controller) -> ObjectMapper Z (return null value)

Requirement Note:

*

*I can't change the POJO since it's autogenerated, and I don't want to update the codegen lib or the mustache template for this.

*Specific content negotiation is not an option

A: In addition to your ObjectMapper annotated with @Primary
you can configure more ObjectMappers qualified with bean names of your choice.
@Bean
@Primary
public ObjectMapper objectMapper() {
    ObjectMapper objectMapper = new ObjectMapper()
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    return objectMapper;
}

@Bean("mySpecialObjectMapper")
public ObjectMapper anotherObjectMapper() {
    ObjectMapper objectMapper = new ObjectMapper()
            /*  do some other configuration */;
    return objectMapper;
}

Then you can refer to them in your controllers like this:

*

*Just giving @Autowired will inject the primary ObjectMapper.

*Giving @Autowired together with @Qualifier("anyName") will inject
the ObjectMapper configured with @Bean("anyName")
@Autowired
private ObjectMapper objectMapper;

@Autowired
@Qualifier("mySpecialObjectMapper")
private ObjectMapper otherObjectMapper;

A: Maybe you just need to use @JsonInclude(JsonInclude.Include.NON_NULL). Try to fix it in the response model level.


Q: how to hide blinking cursor in input text? I want to make something which would look like a select input but is actually not, here are the steps.
I made an <input type="text">.
I added a background-image, which will show a "select arrow", giving the impression that it's a select box.
I added a default value to this input.
There will be a hidden div which will SlideDown() right under this input when I click on it.
I tried the read only thing so that the value cannot be changed, but the blinking cursor will show up.
If I use disabled, the blinking cursor will not show up, but the .click() or .focus function in jQuery will not work. The drop down menu will not SlideDown().
How can I make it clickable while not showing the blinking cursor?
Here's the code

        Secret Question

        <input type="text" class="inputselect" id="secretquestion" name="secretquestion" value="Choose a Secret Question" tabindex=10 />

            test

CSS
.selectoptions
{
    display: none;
    background-color: white;
    color: rgb(46,97,158);
    width: 250px;
    margin:auto;
    border-style: solid;
    border-width:1px;
    border-color: rgb(46,97,158);
    font-size: 14px;
    text-align: center;
}

.inputselect {
    color: white;
    cursor: pointer;
    background-image: url('inputselect.png');
    padding-top: 5px;
    padding-bottom: 5px;
    padding-left:10px;
    padding-right:-10px;
    width:240px;
    border-style: solid;
    border-color: rgb(46,97,158);
    border-width: 1px;
}
.inputselect:hover {
    outline:none;
    color:aqua;
    cursor: pointer;
    background-image: url('inputselecthover.png');
}
.inputselect:focus {
    outline:none;
    color:aqua;
    cursor: pointer;
    background-image: url('inputselecthover.png');
}

A: I think this is a perfect solution: make the input wide enough, align right to screen right, thus make cursor and content locate at the outside of the screen, while it's still clickable

A: The color of the cursor matches the color of the text.
<input type="text" style="color: transparent">

If you actually want to show text in the input box (my, some people are needy), you can use a text shadow.


Q: Facebook Integration in IOS to fetch users data I had registered my application in facebook developers. I got app id and client key.
Is there any tutorials for an application to fetch users data?
Any third parties suggested ?

A: This tutorial is the best for me http://www.raywenderlich.com/44640/integrating-facebook-and-parse-tutorial-part-1

A: Why third party? What's wrong with Facebooks documentation? It's perfectly clear
https://developers.facebook.com/docs/ios/getting-started


Q: wxPython: How to Show status/progress window and update the progress from another python code? I have a regular python app (not wx) , and i want to add a wxStatusWindow (Guage Class) in order to show the progress in my App.
There are many examples in web for wxGuage /Status windows but in all examples the progress is handled within the wxFrame.
How can i call the statusWIndow from my python code while the python code is running ?
I did some reading...is it running on separate thread??
I will appreciate an example...how can i do that?
alternatively..I though of just opening a wxDialog from my app and showing info about the progress (and than closing it and raising another wxDialog with new info)...but again..
I need the message to be displayed and in parallel the code in my app to continue running..and than to be able to close the message box from my python app
any Idea's?
code examples?
10x
Yodash


Q: Problem when I try to move socket creation code to another activity? I have an android application created by eclipse.
This application works as a client connecting to a server wirelessly across a socket connection.
I have a problem with the code of socket creation.
When I try to move the code from an activity to another in my application, then it doesn't work.
Here is the first activity, where the code works:
public class MyNewAndroidActivity extends Activity {
    protected Socket socket;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        final Button button_connect = (Button) findViewById(R.id.button1);
        final Button button_disconnect = (Button) findViewById(R.id.button2);
        final Button b_forward = (Button) findViewById(R.id.b_forward);
        final Button b_backward = (Button) findViewById(R.id.b_backward);
        final Button b_right = (Button) findViewById(R.id.b_right);
        final Button b_left = (Button) findViewById(R.id.b_left);
        final Button b_stop = (Button) findViewById(R.id.b_stop);

        button_connect.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                try {
            // Create socket with time out
            //192.168.1.76
        // my code which I want to transfer it.
        int port = 2005;
    SocketAddress sockaddr = new  InetSocketAddress("192.168.1.15", port);

                      socket = new Socket();
                      int timeoutMs = 2000;
                      socket.connect(sockaddr, timeoutMs);

                    }

            catch (UnknownHostException e) {
                    // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                catch (SocketException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (SecurityException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        });

when I convert it to method in another activity then it doesn't work:
public class IBMEyes extends Activity implements SensorListener{
    protected static Socket socket;
    final String tag = "MyProject";
    String state ="off";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sm = (SensorManager) getSystemService(SENSOR_SERVICE);
        setContentView(R.layout.main);

       Button b_connect = (Button) findViewById(R.id.button1);
        b_connect.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

        SocketConnect();
}
        });

// here is my code that I've transferred it.
    public void SocketConnect() {
        // TODO Auto-generated method stub
        try {

       int port = 2005;
    SocketAddress sockaddr = new  InetSocketAddress("192.168.1.15", port);

              socket = new Socket();
              int timeoutMs = 2000;
              socket.connect(sockaddr, timeoutMs);

            } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            } catch (SocketException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            }

    }


Q: How to fix "unhashable type: 'list'" error I am trying to run a function to get column name corresponding to 2 in data frame
Input Dataframe:
df1
A|B|C|D

1|0|2|4

2|9|1|3

Output DataFrame:
A|B|C|D|new|

1|0|2|4|C|

2|9|1|3|A|

I have made the function but for some reason I am getting TypeError: ("unhashable type: 'list'", 'occurred at index 0')
def colname(x):
    b = (df1.loc[x]==2)
    return b.idxmax()

df1["new"]=df1.apply(colname,axis=1)


Q: JSF : convertNumber MonetaryAmount not working in dataTable I wanted to display MonetaryAmounts inside a dataTable. Curiously it doesn't work : the currencyCode appears to be empty (but not null).
Note : it works outside a dataTable for a single MonetaryAmount.
Tested with wildfly 25.0.1 (Mojarra 2.3.14.SP04) and Payara5
The bean :
@Named("dtBasicView")
@ViewScoped
public class BasicView implements Serializable {

    private List<MonetaryAmount> amounts;

    @PostConstruct
    public void init() {
        amounts = new ArrayList<>();
        CurrencyUnit unit = Monetary.getCurrency("EUR");
        MonetaryAmount amount = Monetary.getDefaultAmountFactory().setCurrency(unit).setNumber(200).create();
        amounts.add(amount);
    }

    public List<MonetaryAmount> getAmounts() {
        return amounts;
    }
}

Facelet :
<h:dataTable var="item" value="#{dtBasicView.amounts}" >
    <h:column>
       <f:facet name="header">Amount</f:facet>
       <h:outputText value="#{item.number}">
            <f:convertNumber currencyCode="#{item.currency.currencyCode}" type="currency" />
       </h:outputText>
    </h:column>
</h:dataTable>

It blows in java.util.Currency because the currencyCode is empty :
if (currencyCode.length() != 3) {
   throw new IllegalArgumentException();
}

Here is the error.
17:17:58,946 SEVERE [javax.enterprise.resource.webcontainer.jsf.application] (default task-11) Error Rendering View[/ui/data/datatable/basic.xhtml]: javax.faces.convert.ConverterException: j_idt303:j_idt305:0:j_idt307: Could not convert '200' to a string.
        at javax.faces.api@3.0.0.SP04//javax.faces.convert.NumberConverter.getAsString(NumberConverter.java:686)
        at com.sun.jsf-impl@2.3.14.SP04//com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.getFormattedValue(HtmlBasicRenderer.java:491)
        at com.sun.jsf-impl@2.3.14.SP04//com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.getFormattedValue(HtmlBasicRenderer.java:509)
        at com.sun.jsf-impl@2.3.14.SP04//com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.getCurrentValue(HtmlBasicRenderer.java:330)
        at com.sun.jsf-impl@2.3.14.SP04//com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeEnd(HtmlBasicRenderer.java:143)
        at javax.faces.api@3.0.0.SP04//javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:595)
        at javax.faces.api@3.0.0.SP04//javax.faces.component.UIComponent.encodeAll(UIComponent.java:1654)
        at deployment.primefaces-showcase-11.0.0.war//org.primefaces.component.column.Column.renderChildren(Column.java:90)
        at deployment.primefaces-showcase-11.0.0.war//org.primefaces.component.datatable.DataTableRenderer.encodeCell(DataTableRenderer.java:1356)
        at deployment.primefaces-showcase-11.0.0.war//org.primefaces.component.datatable.DataTableRenderer.encodeRow(DataTableRenderer.java:1272)
        at deployment.primefaces-showcase-11.0.0.war//org.primefaces.component.datatable.DataTableRenderer.encodeRows(DataTableRenderer.java:1179)
        at deployment.primefaces-showcase-11.0.0.war//org.primefaces.component.datatable.DataTableRenderer.encodeTbody(DataTableRenderer.java:1119)
        at deployment.primefaces-showcase-11.0.0.war//org.primefaces.component.datatable.DataTableRenderer.encodeTbody(DataTableRenderer.java:1072)
        at deployment.primefaces-showcase-11.0.0.war//org.primefaces.component.datatable.DataTableRenderer.encodeRegularTable(DataTableRenderer.java:401)
        at deployment.primefaces-showcase-11.0.0.war//org.primefaces.component.datatable.DataTableRenderer.encodeMarkup(DataTableRenderer.java:331)
        at deployment.primefaces-showcase-11.0.0.war//org.primefaces.component.datatable.DataTableRenderer.render(DataTableRenderer.java:106)
        at deployment.primefaces-showcase-11.0.0.war//org.primefaces.component.datatable.DataTableRenderer.encodeEnd(DataTableRenderer.java:97)
        at javax.faces.api@3.0.0.SP04//javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:595)
        at javax.faces.api@3.0.0.SP04//javax.faces.component.UIComponent.encodeAll(UIComponent.java:1654)
        at javax.faces.api@3.0.0.SP04//javax.faces.render.Renderer.encodeChildren(Renderer.java:152)
        at javax.faces.api@3.0.0.SP04//javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:566)
        at javax.faces.api@3.0.0.SP04//javax.faces.component.UIComponent.encodeAll(UIComponent.java:1647)
        at javax.faces.api@3.0.0.SP04//javax.faces.component.UIComponent.encodeAll(UIComponent.java:1650)
        at javax.faces.api@3.0.0.SP04//javax.faces.component.UIComponent.encodeAll(UIComponent.java:1650)
        at com.sun.jsf-impl@2.3.14.SP04//com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:468)
        at com.sun.jsf-impl@2.3.14.SP04//com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:170)
        at javax.faces.api@3.0.0.SP04//javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:132)
        at javax.faces.api@3.0.0.SP04//javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:132)
        at javax.faces.api@3.0.0.SP04//javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:132)
        at com.sun.jsf-impl@2.3.14.SP04//com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:102)
        at com.sun.jsf-impl@2.3.14.SP04//com.sun.faces.lifecycle.Phase.doPhase(Phase.java:76)
        at com.sun.jsf-impl@2.3.14.SP04//com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:199)
        at javax.faces.api@3.0.0.SP04//javax.faces.lifecycle.LifecycleWrapper.render(LifecycleWrapper.java:88)
        at javax.faces.api@3.0.0.SP04//javax.faces.webapp.FacesServlet.executeLifecyle(FacesServlet.java:708)
        at javax.faces.api@3.0.0.SP04//javax.faces.webapp.FacesServlet.service(FacesServlet.java:451)
        at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:74)
        at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:129)
        at deployment.primefaces-showcase-11.0.0.war//org.primefaces.showcase.filter.CharacterEncodingFilter.doFilter(CharacterEncodingFilter.java:41)
        at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
        at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
        at io.opentracing.contrib.opentracing-jaxrs2//io.opentracing.contrib.jaxrs2.server.SpanFinishingFilter.doFilter(SpanFinishingFilter.java:52)
        at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
        at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
        at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:84)
        at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
        at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.ServletChain$1.handleRequest(ServletChain.java:68)
        at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
        at org.wildfly.security.elytron-web.undertow-server@1.10.0.Final//org.wildfly.elytron.web.undertow.server.ElytronRunAsHandler.lambda$handleRequest$1(ElytronRunAsHandler.java:68)
        at org.wildfly.security.elytron-base@1.17.1.Final//org.wildfly.security.auth.server.FlexibleIdentityAssociation.runAsFunctionEx(FlexibleIdentityAssociation.java:103)
        at org.wildfly.security.elytron-base@1.17.1.Final//org.wildfly.security.auth.server.Scoped.runAsFunctionEx(Scoped.java:161)
        at org.wildfly.security.elytron-base@1.17.1.Final//org.wildfly.security.auth.server.Scoped.runAs(Scoped.java:73)
        at org.wildfly.security.elytron-web.undertow-server@1.10.0.Final//org.wildfly.elytron.web.undertow.server.ElytronRunAsHandler.handleRequest(ElytronRunAsHandler.java:67)
        at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.RedirectDirHandler.handleRequest(RedirectDirHandler.java:68)
        at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:117)
        at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
        at io.undertow.core@2.2.12.Final//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
        at io.undertow.core@2.2.12.Final//io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
        at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
        at io.undertow.core@2.2.12.Final//io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
        at org.wildfly.security.elytron-web.undertow-server-servlet@1.10.0.Final//org.wildfly.elytron.web.undertow.server.servlet.CleanUpHandler.handleRequest(CleanUpHandler.java:38)
        at io.undertow.core@2.2.12.Final//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
        at org.wildfly.extension.undertow@25.0.1.Final//org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
        at io.undertow.core@2.2.12.Final//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
        at org.wildfly.extension.undertow@25.0.1.Final//org.wildfly.extension.undertow.deployment.GlobalRequestControllerHandler.handleRequest(GlobalRequestControllerHandler.java:68)
        at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.SendErrorPageHandler.handleRequest(SendErrorPageHandler.java:52)
        at io.undertow.core@2.2.12.Final//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
        at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:280)
        at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:79)
        at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:134)
        at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:131)
        at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
        at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
        at org.wildfly.extension.undertow@25.0.1.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1544)
        at org.wildfly.extension.undertow@25.0.1.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1544)
        at org.wildfly.extension.undertow@25.0.1.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1544)
        at org.wildfly.extension.undertow@25.0.1.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1544)
        at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:260)
        at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:79)
        at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:100)
        at io.undertow.core@2.2.12.Final//io.undertow.server.Connectors.executeRootHandler(Connectors.java:387)
        at io.undertow.core@2.2.12.Final//io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:852)
        at org.jboss.threads@2.4.0.Final//org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
        at org.jboss.threads@2.4.0.Final//org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1990)
        at org.jboss.threads@2.4.0.Final//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1486)
        at org.jboss.threads@2.4.0.Final//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1377)
        at org.jboss.xnio@3.8.4.Final//org.xnio.XnioWorker$WorkerThreadFactory$1$1.run(XnioWorker.java:1280)
        at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.lang.reflect.InvocationTargetException
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:566)
        at javax.faces.api@3.0.0.SP04//javax.faces.convert.NumberConverter.configureCurrency(NumberConverter.java:775)
        at javax.faces.api@3.0.0.SP04//javax.faces.convert.NumberConverter.getAsString(NumberConverter.java:674)
        ... 86 more
Caused by: java.lang.IllegalArgumentException
        at java.base/java.util.Currency.getInstance(Currency.java:315)
        at java.base/java.util.Currency.getInstance(Currency.java:296)
        ... 92 more

Error with Payara5
[2022-11-30T18:18:45.713+0100] [Payara 5.2021.3] [WARNING] [] [javax.enterprise.web] [tid: _ThreadID=83 _ThreadName=http-thread-pool::http-listener-1(2)] [timeMillis: 1669828725713] [levelValue: 900] [[
  StandardWrapperValve[Faces Servlet]: Servlet.service() for servlet Faces Servlet threw exception
java.lang.IllegalArgumentException
        at java.base/java.util.Currency.getInstance(Currency.java:315)
        at java.base/java.util.Currency.getInstance(Currency.java:296)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:566)
        at javax.faces.convert.NumberConverter.configureCurrency(NumberConverter.java:775)
        at javax.faces.convert.NumberConverter.getAsString(NumberConverter.java:674)
        at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.getFormattedValue(HtmlBasicRenderer.java:491)
        at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.getFormattedValue(HtmlBasicRenderer.java:509)
        at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.getCurrentValue(HtmlBasicRenderer.java:330)
        at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeEnd(HtmlBasicRenderer.java:143)
        at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:595)


Q: What is the difference between Child and Element of a container? What is the difference between Child and Element of a container?
Why do the containers like Spark VGroup have different sets of methods for both Child and Elements?
Can anyone explain me the difference in the simplest way?
Thanks in advance..

A: The addChild method is used for adding a DisplayObject, which is a method from pure actionscript. So you would typically add Sprite, MovieClips etc. Widely used in action script based projects
The Flex classes like VGroup are written on top of the base actionscript classes, and therefore have an extra addElement method to be able to add an IVisualElement, which can also be an FXG for example, or other Flex based components such as UIComponent, Group etc.
However, I doubt that calling addChild on a VGroup will actually provide desired results and may result in errors.
Hope this answers your question.

A: The type IVisualElement and with it all the *Element methods from IVisualElementContainer were introduced in Flex SDK 4.0 as part of the spark layout and lifecycle features.
You are still free to build your own components based on UIComponents without having the spark features and only with the *Child methods.
All classes that extend DisplayObjectContainer of course inherit the *Child methods but in classes like Group (and SkinnableComponent) those methods have been overwritten to throw an error, as one needs to use the *Element methods to use the Spark features.
As Flex 4 supports using the MX layout as well as the Spark layout (there are options to use only one of them or both side by side when compiling) those methods could not be marked as deprecated in Group and SkinnableComponent, wich would at least trigger a compiler warning instead of a runtime error.


Q: How can I list the all Discord servers ID where my bot are in the console? | discord.js I tried on googling but all of the errors was "is not a function", that's because i'm using discord.js V12?
I can't find it on google, there is less question about this one. This was my code.
var serverArray = client.guilds.array();
for(i = 0; i < serverArray.length; i++) {
    console.log("Server ID: " + serverArray[i].id);
}

A: client.guilds.cache.forEach(guild => {
  console.log(`${guild.name} | ${guild.id}`);
})

A: let clientguilds = client.guilds.cache()
console.log(clientguilds.map(g => g.id) || "None")

This should do the trick! It's going to cache all the guilds your bot is in and then it will map the guilds as an array. We then get the id of each guild or, if it's not in any guilds "none".


Q: Can someone explain to me on runQueryOnBackgroundThread? Can someone just explain to me what is runQueryOnBackgroundThread as I already read through some sources but still not understand with it?
@Override
public Cursor runQueryOnBackgroundThread(CharSequence constraint){
    FilterQueryProvider filter = getFilterQueryProvider();
    if (filter != null){
        return filter.runQuery(constraint);
    }

    Uri uri = Uri.withAppendedPath(
                ContactsContract.CommonDataKinds.Phone.CONTENT_FILTER_URI, Uri.encode(constraint.toString()));

    return content.query(uri, CONTACT_PROJECTION, null, null, null);
}

A: A handle of my Activity in the Adapter and the runQuery call in the filter makes a call to startManagingCursor on the Activity whenever the runQuery is called. This is not ideal because a background thread is calling startManagingCursor and also there could be a lot of cursors remaining open until the Activity is destroyed.
I added the following to my Adapter which has a handle on the Activity it is used within
@Override
public void changeCursor(Cursor newCursor) {
Cursor oldCursor = getCursor();
super.changeCursor(newCursor);
if(oldCursor != null && oldCursor != newCursor) {
    // adapter has already dealt with closing the cursor
    activity.stopManagingCursor(oldCursor);
}
activity.startManagingCursor(newCursor);
}

This makes sure that the current cursor used by the adapter is also managed by the activity. When the cursor is closed by the adapter management by the activity is removed. The last cursor held by the adapter will be closed by the activity by way of it still be managed by the activity.


Q: How to unmount webcomponent used inside react component? I am using web component inside react component. when I unmount react component, it seems web component inside react component is not being unmounted properly, because when I mount the react component again, webcomponent props update method is being called and then throws error

Uncaught TypeError: Cannot read property 'appendChild' of null

I am using skate js to create webcomponent.
How to properly unmount the web component. please help, I would always be thakful.
Please let me know if any more information is required.

A: I solved this. The Widget component was not being unmounted properly. I have to remove it forcefully form dom using
Mozilla docs removeChild
After that it works fine.


Q: How can I print/echo/get all attributes from each of the objects in this code? How can I print/echo all properties/attributes values from all Country objects in this code? I thought of using 'foreach' but I don't know the sintaxis.
The echo statement is in the last line of code.
Thanks!
    <?php

   class Country {
  public $nombre;
  public $poblacion;
  public $idioma;
  public $moneda;
  public $economia;
  public $deporte;

}

$country1 = new Country ();
$country1->nombre = 'Argentina';
$country1->poblacion = '40 millones';
$country1->idioma = 'Castellano';
$country1->moneda = 'Peso argentino';
$country1->economia = 'Agro';
$country1->deporte = 'Futbol';

$country2 = new Country ();
$country2->nombre = 'USA';
$country2->poblacion = '200 millones';
$country2->idioma = 'Ingles';
$country2->moneda = 'Dolar estadounidense';
$country2->economia = 'Multiples industrias';
$country2->deporte = 'Basket,Baseball,Futbol Americano';

$country3 = new Country ();
$country3->nombre = 'Alemania';
$country3->poblacion = '50 millones';
$country3->idioma = 'Aleman';
$country3->moneda = 'Euro';
$country3->economia = 'Multiples industrias';
$country3->deporte = 'Futbol';

$countries = [$country1,$country2,$country3];

foreach ($countries as $country)
{

  **echo $country->¿? "
";**

}

A: foreach ($countries as $country) {
    foreach ($country as $k => $v) {
        echo $k . ': ' . $v . '
'; // nombre: Argentina ...
    }
}


Q: jquery-ajax-php: error message not shown on other empty input fields after it's updated I’m trying to validate post data using jquery and ajax for my registration form where an error message will be shown below each input fields. I manage to get the error message initially. But when some of the empty fields were updated with an input, the error message does not shown in the remaining empty field. Would somebody please be kind to point out if is there is any problem with below script?

regsiter.php

        <form action="register-handler.php" method="POST" id="reg-form">

            Username:

            <input type="text" name="username" id="username"  autocomplete="off">

            Password:

            <input type="password" name="password" id="password" >

            Confirm Password:

            <input type="password" name="conf_pass" id="conf_pass" >

            <input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
            <input type="submit" value="submit">

        </form>

register-handler.php
<?php
require_once 'core/init.php';
if(Input::exists()){
    if(Token::check(Input::get('token'))) {

        $validate = new Validate();
        $validation = $validate->check($_POST, array(
            'username' => array(
                'required' => true,
                'min' => 2,
                'max' => 20,
                'unique' => 'users'
            ),
            'password' => array(
                'required' => true,
                'min' => 6
            ),
            'conf_pass' => array(
                'required' => true,
                'matches' => 'password'
            )
        ));

        if($validation->passed()) {
            //register user
            $user = new User();

            $salt = Hash::salt(32);

            try {

                $user->create(array(
                    'username' => Input::get('username'),
                    'password' => Hash::make(Input::get('password'), $salt),
                    'salt' => $salt
                ));

                Session::flash('home', 'You have been registered and can now log in!');
                Redirect::to('index.php');

            } catch(Exception $e) {
                die($e->getMessage());
            }
        }
        else {
            //output errors
            header('Content-Type: application/json');
        echo json_encode($validation->errors());
            }
        }
    }
}
?>

validate.php
<?php
class Validate {
    private $_passed = false,
            $_errors = array()

    public function check($source, $items = array()) {
        foreach ($items as $item => $rules) {
            foreach ($rules as $rule => $rule_value) {

                $value = trim($source[$item]);
                $item = escape($item);

                if ($rule === 'required' && empty($value)) {
                    $this->addError($item, "{$item} is empty");
                } else if (!empty($value)) {
                    switch ($rule) {
                        case 'min':
                            if (strlen($value) < $rule_value) {
                                $this->addError($item, "{$item} must be a minimum of {$rule_value} characters.");
                            }
                            break;
                        case 'max':
                            if (strlen($value) > $rule_value) {
                                $this->addError($item, "{$item} must be a maximum of {$rule_value} characters.");
                            }
                            break;
                        case 'matches':
                            if ($value != $source[$rule_value]) {
                            $this->addError($item, "{$rule_value} must match {$item}");
                            }
                            break;
                    }
                }
            }

        }
        if (empty($this->_errors)) {
            $this->_passed = true;
        }
        return $this;
    }

    private function addError($key, $error) {
        $this->_errors[$key] = $error;
    }

    public function errors() {
        return $this->_errors;
    }

    public function passed() {
        return $this->_passed;
    }
}
?>


Q: setting low rlimit_nproc value doesn't allow even a single fork I am trying to use setrlimit to limit the number of processes a program can create. Here is my code:
struct rlimit limiter;
getrlimit( RLIMIT_NPROC, &limiter );
limiter.rlim_max = limiter.rlim_cur = 10;
setrlimit( RLIMIT_NPROC, &limiter );

int val = fork();
printf( "Error number %d\n", errno ); //gives 11
if( val == -1 ) {
    printf( "Fork failed\n" );
} else if( val ) {
    printf( "parent\n" );
} else {
    printf("child\n" );
}
return 0;

Since the value of rlim_max and rlim_cur is 10, my program should be allowed to fork 10 processes. But right now it is failing even for a single fork call. Though it works if I set the values to around 250. I don't understand why is that. I want a way to limit the number of forks to n.


Q: Silex: How to create a loop in Form The following lines of code get me a Silex Form. One text-field and one checkbox. The text-field contains the name of a team. The checkboxes should contain the username of a user, so that I can add them to the team.
$form = $app['form.factory']->createBuilder(FormType::class)
        ->add('name', TextType::class, array(
            'constraints' => array(new Assert\NotBlank(), new Assert\Length(array('min' => 4,'max' => 64))),
            'label' => 'Team Name',
            'required' => 'required',
            'attr' => array('class' => 'input-field', 'autocomplete' => 'off', 'value' => $team->data()->name),
            'label_attr' => array('class' => 'label')
        ))
        ->add('players', CheckboxType::class, [
                'constraints' => array(new Assert\NotBlank()),
                'label' => $player->username,
                'attr' => array('class' => 'input-field', 'value' => $player->username),
                'label_attr' => array('class' => 'label')
        ])
        ->add('submit', SubmitType::class, [
            'label' => 'Edit',
            'attr' => array('class' => 'submit'),
        ])
        ->getForm();

I can get my list of users using the following lines:
$user = new User()
$user->getList();

foreach($user->data() as $player){
        ->add('players', CheckboxType::class, [
                'constraints' => array(new Assert\NotBlank()),
                'label' => $player->username,
                'attr' => array('class' => 'input-field', 'value' => $player->username),
                'label_attr' => array('class' => 'label')
        ])
    }

However, I don't know how to combine these two parts, since the $form variable is defined in one 'line' with a ';' at the end. How can I break this $form into parts so that I can loop through my users and add a checkbox for every user?

A: The form is "generated" once you execute ->getForm(); so if you want to add anyfield before generating it, you should finish by ->getForm();
So your code should probably look like:
// add you "static" fields
$formBuilder = $app['form.factory']->createBuilder(FormType::class)
    ->add('name', TextType::class, array(
        'constraints' => array(new Assert\NotBlank(), new Assert\Length(array('min' => 4,'max' => 64))),
        'label' => 'Team Name',
        'required' => 'required',
        'attr' => array('class' => 'input-field', 'autocomplete' => 'off', 'value' => $team->data()->name),
        'label_attr' => array('class' => 'label')
    ))
    ->add('players', CheckboxType::class, [
            'constraints' => array(new Assert\NotBlank()),
            'label' => $player->username,
            'attr' => array('class' => 'input-field', 'value' => $player->username),
            'label_attr' => array('class' => 'label')
    ])
    ->add('submit', SubmitType::class, [
        'label' => 'Edit',
        'attr' => array('class' => 'submit'),
    ]);

 $user = new User();
 $user->getList();

// then add your "dynamic" fields

foreach($user->data() as $player) {
    $formBuilder->add('players', CheckboxType::class, [
            'constraints' => array(new Assert\NotBlank()),
            'label' => $player->username,
            'attr' => array('class' => 'input-field', 'value' => $player->username),
            'label_attr' => array('class' => 'label')
    ]);
}

// then generate your form
$form = $formBuilder->getForm();


Q: Facebook messenger webview not allow to access camera and audio I am developing a messenger chat bot, user get a doctor consultation url via bot.
Here is the payload I have use
"message": {
    "attachment": {
      "type": "template",
      "payload": {
        "template_type": "generic",
        "elements": [
          {
            "title": "Dr.ABC has initiaed the call. Click on the Call below to Join.",
            "subtitle": "NOTE: This link will expire in 30 minutes.",
            "image_url": "https://doctorconsult.com/images/doc.jpg",
            "buttons": [
              {
                "type": "web_url",
                "title": "Call",
                "url": "https://doctorconsult.com/patientconversation/665161e3-0f50-4930-aefb-404d5c3f584f",
                "webview_height_ratio": "full",
                "messenger_extensions": true,
                "webview_share_button": "HIDE"
              }
            ]
          }
        ]
      }
    }
 }

this send the web_url for doctor consultation URL ( that need access camera and audio ) when we open up URL in a browser this works, but when I open url using bot button click, it doesn't not allow camera and  audio. How do we allow to access camera and audio to "https://doctorconsult.com/" in messenger web view ?
I am getting permission issue when its loading inside messenger web view when accessing media
navigator.mediaDevices.getUserMedia(this.videoConstraints).then(stream => {
      this.localStream = stream;
      this.localVideoPlayer.srcObject = stream;
      this.localMediaReady = true;
      this.socketService.emitCallingToPatient({
        customerCode: this.conversation.customerCode,
        currentConversationCallId: this.currentConversationCallId
      });
    });

A: That's the expected behavior due to limitations applied to webviews loaded via the in-app-browser/Messenger/Facebook app.


Q: jquery refactor: traversing Here is some awesome code I'd like to make better.
select: function(event, ui)
  {
  jQuery(this).siblings('div.hidden_fields').children('.poly_id').val(ui.item.user)
}

It is part of a select in jquery UI autocomplete.

A: You could try this
jQuery('div.hidden_fields .poly_id',jQuery(this).parent()).val(...);

Remember you can always provide a context to a jQuery Selector
jQuery("someselector", context)


Q: MathGL libmgl.so.7.2.0 not found I have downloaded and compiled MathGL following the instructions on sourceforge without any errors occuring.
When I ran my first test-program:
(The <> brackets in line 1 seem so delete it but they are there in the code)
#include mgl2/mgl.h
    int main(){
    mglGraph gr;
    gr.FPlot("sin(pi*x)");
    gr.WriteFrame("test.png");
}

the compilation with g++ -lmgl went fine.
When trying to run the programm i get:
./a.out: error while loading shared libraries: libmgl.so.7.2.0: cannot open shared object file: No such file or directory
I triple checked to be sure and libmgl.so.7.2.0 is definetely in /usr/local/lib/.
I tried telling g++ this via the -L option but that didn't work either.
Any help would be greatly appreciated

A: g++ -lmgl -lpng /shitfile.cpp -o /shitfile

care friend


Q: How To Append String To Dictionary in Python within Forloop i need to append a value of string to a specific key in dictionary in python within forloop, and if the data in forloop is empty then give the value of empty string which i'm not able to get it right, here is some of the code,
top100 = {}

for product in product_list:
    title = product.xpath('a[@class="someClass"]/text()') # LIST of 100
    price = product.xpath('div[@class="someClass"]/text()') # LIST of 100

    # the value in the title is list of 100 title
    # more like ['title1', 'title2', ...] and so the price [100, 230, ...]

    # how to append each pairs of title and price so i have list of dictionary

    top100['title'].append(title)
    top100['price'].append(price)

print( top100)

output:
KeyError: 'title'

but i need something more like:
top100 = [{'title': 'title1', 'price': 'price1'},
          {'title': 'title2', 'price': 'price2'}
         ]

A: The top 100 variable should be a list, then append a dictionary
top100 = []

for product in product_list:
    title = product.xpath('a[@class="someClass"]/text()') # LIST of 100
    price = product.xpath('div[@class="someClass"]/text()') # LIST of 100

    top100.append({'title':title,'price':price})

print( top100)

A: You need to make top100 a list with many nested dictionaries, with the following code:
top100 = []
for product in product_list:
    title = product.xpath('a[@class="someClass"]/text()') # LIST of 100
    price = product.xpath('div[@class="someClass"]/text()') # LIST of 100
    top100.append({'title':title,'price':price})

A: Here for the another version of result
top100 = {'title':[],'price':[]}

for product in product_list:
    title = product.xpath('a[@class="someClass"]/text()') # LIST of 100
    price = product.xpath('div[@class="someClass"]/text()') # LIST of 100

    top100['title'].append(title)
    top100['price'].append(price)

print( top100)

This should output
{'title':[..., ..., ... ],'price':[..., ..., ...]}

A: thanks for the answer i was able to find my own solution,
top100 = []
for product in product_list:
    titles = product.xpath('a[@class="someLink"]/text()')
    prices = product.xpath('div[@class="somePrice"]/text()')

    for title, price, in zip(titles, prices):
        top100.append({'title':title, 'price':price})

output:
top100 = [{'title': 'title1', 'price': '100'},
          {'title': 'title2', 'price': '200'}]


Q: jQuery getting all input elements of type text where the id ends in "Source" I am trying to get all text boxes that have an id that ends in a particular string.
So far I have tried
$("input[id$='Source']").each(function() {

$("input[type=text][id$='Source']").each(function() {

and also
$("input[type=text] , [id$='Source']").each(function() {

none of these seem to work, could some one maybe point me in the right direction.
I have tried clearing my web browsers cache just to make sure it was not caching any old code.

A: This works:
<input type="text" id="mysource">
<input type="text" id="yoursource">
<input type="text" id="nope">

js (the context 'this' inside of the each function will be the matched elements):
$("input[type='text'][id$='source']").each(function() {
    console.log(this);
});

console result:
<input type="text" id="mysource">
<input type="text" id="yoursource">

A: Clean up your quotes and you should be OK -
$('input[id$="Source"]').each(function() {

$('input[type="text"][id$="Source"]').each(function() {

Here is an example fiddle - http://jsfiddle.net/C5v4H/


Q: Function overloading by function pointer there is a question about overloading functions. Look at this code:
#include<iostream>

void fv(int){}
void fc(const int){}
void fvr(int&){}
void fcr(const int&){}

void fm(void(*fun)(const int))
{
    std::cout << "Constant called" << std::endl;
}

//void fm(void(*fun)(int))
//{
//  std::cout << "non Constant called" << std::endl;
//}

void fm(void(*fun)(const int&))
{
    std::cout << "Constant ref called" << std::endl;
}

void fm(void(*fun)(int&))
{
    std::cout << "non Constant ref called" << std::endl;
}

int main()
{
    fm(&fc);
    fm(&fv);
    fm(&fvr);
    fm(&fcr);
    return 0;
}

if you uncomment void fm(void(*fun)(int)) function you find that compiler can't statically overload function by pointer on function that accept parameter by value and pointer on function that accept const value. Also, if you uncomment void(*fun)(const int) and comment void(*fun)(const int) then all compiles sucessfully. But, if we using references it compiles OK. Don't get why, could you explain me please? Does this mean that pointers to function that accept parameter by value and by const value is same types?
UPD:
Top-level const doesn't influence a function signature
There is a good explanation why top-level const should be removed.

A: Yes, top-level const will be just dropped. Error from gcc

redefinition of ‘void fm(void (*)(int))’

As you can see const is dropped.
Quote from N3376 8.3.5/5

After producing the list of parameter types, any top-level
  cv-qualifiers modifying a parameter type are deleted when forming the
  function type.

A: Yes you cannot overload functions based on the const ness of a non pointer / non-reference argument, see:
Functions with const arguments and Overloading
Which in turn implies that pointers to function that accept parameter by value and const value are same type.


Q: Staf Copy on same Machine : Error registering with STAF, RC: 10 I want to copy a file from one directory to another directory. For doing this I am using staf which gets invoked in one php script, but getting below error, even if I run staf command like below
[root@balveer ConfigManagement_phps]# /usr/local/staf/bin/staf local FS COPY FILE /prd/mdp/Config_Manager/Configuration_files/configfiles/PCEF1/pcef.conf tomachine 172.19.13.53 todirectory /prd/mdp/Config_Manager/Configuration_files/updatedconfigs/
Error registering with STAF, RC: 10

At the time of starting staf, it says staf initialized
Ping test also gives same error
[root@balveer bin]# STAF LOCAL PING PING

Error registering with STAF, RC: 10

I am running staf version 3.4.11 on RHEL 6.3

A: I did following :
$ echo "/usr/local/staf/lib" > /etc/ld.so.conf.d/staf.conf
$ ldconfig

Basically, adding STAF library path in /etc/ld.so.conf.d/staf.conf


Q: flex textflow dyniamic height In my flex application I have scenerio like this:
parent to child
Vbox->Canvas->Sprite->Textflow
In this scenerio now I need to have dynamic height of the textflow & its parents. Here the root parent is the itemrenderer of the datagrid I have.
I need the heights of rows to be adjust according the content in it.
Right now I am importing the xml to textflow, then getting the number of lines, text height. Then removing the textflow & adding it again with the measured height according to the number of lines & text height.
How can I achieve it without removing & adding it again, coz it is taking much time in updating?
Thanks in advance.

A: Right might be a little late to answer this but someone else may benefit.
On the canvas or display object housing the TextFlow and sprite add a creationComplete functon.
I don't know if this step is necessary, but it works for me. Add a label with the text thats going to go into TextFlow (with the same font and fontSize), add a creation complete listener to that as well.
Get the height and width from the newly created label e.target.width e.target.height (in the function listening to the creation of label). Set the displayObjects (in the above case Canvas) height and width to these values, then proceed to add the sprite and textflow.
Note: this was a lazy way for me, label uses measureText which would be a more efficent way of doing this.


Q: How to open multiple nodejs command prompts in windows? For a class, I am using a node js command prompt. In windows only when i search node js command prompt am I able to open the command prompt. This command prompt is basically the regular windows command prompt with edhanced features of node. For example I use the node js command prompt to do things like npm install, npm run serve, etc. I know that to open another window of regular windows command prompt, i can run start cmd.exe  but how so can I do with my node js command prompt?

A: On my machine if I run "Node Command Prompt" a 2nd time, it opens a 2nd window.

If you want to do the same thing, the shortcut that Node installs just runs:

C:\Windows\System32\cmd.exe /k "C:\Program Files\nodejs\nodevars.bat"

so you should be able to run that, assuming your node install location is Program Files\nodejs.

A: Open your environment variables config, and add these 2 directories to Path variable.
C:\Program Files\nodejs\
C:\Users\your_user_name\AppData\Roaming\npm

And then every time you open a regular cmd window, the node.js commands will be available to you.


Q: Hide installed app in android i want to hide the installed app by another app in android application, lets say user has installed 3rd party app called Skype, Watsapp, facebook etc...
is there a way we can hide and show them upon click of a button from another app?. i tried below code. No luck, nothing happened to my launcher
 PackageManager packageManager = context.getPackageManager();
ComponentName componentName = new ComponentName(context,
        LauncherActivity.class);
packageManager.setComponentEnabledSetting(componentName, PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
        PackageManager.DONT_KILL_APP);

But here i was not getting how to hide a particular application?, i also followed these SO link
but i could not get to know how to hide a perticular application.

A: To hide/unhide an app, your app need to be the DevicePolicyManager. You can find more information about the device policy manager at http://developer.android.com/reference/android/app/admin/DevicePolicyManager.html and you may need to use https://developer.android.com/reference/android/app/admin/DevicePolicyManager.html#setApplicationHidden(android.content.ComponentName,%20java.lang.String,%20boolean)
 DevicePolicyManager dpm =
            (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
 ComponentName ownerComponent = new ComponentName(context, DeviceAdminReceiverImpl.class);
 boolean newHiddenValue = true;
 dpm.setApplicationHidden(ownerComponent, packageName, newHiddenValue);


Q: Flutter/Dart security scans I'm looking for software/method to perform a security scan (looking for security vulnerabilities) on my apps being developed in Flutter. I'm having troubles find one that supports Dart. Has anyone been doing security scans and have any recommendations for what to use? Thanks.

A: There's no great security scanning support at the moment although there are some discussions. The first step would be for Google to start to track Dart vulnerabilities in their existing Open Source Vulnerability (OSV) database, you could watch or get involved here: https://github.com/google/osv/issues/62

A: I would suggest the open source framework called mobsf. It's great at scanning a mobile app. I have been using it ever since and I could start patching up my security vulnerability right away.
link : https://github.com/MobSF/Mobile-Security-Framework-MobSF

A: Mobile-Security-Framework-MobSF Great Tools For Doing Mobile Applications  Security Test

A: I appreciate this might be a necropost but for anyone else who comes across this, you could look into Black Duck (https://www.blackducksoftware.com/) for licensing risks and Checkmarx CxSAST (https://checkmarx.com/) for security issues. Both support Dart/Flutter code (we've integrated into our ADO pipelines).
These would be for organisations rather than individuals though.
For private projects, I guess you could look into this integration into SonarQube?


Q: daterangepicker Month and year hard to view I have the following daterangepicker code. the code is functioning however the Month, Year and toggle buttons are very hard to view. I am using a bootstrap theme that is not working well with this. I have been trying to figure out how to change the CSS to make the month, year and toggle buttons more viewable.
What I am seeing

This is what it should look like

<!-- Include Required Prerequisites -->
<script type="text/javascript" src="//cdn.jsdelivr.net/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="//cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
<!-- Include Date Range Picker -->
<script type="text/javascript" src="//cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.css" />

<form class="" action="{{ url_for('about') }}" name="Item_1" method="POST">
    <input style="width: 30%" type="text" name="daterange" value="01/01/2015 01/31/2015" />
    <button type="submit" class="btn btn-success">Submit</button>

    </form>

<script type="text/javascript">
$('input[name="daterange"]').daterangepicker(
{
    locale: {
      format: 'MM-DD-YYYY'
    },
    startDate: '01-01-2017',
    endDate: moment()
},
function(start, end, label) {
    console.log("A new date range was chosen: " + start.format('MM-DD-YYYY') + ' to ' + end.format('MM-DD-YYYY'));
});
</script>

A: Marking it here as an answer, since the comment worked. The color css attribute controls font-colors, including those for glyphicons. So the fix is to change the corresponding table elements and glyphicons to use color: #000 or color: black.
Adding !important simply ensures no other CSS files change the color (unless they use !important too and have priority, through either more specific selectors, or the same selectors but appearing after this rule - which was apparently not the case here).
.calendar-table, .glyphicon-calendar {color: #000 !important;}


Q: Declaring arrow functions as variables In a previous project using webpack and babel writing es2015 I was able to declare an arrow function with a name like this:
x = () => console.log("test");

Using a real function it would look like this:
fetch = () => {
      fetch(`https://www.data.com`)
      .then(response => response.json() {
        console.log(response);
      })}

However when trying to use this code in a browserify and gulp configuration I get the error

Unexpected token, expected ,

Can you tell me why this code only works when I use webpack?

A: You have a syntax error in your code. response => response.json() { } is invalid JS.
To log the response:
fetch('https://www.data.com')
  .then(response => console.log(response))

To convert the response to JSON before logging it:
fetch('https://www.data.com')
  .then(response => response.json())
  .then(json => console.log(json))


Q: How to create a list from existing list in python I am having a list in below format. How can i create another list from the existing one with just selected elements.
[{'UserDiscount': 0.0, 'CostTotalInvEOPAmount': 940.0, 'WeekEndingData': u'2016-10-08', 'WeeksOnHand': 0.0, 'UnitTotalInvEOPQuantity': 250.0, 'WeeksOfSales': 0.0, 'UnitCostAmount': 3.76, 'Week': u'2016 Wk 36', 'CostReceiptAmount': 940.0, 'UnitSalesQuantity': 0.0, 'UnitReceiptQuantity': 250.0, 'Demand': 0.0, 'InventoryBOP': 0.0, 'PEMDiscount': 0.0, 'ElasticLift': 0.0, 'StoreCount': 0, 'PriceStatus': 4, 'UnitOnOrderQuantity': None, 'ReceiptSizeContributions': [{u'sizeId': u'e1656ac7-1cc1-40ce-b485-989bba9d758d', u'contribution': 1.0}], 'CostSalesAmount': 0.0, 'LifeCycleProperties': {u'IsAtRegularPrice': False, u'IsAtMarkdown': False, u'IsFinished': False, u'IsPreSeason': True}, 'MardownDiscount': 0.0, 'RecommendedReceipt': 250.0, 'RecommendedReceiptSizeContributions': [{u'sizeId': u'e1656ac7-1cc1-40ce-b485-989bba9d758d', u'contribution': 1.0}], 'UnitTotalInvBOPQuantity': 0.0, 'CostOnOrderAmount': None, 'InventoryEOP': 250.0, 'CostTotalInvBOPAmount': 0.0, 'Receipt': 250.0, 'Sales': 0.0, 'LostSales': 0.0, 'TotalDiscount': 0.0, 'RetailSalesAmount': 0.0},
 {'UserDiscount': 0.0, 'CostTotalInvEOPAmount': 940.0, 'WeekEndingData': u'2016-10-15', 'WeeksOnHand': 0.0, 'UnitTotalInvEOPQuantity': 250.0, 'WeeksOfSales': 15.784951285314385, 'UnitCostAmount': 3.76, 'Week': u'2016 Wk 37', 'CostReceiptAmount': 0.0, 'UnitSalesQuantity': 0.0, 'UnitReceiptQuantity': 0.0, 'Demand': 0.0, 'InventoryBOP': 250.0, 'PEMDiscount': 0.0, 'ElasticLift': 0.0, 'StoreCount': 0, 'PriceStatus': 4, 'UnitOnOrderQuantity': None, 'ReceiptSizeContributions': [], 'CostSalesAmount': 0.0, 'LifeCycleProperties': {u'IsAtRegularPrice': False, u'IsAtMarkdown': False, u'IsFinished': False, u'IsPreSeason': True}, 'MardownDiscount': 0.0, 'RecommendedReceipt': 0.0, 'RecommendedReceiptSizeContributions': [], 'UnitTotalInvBOPQuantity': 250.0, 'CostOnOrderAmount': None, 'InventoryEOP': 250.0, 'CostTotalInvBOPAmount': 940.0, 'Receipt': 0.0, 'Sales': 0.0, 'LostSales': 0.0, 'TotalDiscount': 0.0, 'RetailSalesAmount': 0.0}]

My new list will having below elements.
[{'UserDiscount': 0.0, 'CostTotalInvEOPAmount': 940.0, 'WeekEndingData': u'2016-10-08', 'WeeksOnHand': 0.0, 'UnitTotalInvEOPQuantity': 250.0, 'WeeksOfSales': 0.0, 'UnitCostAmount': 3.76, 'Week': u'2016 Wk 36', 'CostReceiptAmount': 940.0, 'UnitSalesQuantity': 0.0, 'UnitReceiptQuantity': 250.0, 'Demand': 0.0, 'InventoryBOP': 0.0, 'PEMDiscount': 0.0, 'ElasticLift': 0.0, 'StoreCount': 0, 'PriceStatus': 4, 'UnitOnOrderQuantity': None, 'CostSalesAmount': 0.0,  'RecommendedReceipt': 250.0, 'RetailSalesAmount': 0.0},
 {'UserDiscount': 0.0, 'CostTotalInvEOPAmount': 940.0, 'WeekEndingData': u'2016-10-15', 'WeeksOnHand': 0.0, 'UnitTotalInvEOPQuantity': 250.0, 'WeeksOfSales': 15.784951285314385, 'UnitCostAmount': 3.76, 'Week': u'2016 Wk 37', 'CostReceiptAmount': 0.0, 'UnitSalesQuantity': 0.0, 'UnitReceiptQuantity': 0.0, 'Demand': 0.0, 'InventoryBOP': 250.0, 'PEMDiscount': 0.0, 'ElasticLift': 0.0, 'StoreCount': 0, 'PriceStatus': 4, 'UnitOnOrderQuantity': None,  'CostSalesAmount': 0.0, 'RecommendedReceipt': 0.0, 'RetailSalesAmount': 0.0}]

A: You have a list with two dictionaries. To filter the dictionaries you can try
    keep=[key1,key2] #keys you wanna keep
    newList = []
    for item in mylist:
        d = dict((key,value) for key, value in item.iteritems() if key in keep)
        newlist.append(d)
    del mylist

Also using funcy you can do a
   import funcy
   mydict={1:1,2:2,3:3}
   keep=[1,2]
   funcy.project(mydict,keep)
=> {1: 1, 2: 2}

which is much prettier imho.

A: You could use the list comprehension https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions
[l for l in your_list if l['UserDiscount'] >= 1 ]
[{'UserDiscount': l['UserDiscount'],'CostTotalInvEOPAmount': l['CostTotalInvEOPAmount']}  for l in your_list ]

Using this way you can filter the elements in your list and change the structure of your dicts in the list


Q: PHP Select random second value I have a file called file.txt and inside I have this text:
Text 1
Vivamus arcu neque, ullamcorper vel eleifend id, euismod viverra nisi.

Text 2
Cras posuere neque vitae fringilla lobortis.

Text 2
Phasellus eu sapien sit amet diam eleifend ultricies a vitae tellus.

Text 3
Nulla at ipsum et quam euismod porttitor sit amet sed odio.

I select from this file 'Text 2' line and description under that line.
I want to select a random 'Text 2' line and its description not all of them. I tried to break that but it shows me only the first value of course and I tried to shuffle %trimmed but it didn't worked as I expected.
$trimmed = file('file.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

$value = 2;

foreach ($trimmed as $line) {

    if ($line == "Text $value") {
        echo $line."
";
        echo current($trimmed);
    }
}

Thanks

A: Try this, it might be bulky :
<?php

  function get_random_line($number, $file='file.txt'){

    $trimmed = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $string = "Text $number";

    $array = array();
    foreach ($trimmed as $key => $line) {

      if($key % 2 == 0){
        $arr_key = $line;
        if(!array_key_exists($arr_key,$array)){
          $array[$arr_key]['total'] = 0;
        }
      }else{
        $array[$arr_key]['total']++;
        $array[$arr_key]['rows'][] = $line;
      }

    }
    if(key_exists($string,$array)){
      $key = array_rand($array[$string]['rows'],1);
      return $array[$string]['rows'][$key];
    }else
    {
      return 'Provide a Valid Key';
    }

  }

  echo '
';
  print_r(get_random_line(3,'file.txt')); // Get Random Lines based on Label Value
  echo '
';

?>


Q: Long waiting time between PHP and Oracle OCI I installed XAMPP on Windows server. There are 2 application on my server:
First Application: PHP and MySQL application. This application runs quickly without and waiting time between links/pages.
Second Appilcation: PHP and Oracle application. I use “Oracle Instant Client (OCI) for Windows (32 bit)” to connect Oracle Server (on another machine). I have 8 tables with max 1000 row-data on each table. My queries are very simple. Everyting is working correctly when querying my Oracle database.
But, sometimes I’m waiting more than 20 seconds between pages/links. The is too much time to recieve page. This mostly occurs when entering the site for the first time. Additionaly, it occurs when trying to click on another page or link in application, after waiting 5-10 minutes on a page.
How can I reduce or terminate this delay when connecting Oracle database using OCI?

A: How are you connecting? If you are using oci_connect, then that's probably a large part of the problem - switch to oci_pconnect.
Failing that, do make sure that DNS A and PTR records are available for both ends (or make sure you're only using ip addresses rather than names to connect).
C.


Q: Swift 2.2 - uploadTaskWithRequest - How can I upload a text file from my app to my server I'm really struggling to upload a text file from my apps documents directory to my php script. All I want to do is upload a text file from the app onto my server.
The Apple documentation makes it sound so simple but its just not in depth enough and I can't get it working so I'm hoping someone may be able to help.
Filtering out some of the classes and functions here is the main part of what I have in Swift 2.2:
lazy var config: NSURLSesionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
lazy var session: NSURLSession = NSURLSession(configuration: self.config, delgate: self, delegateQueue: NSOperationQueue.mainQueue())

let phpURL = "https://test-server.test/upload.php?"

let uploadStringURL: NSURL = NSURL(string: phpURL)!
let uploadRequest = NSMutableURLRequest(URL: uploadStringURL)

let fileManager = NSFileManager.defaultManager()
let docs = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .userDomainMask).first
let fullFilePath = docs!/URLByAppendingPathComponent("upload.dat")

uploadRequest.HTTPMethod = "POST"

let uploadTask = session.uploadTaskWithRequest(uploadRequest, fromFile: fullFilePath, completionHandler: {(let data, let response, let error) in

})

uploadTask.resume()

The uploadTask should be pushing the file to the server and it gets a response 200 showing that it was successful.
Here is the PHP part which I think is where the problem may lie:
<?php
    $target_dir = "/var/www/html/test-files/uploads";

    $target_dir = $target_dir . "/" . basename($_FILES["file"]["name"]);

    echo '{"target":'.$target_dir.'},';
    echo '{"base":'.basename($_FILES["file"]["name"]).'}';

    if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_dir)) {
        echo json_encode([
             "Message" => "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.",
             "Status" => "OK"
        ]);
    }

    else {

        echo json_encode([
            "Message" => "Sorry, there was an error uploading your file.",
            "Status" => "Error"
        ]);

    }
?>

I don't know too much about PHP but the $_FILES variable is blank.


Q: Is it possible to use .NET 4.6.1 for Xamarin on Mac? I want to use .NET PCL library from a NuGet that target .Net 4.6.1 in Xamarin PLC project.
I can add it to the project, it will build fine. But, I cannot reference it in the project itself, it just doesn't allow because of .NET versions differences. The maximum version that I can set for my PCL projects is 4.5.
I can select 4.5.1 for example but it will jump back to 4.5 due to missing profiles for that version.
I was not able to find those profiles or update .NET Framework.
If I'm doing something completely dumb, please, tell me :)

A: If you are using visual studio 2017, you need to go to the visual studio installer, and select a few more checkboxes:


Q: How to set up IRIS database with Quarkus I'm trying to use Intersystems IRIS Database with
Quarkus, but I'm getting problems making it work
does anyone knows how to set up the Intersystems IRIS Database
on Quarkus ?
I did that on my pom.xml  and also I added the jar
hibernate-iris-1.0.0.jar and intersystems-jdbc-3.2.0.jar but it's not working
<dependency>
            <groupId>com.intersystems</groupId>
            <artifactId>intersystems-jdbc</artifactId>
            <version>3.2.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/src/main/resources/intersystems-jdbc-3.2.0.jar</systemPath>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-iris</artifactId>
            <version>1.0.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/src/main/resources/hibernate-iris-1.0.0.jar</systemPath>
        </dependency>

This is my application.properties

quarkus:
  datasource:
    db-kind: other
    username: _system
    password: *****
    jdbc:
      url: jdbc:IRIS://localhost:1972/USER
      driver: com.intersystems.jdbc.IRISDriver
  hibernate-orm:
    dialect: org.hibernate.dialect.InterSystemsIRISDialect
    jdbc:
      timezone: UTC

A: I found the solution, to set up Intersystems IRIS on Quarkus you need to add manually the jar file, and also you need to set up the pom.xml also some setup from Intersystems was made as a java class.  you can see the solution looking at my project on GitHub
this is the link: https://github.com/JoseAdemar/quarkus-project-with-intersystems-ris-database


Q: Unknown provider error when trying to inject a service from another module I've seen several posts on unknown provider errors but none of them have addressed my particular problem. I'm getting the following error:
Error: [$injector:unpr] Unknown provider: userAccountResourceProvider <- userAccountResource <- AdminUserAccountsCtrl

Here is my index.html:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1">

User Accounts

                            Username
                            Full Name

                            {{ account.username }}
                            {{ account.firstName}} {{ account.lastName }}

Here is my app.js;
(function() {
    "use strict";

    var app = angular.module("rpms",
                             ["common.services"]);

}());

Here is my second module - common.services.js:
(function() {
    "use strict";

    angular
        .module("common.services",
                ["ngResource"]);
}());

And here is my userAccountResource service declaration in the common.services module:
(function() {
    "use strict";

    angular
        .module("common.services")
        .factory("userAccountResource"
                 ["$resource",
                  userAccountResource]);

    function userAccountResource($resource) {
        return $resource("/api/accounts/:accountId");
    }

}());

Finally, here is my AdminUserAccountsCtrl controller declaration - using this is causing the error:
(function() {
    "use strict";

    angular
        .module("rpms")
        .controller("AdminUserAccountsCtrl",
                    ["userAccountResource",
                     adminUserAccountsCtrl]);

    function adminUserAccountsCtrl(userAccountResource) {
        var vm = this;

        userAccountResource.query(function(data) {
            vm.userAccounts = data;
        });
    }

}());

I know that the userAccountResource is created under the common.services module but the common.services module is included as a dependency of the rpms module. Why is it considered an unknown provider?
Thanks.

A: Try to add , after "userAccountResource" like this
 .factory("userAccountResource",  //, here was missing
             ["$resource",
              userAccountResource]);


Q: Find Repeated Digits In List with Java I am working on Pi Finder app.I know there is a lot  of apps about it but i want to do it myself.I did  it with Leibniz formula but it is working very slow because of repeated numbers.I am using lists for storage.Can you help me about find repeated numbers in lists or arrays?
Example
{1,2,5,4,7,6,4,7,6,4,7,....}
I need to find 4,7,6

A: You can find the duplicate elements by using a Set as the accumlator and then utilise Collections.frequency to check if a given number occurs more than once within the List<Integer> like this:
List<Integer> elements = new ArrayList<>(Arrays.asList(1,2,5,4,7,6,4,7,6,4,7));
Set<Integer> accumulator = new LinkedHashSet<>();
for (Integer number : elements) {
   if(Collections.frequency(elements, number) > 1)
       accumulator.add(number);
}

now the accumulator contains:
[4, 7, 6]

LinkedHashSet is utilised here to maintain insertion order. if that is not required then you can use a HashSet instead.
or a better performant solution as suggested by JB Nizet:
List<Integer> elements = new ArrayList<>(Arrays.asList(1,2,5,4,7,6,4,7,6,4,7));
Set<Integer> tempAccumulator = new LinkedHashSet<>();
Set<Integer> resultSet = new LinkedHashSet<>();
for (Integer number : elements) {
     if(!tempAccumulator.add(number))
        resultSet.add(number);
}


Q: Android Studio emulator (AVD) on Mac OSX : AVD icon quickly appears and immediately disappears I am trying to launch an AVD in Android Studio on Mac OSX. I create it and then I launch it.
The problem is that the AVD icon quickly appears in the dock and immediately disappears.
Note that the default emulators present in Android Studio work properly.
Do you know how to solve this problem?
Thanks !

A: Maybe you don't create AVD correctly. Try that: Nexus 5x with Marshmallow x86_64 OS. I'm using that emulator and works perfectly.


Q: ButterKnife OnClick listeners runs shortly after view created in custom view I have a strange problem with ButterKnife's OnClick listeners. When my custom view opened below OnClick listeners are running automatically when view opened. Below code helps you to understand what my problem is.
public class UserMenuFragment extends LinearLayout {
@BindView(R.id.buttonBlockUser)
Button buttonBlockUser;
@BindView(R.id.buttonMuteUser)
Button buttonMuteUser;
@BindView(R.id.buttonHideYourPreset)
Button buttonHideYourPreset;
@BindView(R.id.buttonTurnOnNotifs)
Button buttonTurnOnNotifs;

public UserMenuFragment(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    initView();
}

public UserMenuFragment(Context context, AttributeSet attrs) {
    super(context, attrs);
    initView();
}

public UserMenuFragment(Context context) {
    super(context);
    initView();
}

private void initView() {
    View view = inflate(getContext(), R.layout.fragment_user_menu, null);
    addView(view);
    bindViewWithButterKnife(this, view);
    onButtonReportUserClicked();
    onButtonBlockUserClicked();
    onButtonMuteUserClicked();
    onButtonHideYourPresetClicked();
    onButtonCopyProfileLinkClicked();
    onButtonTurnOnNotifsClicked();
}

@OnClick(R.id.buttonReportUser)
void onButtonReportUserClicked() {
    Toast.makeText(getContext(), "User Reported!", Toast.LENGTH_SHORT).show();
}

@OnClick(R.id.buttonBlockUser)
void onButtonBlockUserClicked() {
    Toast.makeText(getContext(), "User Blocked!", Toast.LENGTH_SHORT).show();
    changeButtonText(buttonBlockUser, R.string.unblock_user_text);
}

@OnClick(R.id.buttonMuteUser)
void onButtonMuteUserClicked() {
    Toast.makeText(getContext(), "User Muted!", Toast.LENGTH_SHORT).show();
    changeButtonText(buttonMuteUser, R.string.unmute_user_text);
}

@OnClick(R.id.buttonHideYourPreset)
void onButtonHideYourPresetClicked() {
    Toast.makeText(getContext(), "User preset hided!", Toast.LENGTH_SHORT).show();
    buttonHideYourPreset.setText(getContext().getString(R.string.show_your_preset_text));
    changeButtonText(buttonHideYourPreset, R.string.show_your_preset_text);
}

@OnClick(R.id.buttonCopyProfileLink)
void onButtonCopyProfileLinkClicked() {
    Toast.makeText(getContext(), "User's profile link copied!", Toast.LENGTH_SHORT).show();
}

@OnClick(R.id.buttonTurnOnNotifs)
void onButtonTurnOnNotifsClicked() {
    Toast.makeText(getContext(), "User's notification is off now!!", Toast.LENGTH_SHORT).show();
    changeButtonText(buttonTurnOnNotifs, R.string.turn_off_notification_text);
}

private void changeButtonText(Button button, int newText) {
    button.setText(getContext().getString(newText));
}

private void bindViewWithButterKnife(UserMenuFragment whichFragment, View view) {
    ButterKnife.bind(whichFragment, view);
}

}
IMO this is happening because I called the OnClick listeners in my constructor so while view creating(after created) naturally they are running. Could somebody help me to understand where is the exact problem is and how to fix it?
My ButterKnife versions:
implementation 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'

A: Change initView() to :
private void initView() {
    View view = inflate(getContext(), R.layout.fragment_user_menu, null);
    addView(view);
    bindViewWithButterKnife(this, view);
}

I don't think you need to call the methods, the annotations already do the job to set the listeners, right ?


Q: Paste Values into new worksheet for all Open Worksheets including pictures I am trying to create a renamed copy of all active workbooks (even non macro-enabled ones) without formulas, possibly by pasting values but without modifying images. I am working with Excel 2007.
My process would ideally be to:
1) Create a do while there are xls files loop that converts all xls files to xlsm. One possible addition would be an array to store A)the worksheet name(s) B)Its tabs name and their status
2) Run a for each or for loop that automatically pastes values for all active worksheets include those with graphs or other images into a new document that has the same name with all small addition at the end.
3) Convert my newly-named files containing values only into xls.
One issue I am running into when I try to do this has to do with links. The initial worksheets have formulas with links that do not automatically update. When I do this, the formulas in the original worksheet with link references tend to get corrupted.
Here is a general macro I found for pasting values:
Sub test()
Dim MyNames As Range, MyNewSheet As Range

    Set MyNames = Range("R5").CurrentRegion ' load contigeous range into variable
    For Each MyNewSheet In MyNames.Cells    ' loop through cell children of range variable
        Sheets.Add.Name = MyNewSheet.Value
    Next MyNewSheet
    MyNames.Worksheet.Select                ' move selection to original sheet
End Sub

A: I think this is what you're asking for:
Sub test()

Dim wb As Workbook
Dim ws As Worksheet
Dim counter As Integer
Dim filePath As String

Set wb = ActiveWorkbook
countet = 1

filePath = "c:/" 'Enter your destination folder here

For Each ws In wb.Sheets
    Sheets("Sheet1").Copy
    With ActiveSheet.UsedRange
        .Value = .Value
    End With
    ActiveWorkbook.SaveAs filePath & counter & ".xlsx", FileFormat:=51
    counter = counter + 1
Next ws
End Sub

This is mostly taken from here.
The counter is a bit of a hack to make sure that the files aren't all being saved as the same name and overwriting each other. Maybe there's a more appropriate way that you can get around this.