text:
Q: Reactjs overwriting component when I try to create a component per item in my list I have an array of data resembling the following:
data = [{name: 'A', data: 1}, {name: 'B', data: 2}]

I also have code resembling the following:
function ReportComponent({ data }) {
  return data.map((datum) => (
    <Typography>
      {datum.name}: {datum.data}
    </Typography>
  ));
}

which is called in
function ReportBox({ component }) {
  const { data } = useFetchHook(component.urls)
  // data returns exactly as expected, an array of objects
  return (
    <Box>
      <Typography>
        {component.title}
      </Typography>
      {data !== null && <ReportComponent data={data} />}
    </Box>
  );
}

My issue is, when I run the application, I only get one output from my data (when I console.log(data) it returns the data I showed above), either
A: 1 OR B:2. I expect there to be both present in the component. Any advice?
---- Update ----
useFetch function
import { useState, useEffect } from 'react';

function useFetch(urls) {
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    let i = urls.length - 1;
    const result = [];

    while (i >= 0) {
      const abortCont = new AbortController();
      console.log(`url ${i}`);
      console.log(urls[i]);
      fetch(urls[i], { signal: abortCont.signal }, { mode: 'cors' })
        .then((res) => {
          if (!res.ok) {
            console.log('something went wrong with the data fetch');
          }
          return res.json(); // why?
        })
        .then((data) => {
          result.push(data);
          setData(result);
        })
        .catch((err) => {
          if (err.name === 'AbortError') {
            console.log('aborted');
          } else {
            setError(err.message);
          }
        });
      i -= 1;
    }
  }, [urls]);
  // console.log(data);

  return { data, error };
}

export default useFetch;

--- Update DashBox ---
mport { Box, Grid, Container, Typography } from '@mui/material';
import ReportBox from './ReportBox';

function DashBox({ components }) {
  // console.log(components);
  return (
    <Grid
      item
      columns={5}
      sx={{
        display: 'flex',
        flexDirection: 'row',
        justifyContent: 'space-evenly',
        alignItems: 'stretch',
        marginTop: '20px',
        marginLeft: '5px'
      }}
    >
      {components.map((component) => (
        <ReportBox component={component} />
      ))}
    </Grid>
  );
}

export default DashBox;

--- Update Page ---
export default function Page() {
  const optionsFilter= [
    'A',
    'B',
    'C'
  ];
  const [filter, setFilter] = useState('A');

  const componentsPage = [
    {
      title: 'One',
      urls: [
        `http://localhost:9000/page1?filter=${filter}`,
        `http://localhost:9000/page2?filter=${filter}`
      ]
    }
  ];

  const componentsPageGraphs = [
    {
      title: 'OneGraph',
      urls: [
        `http://localhost:9000/page1?filter=${filter}`,
        `http://localhost:9000/page2?filter=${filter}`
      ]
    }
  ];

  return (
    <Page title="Page">
      <Container>
        <Typography variant="h4" sx={{ mb: 5 }}>
          Page
        </Typography>
        <Container marginBottom="10px">
          <Typography marginLeft="5px" variant="h5">
            Filters
          </Typography>
          <Grid
            columns={5}
            sx={{
              display: 'flex',
              flexDirection: 'row',
              alignItems: 'stretch',
              marginTop: '10px',
              marginLeft: '5px',
              justifyContent: 'space-evenly'
            }}
          >
            <Grid item sx={{ pr: 5 }}>
              <DropDown
                options={optionsFilter}
                title="Filter Type"
                setData={setFilter}
                data={filter}
                key="one"
              />
            </Grid>
          </Grid>
        </Container>

        <Box
          container
          sx={{ border: 2 }}
          marginLeft="20px"
          pr="20px"
          pb="20px"
          pl="20px"
          width="100%"
        >
          <Typography variant="h3">Page Dashboard</Typography>
          <DashBox components={componentsPage} />
        </Box>
        <Grid container spacing={2} marginTop="20px">
          {componentsPageGraphs.map((component) => (
            <Grid item xs={6}>
              <Typography>{component.title}</Typography>
              <LineChart xtype="category" urls={component.urls} />
            </Grid>
          ))}
        </Grid>
      </Container>
    </Page>
  );
}

---- Update again with the suggested fetch, unfortunately still overwriting ---
import { useState, useEffect, useRef } from 'react';

const sameContents = (array1, array2) =>
  array1.length === array2.length && array1.every((value, index) => value === array2[index]);

function useFetch(urls) {
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);
  const urlsRef = useRef(null);

  if (!urlsRef.current || !sameContents(urlsRef.current, urls)) {
    urlsRef.current = urls.slice();
  }

  useEffect(() => {
    const results = [];
    if (!urlsRef.current) {
      return;
    }
    const controller = new AbortController();
    const { signal } = controller;

    Promise.all(
      urlsRef.current.map((url) => {
        fetch(url, { signal, mode: 'cors' })
          .then((res) => {
            if (!res.ok) {
              console.log('http issue');
            }
            return res.json();
          })
          .then((data) => {
            if (!signal.aborted) {
              results.push(data);
              setData(results);
              setError(null);
            }
          })
          .catch((error) => {
            if (signal.aborted) {
              return;
            }
            setData(null);
            setError(error);
          });
        return () => {
          controller.abort();
        };
      })
    );
  }, [urlsRef.current]);
  return { data, error };
}

export default useFetch;

Stack Snippet:

const {useState, useEffect} = React;

// Fake Typography component
const Typography = ({children}) =>
{children}
;

// Fake Box component
const Box = ({children}) =>
{children}
;

// Fake fetch hook
function useFetchHook(urls) {
    const [data, setData] = useState(null);
    useEffect(() => {
        setTimeout(() => {
            setData([
                {name: "One", data: "Data for 'One'"},
                {name: "Two", data: "Data for 'Two'"},
                {name: "Three", data: "Data for 'Three'"},
            ]);
        }, 500);
    }, []);
    return {data};
}

function ReportComponent({ data }) {
    return data.map((datum) => (
        <Typography>
            {datum.name}: {datum.data}
        </Typography>
    ));
}

function ReportBox({ component }) {
    const { data } = useFetchHook(component.urls)

    // data returns exactly as expected, an array of objects
    return (
        <Box>
            <Typography>
                {component.title}
            </Typography>
            {data !== null && <ReportComponent data={data} />}
        </Box>
    );
}

ReactDOM.render(<ReportBox component={{urls: [], title: "Example"}} />, document.getElementById("root"));

A: Your Page component creates a new componentsPage object with new urls arrays in the components every time it renders. Those new urls arrays are ultimately passed to useFetch (aka useFetchHook), where you have this structure:
function useFetch(urls) {
    const [data, setData] = useState(null);
    const [error, setError] = useState(null);

    useEffect(() => {
        // ...code that fetches and sets `data`/`error`...
    }, [urls]);
    // console.log(data);

    return { data, error };
}

That means that every time the urls parameter changes value (the old value isn't === the new value), it will repeat the fetch and update data or error.
There are various issues with the hook as well, the primary problem being that it does asynchronous work (a series of fetch calls) but doesn't check to be sure that the results its getting aren't outdated (because urls changed). More on that in a moment.
Since the urls arrays are recreated every time, useFetch does the fetches again every time, because no array is ever === any other array, even if they have the same contents:

console.log(["1", "2", "3"] === ["1", "2", "3"]); // false

So you need to:

*

*Have useFetch only start a new series of fetches when the URLs really change. If it's given a new array with the same contents, it shouldn't do a new set of fetches.

*useFetch should abort the fetches that are in progress if it's about to get a new set of urls, and shouldn't use the previous results if that's happened.
You seem to have started on #2 by using an AbortController, but nothing every called its abort method, so it didn't do anything.
Here's a version of useFetch that handles both of those things, see the comments:
const sameContents = (array1, array2) => {
    return array1.length === array2.length &&
           array1.every((value, index) => value === array2[index]);
};

function useFetch(urls) {
    const [data, setData] = useState(null);
    const [error, setError] = useState(null);
    const urlsRef = useRef(null);               // A place to keep the URLs we're handling

    if (!urlsRef.current ||                     // Mounting, or
        !sameContents(urlsRef.current, urls)    // Called after mount with *different* URLs
       ) {
        // Remember these URLs
        urlsRef.current = urls.slice();
    }

    useEffect(() => {
        if (!urlsRef.current) {
            // Nothing to do
            return;
        }
        // Use the same controller and signal for all the fetches
        const controller = new AbortController();
        const {signal} = controller;
        // Use `Promise.all` to wait for all the fetches to complete (or one
        // of them to fail) before setting `data`.
        Promise.all(urlsRef.current.map(url =>
            // Note: You had `{ mode: "cors" }` on its own as a third argument,
            // but it should have been part of the second argument (`fetch`
            // only takes two).
            fetch(url, {signal, mode: "cors"})
            .then(res => {
                if (!res.ok) {
                    // HTTP error
                    throw new Error(`HTTP error ${res.status}`);
                }
                // HTTP okay, read the body of the response and parse it
                return res.json();
            })
        ))
        .then(data => {
            // Got all the data. If this set of results isn't out of date,
            // set it and clear any previous error
            if (!signal.aborted) {
                setData(data);
                setError(null);
            }
        })
        .catch(error => {
            // Do nothing if these results are out of date
            if (signal.aborted) {
                return;
            }
            // Clear data, set error
            setData(null);
            setError(error);
        });
        // Return a cleanup callback to abort the set of fetches when we get
        // new URLs.
        return () => {
            controller.abort();
        };
    }, [urlsRef.current]); // <=== Use this instead of `urls`

    return { data, error };
}

That's a sketch, I won't be surprised if you need to make small tweaks to it, but it should get you going the right way.


text:
Q: Apple rejected my app for problems with IPv6 (crashing) I have an App that doesn't use internet connexion, but apple send me a message where says that I have a crash in my first view controller for problem with the IPv6. Apple send me a report for the crash but i'm not able to learn it, i need your help. Or maybe if u had the same problem with this conexión(IPv6) and you were find the error.
pleas help me!!
Heres one file from the crash, that apple send me but i don't understand, pleas help me to know what they say.

{"app_name":"idWallet","timestamp":"2017-03-03 19:35:40.34 -0800","app_version":"1.1","slice_uuid":"7670eb49-b5ca-3334-b398-6cdb6982530e","adam_id":0,"build_version":"3","bundleID":"fernandorey.idWallet","share_with_app_devs":false,"is_first_party":false,"bug_type":"109","os_version":"iPhone OS 10.2.1 (14D27)","incident_id":"195A9217-8AF8-47BA-A8C2-4FC808AF587F","name":"idWallet"}
Incident Identifier: 195A9217-8AF8-47BA-A8C2-4FC808AF587F
CrashReporter Key:   0ec021c8a7f1efb30dfc7eceb07eaa3fd8f82c46
Hardware Model:      xxx
Process:             idWallet [8539]
Path:                /private/var/containers/Bundle/Application/E974F007-2A8F-4724-A766-6E542BCDD035/idWallet.app/idWallet
Identifier:          fernandorey.idWallet
Version:             3 (1.1)
Code Type:           ARM-64 (Native)
Role:                Foreground
Parent Process:      launchd [1]
Coalition:           fernandorey.idWallet [4123]

Date/Time:           2017-03-03 19:35:40.1752 -0800
Launch Time:         2017-03-03 19:26:24.4423 -0800
OS Version:          iPhone OS 10.2.1 (14D27)
Report Version:      104

Exception Type:  EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Exception Note:  EXC_CORPSE_NOTIFY
Triggered by Thread:  0

Application Specific Information:
abort() called

Filtered syslog:
None found

Last Exception Backtrace:
(0x18e1a91b8 0x18cbe055c 0x1904c0b90 0x10005f17c 0x10005e8c8 0x194057924 0x1940574ec 0x194a19cf0 0x1943a24ac 0x1943c3a54 0x1943c6920 0x19414a154 0x1943ca0e4 0x194706808 0x194814854 0x19481465c 0x1943ba9b8 0x100067b98 0x100068804 0x10006841c 0x100068218 0x19408cd30 0x19408ccb0 0x194077128 0x19408c59c 0x19408c0c4 0x194087328 0x194057da0 0x19484175c 0x19483b130 0x18e156b5c 0x18e1564a4 0x18e1540a4 0x18e0822b8 0x18fb36198 0x1940c27fc 0x1940bd534 0x10005d3b4 0x18d0655b8)

Thread 0 name:  Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0   libsystem_kernel.dylib          0x000000018d177014 0x18d158000 + 126996
1   libsystem_pthread.dylib         0x000000018d23f450 0x18d23a000 + 21584
2   libsystem_c.dylib               0x000000018d0eb400 0x18d088000 + 406528
3   libc++abi.dylib                 0x000000018cbb52d4 0x18cbb4000 + 4820
4   libc++abi.dylib                 0x000000018cbd2cc0 0x18cbb4000 + 126144
5   libobjc.A.dylib                 0x000000018cbe0844 0x18cbd8000 + 34884
6   libc++abi.dylib                 0x000000018cbcf66c 0x18cbb4000 + 112236
7   libc++abi.dylib                 0x000000018cbcf234 0x18cbb4000 + 111156
8   libobjc.A.dylib                 0x000000018cbe071c 0x18cbd8000 + 34588
9   CoreFoundation                  0x000000018e08232c 0x18e079000 + 37676
10  GraphicsServices                0x000000018fb36198 0x18fb2a000 + 49560
11  UIKit                           0x00000001940c27fc 0x194048000 + 501756
12  UIKit                           0x00000001940bd534 0x194048000 + 480564
13  idWallet                        0x000000010005d3b4 0x100054000 + 37812
14  libdyld.dylib                   0x000000018d0655b8 0x18d061000 + 17848

Thread 1 name:  com.apple.uikit.eventfetch-thread
Thread 1:
0   libsystem_kernel.dylib          0x000000018d159188 0x18d158000 + 4488
1   libsystem_kernel.dylib          0x000000018d158ff8 0x18d158000 + 4088
2   CoreFoundation                  0x000000018e1565d0 0x18e079000 + 906704
3   CoreFoundation                  0x000000018e1541ec 0x18e079000 + 897516
4   CoreFoundation                  0x000000018e0822b8 0x18e079000 + 37560
5   Foundation                      0x000000018ebbf26c 0x18ebb3000 + 49772
6   Foundation                      0x000000018ebdfdd0 0x18ebb3000 + 183760
7   UIKit                           0x0000000194a36c38 0x194048000 + 10415160
8   Foundation                      0x000000018ecbce68 0x18ebb3000 + 1089128
9   libsystem_pthread.dylib         0x000000018d23d850 0x18d23a000 + 14416
10  libsystem_pthread.dylib         0x000000018d23d760 0x18d23a000 + 14176
11  libsystem_pthread.dylib         0x000000018d23ad94 0x18d23a000 + 3476

Thread 2:
0   libsystem_pthread.dylib         0x000000018d23ad88 0x18d23a000 + 3464

Thread 3:
0   libsystem_pthread.dylib         0x000000018d23ad88 0x18d23a000 + 3464

Thread 4:
0   libsystem_pthread.dylib         0x000000018d23ad88 0x18d23a000 + 3464

Thread 0 crashed with ARM Thread State (64-bit):
    x0: 0x0000000000000000   x1: 0x0000000000000000   x2: 0x0000000000000000   x3: 0x00000001780e8437
    x4: 0x000000018cbd3bc3   x5: 0x000000016fdab520   x6: 0x000000000000006e   x7: 0xffffffffffffffec
    x8: 0x0000000008000000   x9: 0x0000000004000000  x10: 0x000000000000000b  x11: 0x0000000000000010
   x12: 0x000000018d102772  x13: 0x0000000000000000  x14: 0x0000040000000400  x15: 0x0000000000000000
   x16: 0x0000000000000148  x17: 0x0000000000000000  x18: 0x0000000000000000  x19: 0x0000000000000006
   x20: 0x00000001b3219c40  x21: 0x000000016fdab520  x22: 0x00000001b3220bb8  x23: 0x0000000000000001
   x24: 0x0000000178018be0  x25: 0x0000000000000000  x26: 0x0000000000000001  x27: 0x0000000000000000
   x28: 0x000000016fdabbc0   fp: 0x000000016fdab480   lr: 0x000000018d23f450
    sp: 0x000000016fdab460   pc: 0x000000018d177014 cpsr: 0x00000000

.
.
.

i can't add all the message for question of limit characters.

A: As @dan mentioned, try to symbolicate your crash report.
The following link will help you.
https://developer.apple.com/library/content/technotes/tn2151/_index.html#//apple_ref/doc/uid/DTS40008184-CH1-SYMBOLICATEWITHXCODE

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the response for RESTORE_TRANSACTIONS in case of subscription bought twice? I can't test this myself, because there is no way to completely terminate subscription, apparently.
So, I want to test the following use case: user buys subscription, cancel's it (or it expires), than user buys same subscription.
What will I get with RESTORE_TRANSACTIONS response? Will I get two items with same item id, different purchase tokens and different state? Or purchaseToken will remain the same? I'm afraid that there will be only one subscription with different order ID and purchase token, and the information on previous subscriptions will be lost, but I can't confirm it right now. Also, will orderId be changed with every recurring purchase inside a subscription?
Why I need this - subscription will supply user with new content daily, so when user cancel subscription (subscription A) and later buys a new one (subscription B) I need to show to user content released during time-frame of subscription A,and content in a time-frame of subscription B, but not the content released in period used didn't had active subscription.

A:
Note: You should use the RESTORE_TRANSACTIONS request type only when your application is installed for the first time on a device or when your application has been removed from a device and reinstalled.
Using RESTORE_TRANSACTIONS on a regular basis is not recommended because of performance impacts.

Taken right from Android Developers http://developer.android.com/guide/google/play/billing/billing_overview.html
Although I do understand your concern for the Subscription Billing. Google is pretty good about their API and how you should interact with purchases.
When you send a RESTORE_TRANSACTIONS request you will get two broadcast back. A RESPONSE_CODE and a PURCHASE_STATE_CHANGED. Here's the table from Google stating the different values you could receive.

Coming back to your question about buying two subscriptions: you should check to see if the user has bought a subscription with the GET_PURCHASE_INFORMATION request, if the Subscription is in the list check the Purchase State of the Subscription to see if you should continue with the purchase.
As for what you would get if you "Could" buy two of the same subscriptions, its (I want to say impossible) unlikely... But you will get two order transactions.
As long as you're always aware of the user transactions on your part, Google's API will do the rest. Good luck!


text:
Q: RSolr::Error::Http (RSolr::Error::Http - 429 I am working on Ruby on Rails project hosted on heroku server. the search functionnalit works fine on localhost. But when i try on production i get the following error:
RSolr::Error::Http (RSolr::Error::Http - 429
Error: {"code":429,"message":"Request meter exhausted. Please consider batching your requests, or contact support@websolr.com for help."}

I have spent time looking for resolving this problem. I found that the 429 code status refers to too many requests in websolr and it is used to protect from DoS attacks.
Please how can I resolve this issue.
Regards

A: Websolr Support here. An HTTP 429 response indicates that the connection pool to your index is fully saturated. There are a couple of options to address it:

*

*Batch updates. If you're making a lot of single-document writes for some reason, try batching them to reduce the number of connections in use.

*Upgrade to a higher plan. Concurrency limits scale with plan level, so upgrading can get you the resources you need.

*Shoot us an email at support@websolr.com and we'll take a look and see if there are any other recommendations.


text:
Q: In MacOS, how can I group the processes based on apps? I want to know the resources used on the basis of applications. I found a duplicate, but the answer there has issues and since its over a year old, I decided to post a new one, instead of posting there.
The solution in the previous post was, Activity Monitor>View>"All Processes, Hierarchically". But that has an issue:
Did I do something wrong or is this a bug? Is there any other way of knowing it?

A: These Google Chrome Helper processes are sub-processes of the Google Chrome app. You'll notice that the highlighted sub-process is indeed at the top of all the other sub-processes in the list - the proper hierarchy. You did nothing wrong, nor is there a bug.


text:
Q: Converting a string to a list in sicstus prolog I'm making a chess-like game and, in order to make the various moves, I want to read some user input like "11-12" to move the piece located at the "coordinates" 1-1 to the position 1-2. I want to convert the string "11-12" to a list like [1,1,-,1,2]. I would like to end up with something like this:
...
read(Play),
convert_play_to_list_L(Play, L),
element_at(StartX,L,1),
element_at(StartY,L,2),
element_at(EndX,L,3),
element_at(EndY,L,4),
...

example:
Play = "1112" , L = [1,1,1,2] , StartX = 1 , StartY = 1 , EndX = 1  , EndY = 2


text:
Q: Image and text position in list inline elements I am trying to design a web-page where I have a list of bands, and every image will be a small set picture of the band logo(or something). I am setting the style inline and I have tried vertical-align and line-height etc and nothing seems to work.
I am pretty sure I could accomplish this with tables but I have been told many times that is not the proper use of the table.

band name

band name

band name

band name

band name

Here is the small amount of CSS I have
    #content li{display:inline;}
    img {
    max-height:100px;
    max-width: 100px;
    }

   #content ul{list-style-type: none;
    clear:left;
   }

Any help or tips would be greatly appreciated

A: My best guess is that you are looking for this:
#content ul li {
   float:left;
}

otherwise you'd have to be a bit more specific on what you are trying to accomplish.

A: If I understood what you're trying to do, try this:
#content li {
    display: inline-block;
    background-color: #eaeaea;
    border: 1px solid red;
    text-align: center;
    max-width: 100px;
    white-space: nowrap;
    overflow: hidden;
    margin: 5px;
}

img {
    max-height:100px;
    max-width: 100px;
    display: block;
}

#content ul{
    list-style-type: none;
    clear:left;
}

Have a look at it here: http://jsfiddle.net/zDhKQ/

A: I believe you want the align tag. Something like this:

This is some text.

Will result in something that looks nice.


text:
Q: Como exibir uma mensagem após excluir um registro utilizando php? Tenho uma página com uma lista de dados e para cada registro tenho a opção excluir. Quando eu clico no botão excluir, antes de executar a ação ele verifica em um arquivo controlador qual ação foi solicitada para só então fazer a execução do código de exclusão.
O fluxo de ações segue mais ou menos assim:
Clique do Botão => Verificação no Controller => Executa Ação
Eu tentei printar em tela uma mensagem após a execução do código, porém a mensagem é exibida na página de controller. O que não é certo pois essa página não deveria exibir nada, sendo apenas uma ponte entre a solicitação e a ação desejada.
Para solicitar a exclusão eu estou utilizando o método post. Seria possível fazer a mensagem de confirmação aparecer na página aonde existe a listagem? Caso seja possível, como poderia ser feito?

A: Sim, é possível fazer isso utilizando AJAX. O código fica mais ou menos assim:

jQuery.ajax({
  type: "POST",
  url: URL-DA-SUA-REQUISICAO,
  data: DADOS-DA-SUA-REQUISICAO,
  success: function sucesso(dados) {
    document.write('Concluido')
  },
  error: function erro(error) {
    document.write('Ops, um erro ocorreu')
    console.error(error)
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Vale lembrar, que nesse caso, a função do campo error somente será chamada caso ocorra um erro na requisição ou quando o status HTTP retornado seja um status de erro.


text:
Q: Display amount of pending posts in back/front end I want to display the total amount of pending posts that my site has. My site is a single site, not a network. I am looking to echo that count in the back-end (a custom plugin page) and in the front-end.

How can I do this?

A: Easy native SQL query:
global $wpdb;

$sql = <<<SQL
SELECT post_status, COUNT( * ) AS count
    FROM {$wpdb->posts}
WHERE post_status = 'pending'
SQL;

$result = $wpdb->get_results( $sql );

The result will be something like
+ ----------- + ----- +
| post_status | count |
+ ----------- + ----- +
|   pending   |  158  |
+ ----------- + ----- +

So you'll be able to show the number of pending posts with $result->count.
is_user_logged_in() checks if a user is logged in.
And with edit_post_link() you'll be able to link to those posts directly (after you queried for them separately). The following will link to the posts admin table filtered by post status pending:
printf( 'Pending Posts', admin_url( 'edit.php?post_status=pending' ) );

Plugin
As a plugin:
<?php
/**
 * Plugin Name: (#115946) Post Count by status
 * Plugin URI:  http://wordpress.stackexchange.com/questions/115946
 * Author:      Franz Josef Kaiser <wecodemore@gmail.com>
 * Author URI:  http://unserkaiser.com
 */

function wpse115946PostCountByStatus( $status )
{
    global $wpdb;

$sql = <<<SQL
SELECT post_status, COUNT( * ) AS count
    FROM {$wpdb->posts}
WHERE post_status = %s
SQL;

    $result = array_shift( $wpdb->get_results( $wpdb->prepare( $sql, $status ) ) );

    $title = sprintf( _e( '%s %s posts', ucwords( $status ), $result->count ) );
    return printf(
        '%2$s',
        admin_url( 'edit.php?post_status=pending' ),
        $title
    );
}


text:
Q: TCP communication on Vista I have a very simple app I'm trying to get to run under TCP using WCF 3.5 on Vista Enterpise. The error I'm getting when trying to hit a WCF service at http://localhost:8080 (or any other port not reserved by http) is:
TCP error code 10061: No connection could be made because the target machine actively refused it 127.0.0.1:8080.
I've gotten this to work a few months ago, but I forgot how. I'm wondering if I have the port reserved or something...I've tried allowing the compiled executable through Windows Firewall and tried opening port 8080 for TCP through the firewall, but i get the same error. Any thoughts or ideas on where to look or what to check?
Thanks!

A: Try going to http://machinename:8080 - I've had Vista make firewall distinctions based on that before, especially if the Loopback adapter was installed

A: No dice. Changing localhost to the machine name doesn't let me in.
It's not http that is having the problem...localhost works fine there as well. But everything I've tried to do with tcp has faild with the same error. Completely frustrating as I know I've seen this work on this box before.
Edit to include commented answer: Just FYI, finally found the problem. Something was misnamed in the service's config file. I wish the error could have been a bit clearer, but all is well. Thanks!


text:
Q: Adding points to pyplot choropeth map I have created a choropleth map in python with pyplot on US census data. Now I want to add points to this map denoting the location of towns using longitude and latitude. My code below successfully renders the choropleth but not the points on top

fig1 = px.choropleth(population, locations=population['StateAbbr'], locationmode='USA-states',
 color='per1910',color_continuous_scale='inferno',
 range_color=(0, .15),scope='usa',labels={'StateAbbr':'per1910'},hover_name='StateAbbr',)

go.Figure(data=go.Scattergeo(
        lon = champs['Lon'],
        lat = champs['Lat'],
        text = champs['School'],
        mode = 'markers',
        marker_color = 'blue',
        ))

fig1.update_layout(title_text = 'Census: 1910 Championships: 1872-1915')
fig1.show()


text:
Q: Neater way to catch exception in exception handler in Python In a Python program, one generally catches an exception using a try-except block:
try:
    # Do stuff
except ValueError:
    # Handle exception

The best way I know of to catch an exception in an exception handler is a nested try-except block. However, with many nested try-catch blocks, this may get a bit messy:
try:
    # Some assignment that throws an exception if the object is not in the list
    try:
        # Some assignment function that throws an exception if the the object is not already in the database
        # Error Handling
    except ValueError:
        try:
            # Some function that throws an exception if the object does not have an undesired property
            # Error Handling
        except AttributeError:
            try:
                # Some function that throws an exception if an error happens
            except Exception:
                # Exception handling
except ValueError:
    # Exception handling

Is there a neater way to do this? Something like:
try:
   # Some assignment that throws an exception if the object is not in the list
   try:
       # Some assignment function that throws an exception if the object is not already in the database
   except ValueError:
       # Some function that throws an exception if the object does not have an undesired property
   exceptexcept AttributeError:
       # Some function that throws an exception if an error happens
   exceptexcept Exception:
       # Exception handling
except ValueError:
   # Exception handling

A: This sounds like a loop where you want to keep trying until you succeed or run out of options. So you could implement it that way, e.g., something like this
# Each pair contains a function to call and an exception that can be caught.
# If that exception is raised, the next function will be tried.
action_list = [
    (get_from_list, ValueError),  # throws ValueError if item can't be retrieved
    (get_from_database, ValueError),  # throws ValueError if item can't be retrieved
    (get_from_object, AttributeError),  # throws AttributeError if item lacks desired property
]

result = None
for action, ex in action_list:
    try:
        result = action(key)
        break
    except ex:
        continue

You could tidy this up a bit by having all your helper functions raise a custom exception like "NotFound", which you then use as a signal to check the next level, like this:
# actions to try; all raise NotFound if unsuccessful
action_list = [
    get_from_list, get_from_database, get_from_object
]

result = None
for action in action_list:
    try:
        result = action(key)
        break
    except NotFound:
        continue

Or you could put all the steps in a function that returns as soon as it succeeds. This way your assignments could be done in regular code rather than using helper functions:
def get_value(key):

    try:
        return some_list[int(key)]
    except ValueError:
        pass

    try:
        return get_from_database(key)
    except ValueError:
        pass

    try:
        return getattr(some_object, key)
    except AttributeError:
        pass

    return None

If you don't want another function you could abuse a for loop:
result = None
for _ in range(1):

    try:
        result = some_list[int(key)]
        break
    except ValueError:
        pass

    try:
        result = get_from_database(key)
        break
    except ValueError:
        pass

    try:
        result = getattr(some_object, key)
        break
    except AttributeError:
        pass

Or you could use a single outer try/except with a custom Found exception as a "structured goto":
result = None
try:
    try:
        result = some_list[int(key)]
        raise Found
    except ValueError:
        pass
    try:
        result = get_from_database(key)
        raise Found
    except ValueError:
        pass
    try:
        result = getattr(some_object, key)
        raise Found
    except AttributeError:
        pass
except Found:
    pass  # all good

Or there's this tried-but-true construct:
result = None
if result is None:
    try:
        result = some_list[int(key)]
    except ValueError:
        pass
if result is None:
    try:
        result = get_from_database(key)
    except ValueError:
        pass
if result is None:
    try:
        result = getattr(some_object, key)
    except AttributeError:
        pass


text:
Q: How To Prove:$\sum_{n=1}^{\infty} \frac{(-1)^n}{n^4} = -\frac{7}{{720}}{\pi ^4}$ When I tried to solve this integral:
$$\int_0^\infty  {\frac{{{x^3}}}{{1 + {e^x}}}} \;{\rm{d}}x$$
I had trouble computing the sieries:
$$\sum_{n=1}^{\infty} \frac{(-1)^n}{n^4}$$
Thanks.

A: $$\sum_{n=1}^{+\infty}\frac{(-1)^n}{n^4} = -\sum_{n=1}^{+\infty}\frac{1}{n^4}+2\sum_{m=1}^{+\infty}\frac{1}{(2m)^4} = \left(-1+\frac{2}{16}\right)\sum_{n=1}^{+\infty}\frac{1}{n^4}=-\frac{7}{8}\zeta(4) = -\frac{7\pi^4}{720}.$$

A: From the definition of the polylogarithm, we have that
$$\sum_{n=1}^{\infty} \frac{(-1)^n}{n^4}=\mathrm{Li}_4(-1).$$
Since $\mathrm{Li}_s(-1)=-\eta(s)$, we then seek to evaluate $-\eta(4)$. This is easy, as
$$\eta(s)=(1-2^{1-s})\zeta(s).$$
This would imply that
$$-\eta(4)=-(1-2^{-3})\zeta(4),$$
and since $\zeta(4) = \pi^4/90$, we have
$$-\eta(4)=-\frac{7\pi^4}{720}.$$
Note that $\eta(s)$ denotes the Dirichlet eta function.


text:
Q: Generating a pre-signed URL for S3 object with KMS encryption - what am I doing wrong? I'm using the AWS SDK v2.3.44.0 for .NET 4.0 and am trying to generate a pre-signed URL for clients to download objects. All of the objects are stored in an S3 bucket and encrypted using the aws:kms server side encryption method.
I'm using the AmazonS3Client's GetPreSignedURL method to generate the URL.
My AmazonS3Client object is created like so:
var client = new AmazonS3Client(new AmazonS3Config
{
    RegionEndpoint = RegionEndpoint.USEast1,
    SignatureVersion = "4"
});

My GetPresignedUrlRequest object is created like so:
var request = new GetPreSignedUrlRequest
{
    BucketName = bucket,
    Key = key,
    Expires = expires,
    ServerSideEncryptionMethod = ServerSideEncryptionMethod.AWSKMS
 };

Now when I run client.GetPreSignedURL(request) it generates a URL like so (formatted for readability and sanitized):
https://{bucket}.s3.amazonaws.com/{key}?AWSAccessKeyId={access key}
    &Expires={timestamp}
    &Signature=AWS4-HMAC-SHA256%20Credential%3D{access key}%2F20150626%2Fus-east-1%2Fs3%2Faws4_request%2C%20SignedHeaders%3Dhost%3Bx-amz-content-sha256%3Bx-amz-date%3Bx-amz-server-side-encryption%2C%20Signature%3D{signature}

When navigating to this URL, I get an XML breakdown of an error: SignatureDoesNotMatch.
This URL looks different from the one Amazon describes in their docs. Also, generating the URL from Visual Studio using the AWS plugin generates a working URL that looks like this (again formatted and sanitized):
https://{bucket}.s3.amazonaws.com/{key}?
    X-Amz-Expires=900
    &X-Amz-Algorithm=AWS4-HMAC-SHA256
    &X-Amz-Credential={access key}/20150626/us-east-1/s3/aws4_request
    &X-Amz-Date=20150626T195148Z
    &X-Amz-SignedHeaders=host
    &X-Amz-Signature={signature}

What am I doing wrong that my pre-signed URLs are not being generated properly for downloading aws:kms encrypted files?

A: Alright, after much digging I found where I went wrong. To use SignatureVersion4, you need to set that before the client is created via a static property on the AWSConfigs.S3Config object. All the other fields I set are not needed in my case either.
Thus the proper way to do it is:
 private static AmazonS3Client CreateClient()
 {
     AWSConfigs.S3Config.UseSignatureVersion4 = true;
     return new AmazonS3Client(RegionEndpoint.USEast1);
 }

And creating the request
 var request = new GetPreSignedUrlRequest
 {
     BucketName = bucket,
     Key = key,
     Expires = expires
 };


text:
Q: QFileDialog combine MIME type filters to "All formats" I am using Qt 5.9 to open a file dialog asking the user to select an image file:
QStringList mimeTypeFilters;
const QByteArrayList supportedMimeTypes = QImageReader::supportedMimeTypes();
foreach(const QByteArray& mimeTypeName, supportedMimeTypes) {
    mimeTypeFilters.append(mimeTypeName);
}
mimeTypeFilters.sort();

QFileDialog* fileDialog = new QFileDialog(this, "Select image");
fileDialog->setMimeTypeFilters(mimeTypeFilters);
fileDialog->setFileMode(QFileDialog::ExistingFile);
fileDialog->exec();

All supported image formats are added as MIME type filters to the dialog, which is working quite well. However, I want to add an additional filter (such as "All formats" or "All supported") that allows the user to select an image of ANY of the supported formats, as selecting the correct format prior to selecting the image is quite tedious. What is the most elegant solution to achieve this, without subclassing any of the involved Qt classes?

A: Thanks to SteakOverflow's comment, here is the solution I came up with:
// get supported image file types
QStringList mimeTypeFilters;
const QByteArrayList supportedMimeTypes = QImageReader::supportedMimeTypes();
foreach(const QByteArray& mimeTypeName, supportedMimeTypes) {
    mimeTypeFilters.append(mimeTypeName);
}
mimeTypeFilters.sort(Qt::CaseInsensitive);

// compose filter for all supported types
QMimeDatabase mimeDB;
QStringList allSupportedFormats;
for(const QString& mimeTypeFilter: mimeTypeFilters) {
    QMimeType mimeType = mimeDB.mimeTypeForName(mimeTypeFilter);
    if(mimeType.isValid()) {
        allSupportedFormats.append(mimeType.globPatterns());
    }
}
QString allSupportedFormatsFilter = QString("All supported formats (%1)").arg(allSupportedFormats.join(' '));

QFileDialog* fileDialog = new QFileDialog(this, "Select image");
fileDialog->setFileMode(QFileDialog::ExistingFile);
fileDialog->setMimeTypeFilters(mimeTypeFilters);
QStringList nameFilters = fileDialog->nameFilters();
nameFilters.append(allSupportedFormatsFilter);
fileDialog->setNameFilters(nameFilters);
fileDialog->selectNameFilter(allSupportedFormatsFilter);

It is basically the same implementation QFileDialog uses internally to convert mime type filters to name filters. The new name filter for all supported formats will be added at the bottom of the filter list and pre-selected. The filter string is quite long and not fully visible in the dialog at once, but will become fully visible once the user opens the drop-down menu.


text:
Q: If $\alpha,\beta\in S_n$ are disjoint, are $\alpha^m, \beta^n$ disjoint for any $m,n\in\Bbb{N}$? If $\alpha,\beta\in S_n$ are disjoint, are $\alpha^m, \beta^n$ disjoint for any $m,n\in\Bbb{N}$?
I believe that the answer is true but I am not sure how to get a proper proof for this statement.
I have proved one property that is

Let $\alpha=(i_1 i_2\dots i_r)$ and $\beta=(j_1j_2\dots j_s)$. Then $\alpha$ and $\beta$ are disjoint iff $\{i_1,\dots,i_r\}\cap \{j_1,\dots,j_s\}=\varnothing$.

Let $A=\{i_1,\dots,i_r\}$  and $B=\{j_1,\dots,j_s\}$ be the set of elements moved by each $\alpha$ and $\beta$ respectively. Write each $\alpha$ and $\beta$ as a product of disjoint cycles. Since $\alpha$ and $\beta$ are disjoint, their cycles are disjoint too. By the above property, $A\cap B=\varnothing$. Note that the elements moved by $\alpha^m$ and $\beta^n$ will be subset of $A$ and $B$, so the elements moved by both $\alpha^m$ and $\beta^n$ will be subset of $A\cap B$ which is empty set.

A: We say an element $x$ is moved by a permutation if $\alpha(x)\neq x$. Denote the set of elements moved by $\alpha$ as $\mu(\alpha)$.
Recall that two permutations are said to be disjoint if $\mu(\alpha)\cap \mu(\beta)=\varnothing$.
It is easy to show that $\mu(\alpha^n) \subseteq \mu(\alpha)$.
So clearly if $\mu(\alpha)\cap \mu (\beta)=\varnothing$ then $\mu(\alpha ^n ) \cap \mu (\beta ^m)=\varnothing$


text:
Q: Powershell commands only work when I run selection in ise I'm new to powershell and I'm using the ps ise to write a ps script that executes a .exe remotely on another server.
When I click run in the ise, the script doesn't appear to do anything. However, when I right-click on the individual lines of code in the ps script, I can see within the ps console and the target server that each line of code works.
What am I missing to get it to work when I just click run script in the ise or when I run the script from the command line?
Here is what the script basically looks like:
Enter-PSSession -ComputerName MyServer1
D:\Somefolder\On\TargetServer\theremote.exe
Exit-PSSession

I appreciate any help or guidance on this.

A: Let me explain you.
Enter-PSsession basically creates an interactive session with the remote computer.
So once the session has been created, you can run all the commands which interactive will return the result from the remote computer.
You should use invoke-command to get your job done . It should be like:
Invoke-Command -ComputerName MyServer1 -ScriptBlock {& 'D:\Somefolder\On\TargetServer\theremote.exe'}

Now, by default it uses Windows Authentication. If you want to specify any credentials then you can use -Credential switch.
Or another method is to create a remote session first using new-pssession, then store the session in a variable.
Finally, you can specify the session in the invoke-command as -SessionName
As per the comments, this is how you can pass the parameters(I am passing only 1 parameter here):
Invoke-Command -ComputerName MyServer1 -ScriptBlock { param ($param1) & 'D:\Somefolder\On\TargetServer\theremote.exe' -something $param1 } -ArgumentList "param1Value"

Hope it helps.


text:
Q: I want to retrieve the instance of a course module tl;dr; trying to get a course module instance via a course module through mysql or the official moodle api. My solution in the end seems rather scrappy though, so i would like some advice.
Hi Moodle people
I am trying to retrieve the corresponding course module instance for each row in mdl_course_modules, a instance in this context would be a single row from mdl_quiz, mdl_wiki or some other course_modules instance.
I have tried a few things, the one i expected to work was:
function get_all_course_modules($course_id) {
   global $DB;
   $course = $DB->get_record('course', array('id' => $course_id));
   $mod_info = get_fast_modinfo($course);
}

I wasn't able to get the course modules instance from $mod_info .
So i tried to do some custom mysql instead,
SELECT course.id, course.fullname, cm.course, cm.section, m.name
 FROM mdl_course AS course
 JOIN mdl_course_modules AS cm ON cm.course = course.id
 JOIN mdl_modules AS m ON m.id = cm.module
 JOIN CONCAT('mdl_', m.name) AS module_type ON ...somethingsomething
 WHERE course.id = 2;

The sql isn't quite finished, i stumbled on the fact that i dont know all of the different course modules beforehand, that means that i have to use the name of the course_module dynamically to select which instance table i want to join on, or just LEFT JOIN on all of the possible course modules instance tables, but that would take forever and would stop working if someone put in a new course module instance.
Right now im doing the following:
 $result = array();
$course_mods = get_course_mods($course_id);

if($course_mods) {
    foreach($course_mods as $course_mod) {
        $DB->get_records_sql('some sql that selects the instance');
    }
}

return $result;

This last piece of code would eventually work, i would be able to able to dynamically create the query from the $course_mod variables such as $course_mod->instance, $course_mod->mod_name etc.
But i think this seems tough. Have any of you guys suceeded in getting the course_module instance in a easier way??
Thanks!!

A: This is the function i ended up using, to retrieve course module instances, its not so pretty, but whatever.
function get_all_course_modules($course_id) {
global $DB;
$course_mods = get_course_mods($course_id);
$result = array();
if($course_mods) {
    foreach($course_mods as $course_mod) {
        $course_mod->course_module_instance = $DB->get_record($course_mod->modname, array('id' =>$course_mod->instance ));
        $result[$course_mod->id] = $course_mod;
    }
}
return $result;
}


text:
Q: How to convert TestNG report index.html to pdf I am trying to convert TestNG report to PDF.
I have tried so many options present on google but all are converting HTML code to PDF but I required replica of index.html or emailable report to PDF.
Many are offering different plug-ins.. I do not have problem with them unless there presentation and information they sharing is some what equalvent to TestNG report.
I understand the index.html have other dependansies like css and other things like images.
Can anyone suggest a good option.
Please specify the jars required and import if possible.
It will really help :)

A: If you want a pdf report, you can use this TestNG extension: http://uttesh.com/pdfngreport/
Or you can write your own by implementing the IReporter interface, and maybe combined with IText or any other pdf generation lib.

A: If don't want to use above plugin and you just want to convert your index.html, you can refer the following thread.
A java library for converting xml/html to pdf


text:
Q: Reactive Webclient I would like to programmatically login to a web application using reactive web client . I could see I am authenticated correctly but could not able to reach redirected url.
I access my application http://localhost:8080/myapplogin
Here my web client response will have a Location header http://localhost:8082/portal/auth/home , and I would like the browser to redirect to this url
I could see the application in 8082 authenticating and redirecting(/auth/home) but do not know how to make my web client return the response and do the redirection through browser. Can someone help
@GetMapping("/myapplogin")
Publisher<ClientResponse> mylogin() {

    MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
    formData.add("username", "testuser");
    formData.add("password", "test password");

    return WebClient.create()
            .post()
            .uri("http://localhost:8082/portal/auth/login")
            .contentType(MediaType.APPLICATION_FORM_URLENCODED)
            .body(BodyInserters.fromFormData(formData))
            .exchange();
}

A: You need to return status codes that start with 3, and a Location header holding the URL to redirect to.
@GetMapping("/myapplogin")
public Mono<ResponseEntity> mylogin() {
    return login()
            .map(res -> ResponseEntity
                    .status(HttpStatus.PERMANENT_REDIRECT)
                    .location(URI.create("/auth/home"))
                    .build()
            );
}

where login is
Mono<ClientResponse> login() {

    MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
    formData.add("username", "testuser");
    formData.add("password", "test password");

    return WebClient.create()
            .post()
            .uri("http://localhost:8082/portal/auth/login")
            .contentType(MediaType.APPLICATION_FORM_URLENCODED)
            .body(BodyInserters.fromFormData(formData))
            .exchange();
}


text:
Q: Mapping array values to PickerItem: "Cannot read property 'displayName' of undefined" New to React, following a tutorial online. Tutor initially wrote this code:
<Picker selectedValue={this.props.day}>
  <Picker.item label='Monday' value='Monday' />
  <Picker.item label='Tuesday' value='Tuesday' />
  <Picker.item label='Wednesday' value='Wednesday' />
  <Picker.item label='Thursday' value='Thursday' />
  <Picker.item label='Friday' value='Friday' />
  <Picker.item label='Saturday' value='Saturday' />
  <Picker.item label='Sunday' value='Sunday' />
</Picker>

Rendered absolutely fine.
That being said, it's ugly code. I thought it would be cleaner to map this from an array, like so:
renderPickerItems() {
    return ['Monday', 'Tuesday', 'Wednesday',
            'Thursday', 'Friday', 'Saturday', 'Sunday'].map(day =>
        <Picker.item label={day} value={day} />
    );
}

So, I wrote that function and replaced the first block of code with just this:
<Picker selectedValue={this.props.day}>
  {this.renderPickerItems()}
</Picker>

That, however, did not work.
I received the error:
Unhandled JS Exception: TypeError: Cannot read property 'displayName' of undefined
I tried printing the return of that method to the console and I actually got React Native objects with the correct props passed in, so I'm not sure why it fails at all.
What I'm trying to accomplish seems very trivial and I can't seem to find anyone who had similar issues.
I'm on React Native version 0.51.0.
Thank you in advance.

A: Okay, so the answer was that I'm just terrible at following instructions.
The correct syntax is Picker.Item and not Picker.item.


text:
Q: Array of template objects I don't know how to resolve a problem with templates and inheritance.
In my code there is a templated class which looks more or less like:
template<typename T>
class Derived : public Base{
     T value;
public:
     Derived(T arg) { value=arg; };
     T getValue() { return value;};
};

class Base{
};

The only purpose of my Base class is to group an array of objects of the Derived class. The parameter T is generally double, float or complex, although int and structs might also become useful. (There should be several more similar derived classes with a few additional functions, later.)
I can create such a group
Base** M = new Base*[numElements];

and assign elements of the derived class to them, e.g.:
M[54] = new Derived<double>(100.);

But how can I find out that the 55th element has value 100 later?
I would need something like
virtual T getValue() = 0;

but T is a typename of the derived class and may be different for any two elements of this array.

A: The Visitor pattern is probably your best bet here.  The code iterating the array has to provide a "Visitor" object that knows how to handle each of the various types.
struct NumericVisitor
{
    virtual void visit(double) = 0;
    virtual void visit(int) = 0;
    virtual void visit(unsigned char) = 0;
};

struct Visitable
{
    virtual void visitValue(NumericVisitor& visitor) = 0;
};

template<typename T>
class Derived : public Visitable
{
     T value;
public:
     Derived(const T& arg) value(arg) {}
     void visitValue(NumericVisitor& visitor) { visitor.visit(value); }
};

Now you can define visitors for each operation you want to do on the collection, e.g. convert each element to a string, with a different format for each type, or store each element into a file, where each type can take up a different amount of space.

A: You could add overloaded has_value() methods to the Base class:
class Base
{
public:
    virtual ~Base () {}
    virtual bool has_value (int i) {return false;}
    virtual bool has_value (double d) {return false;}
    virtual bool has_value (const std::string& s) {return false;}
    // etc.
};

one of which you which you override in the Derived class:
template<typename T>
class Derived : public Base
{
     T value;
public:
     Derived(T arg) {value=arg;}
     T getValue() { return value;}

     virtual bool has_value (T t)
     {
         return t == value;
     }
};

E.g.:
bool test ()
{
    std::vector<Base*> bases;
    bases.push_back (new Derived<double> (1.234));
    bases.push_back (new Derived<int> (100));
    bases.push_back (new Derived<std::string> ("zap"));

    for(std::vector<Base*>::const_iterator iter = bases.begin (); iter != bases.end (); ++iter)
        if ((*iter)->has_value (100))
            return true;
    return false;
}

Note, you can't replace the has_value methods in the Base class with a single templated method as virtual methods can't be templated.

A: Add a method "getDouble" to your base class. The derived classes must then implement this method and cast their own type to double if required.

A: You can use dynamic_cast to know what a type is it (in addition to what @StackedCrooked says).
It would require some virtual functions defined in the base class, but you already need a virtual destructor there (to have the ability to delete values through base class pointers).
As an alternative, you might try boost::variant or boost::any :)

A: NO. It's not possible practically to have such function, because of 2 reasons:

*

*Base can't be template, as you
want a generic handle to store an
array which can contain any type of
Derived like <int>, <double>, <float>,
any struct <abc>.

*You can not have a template
virtual method inside Base,
because language doesn't allow it

Plain simple way to solve this problem is to have "getter" method for every type like get_double(), get_int(), get_float(), get_abc() and so on. However, your Base will be cluttered with such methods.

A: use boost::any to store the objects in the array. Then when you want to operate on it, you can use boost::any_cast to the possible types you have.


text:
Q: Regular expression validator accept decimal numbers 0 or 5 I'm trying to write a Regular Expression validator. It should accept numbers only with decimal part 0 or 5 only.
like,
Valid Numbers
0.5
1 (1.0)
1.5
2 (2.0)
2.5
 . . . etc.
Invalid Numbers
0.1
1.2
1.3
2.4
2.6
please help me... Thanks.

A: ^\d+(?:\.[05]0?)?$

works, but also allows leading zeroes like 00001.0. Is that OK?
If not, use
^(?:0|[1-9]\d*)(?:\.[05]0?)?$

This allows 0, 123, 0.00, 1.5, 2.50 etc. but rejects 00, 1.2, 1.500, -1 or .5.

A: Try this:
^[0-9]+(\.[05])?$

The (...)? means that the decimal part is  optional.


text:
Q: when are block scope variables allocated If I have a c function
int foo(int input)
{
    int x = 5;
    if( input == 0 ){
        int y = 6;
    } else {
        int z = 7;
    }
}

I know that that stack pointer is adjusted when we enter the function, and that makes space for the int x statement. And I know that y and z only exist within the scope of their respective blocks. But when and how is the space for them allocated?

A: It's up to the compiler, as long as the space lasts for at least the lifetime of the variable.
Typically, space for all automatic variables in a function is allocated on the stack at the start of the function, and freed when the function returns. Some variables might be placed in registers, if they don't need to have an address. Your variables will probably not exist at all, since they are never used.
Update: As noted in the comments, C (but not yet C++) allows dynamically-sized local arrays. Obviously, space for these can't be allocated until the size is known.

A: int foo(int input)
{ // BLOCK 1
    int x = 5;
    if( input == 0 )
    { // BLOCK 2
        int y = input * (x + 6);
        // other code here
    }
    else
    { // BLOCK 3
        int z = input + x;
        // other code here
    }
}

The compiler is able to optimize much of this away, but the high level language rules are this:
x is valid in BLOCK 1 and any sub-blocks (BLOCK 2 and BLOCK 3).
y is valid only in BLOCK 2.
z is valid only in BLOCK 3.
The first pass the compiler makes will generally leave these rules in tact.  Subsequent passes will typically see that you are not using the variables (or optimize how they are used) and may move them around or not store them in memory at all (e.g. they may simply be put in a register), so trying to equate their scope in the high level language to how it will be optimized in assembly is a fool's errand.


text:
Q: Unable to find expansion in regular perturbation problem
Consider the equation: $\varepsilon^{3}x+x=1$.

*

*Look for a rescaling of this equation in the form $x = \varepsilon^n X$ with $X \in O(1)$ and explain what value $n$ should take to find two more solutions.

I've plugged in the substitution into the original equation to get:
$$ \varepsilon^{n+3}X + \varepsilon^{n}X = 1 $$
but I don't know how to explain a value for $n$ that will yield two more solutions.
What am I supposed to be looking for here?
I would be very grateful if someone is able to point me in the right direction.


text:
Q: When computing the Legendre symbol $(\frac{3}{p})$, how to combine different congruences together into one statement? I try to find Legendre symbol for $\left(\dfrac{3}{p}\right)$.
This is what I did so far:
case 1: $p=3\mod{4}. $
so $\left(\dfrac{3}{p}\right)=-\left(\dfrac{p}{3}\right)$. now $\left(\dfrac{3}{p}\right)=-1$ iff $p=2 \mod{3}$
case 2: $p=1\mod{4}$
so $\left(\dfrac{3}{p}\right)=\left(\dfrac{p}{3}\right)$. now $\left(\dfrac{3}{p}\right)=1$ iff $p=1 \mod{3}$
Now, I don't know how to combine the cases (each case with itself and together).

A: As you've noted, the cases are as follows:

*

*If $p\equiv 3\bmod 4$, then  $(\frac{3}{p})=-(\frac{p}{3})$.

*

*If $p\equiv 1\bmod 3$, then $(\frac{p}{3})=1$, so $(\frac{3}{p})=-1$.

*If $p\equiv 2\bmod 3$, then $(\frac{p}{3})=-1$, so $(\frac{3}{p})=1$.

*If $p\equiv 1\bmod 4$, then  $(\frac{3}{p})=(\frac{p}{3})$.

*

*If $p\equiv 1\bmod 3$, then $(\frac{p}{3})=1$, so $(\frac{3}{p})=1$.

*If $p\equiv 2\bmod 3$, then $(\frac{p}{3})=-1$, so $(\frac{3}{p})=-1$.

Thus,
$$\left(\frac{3}{p}\right)=\begin{cases}
1 & \text{ if }\begin{cases}p\equiv 3\bmod 4 \text{ and }p\equiv 2\bmod 3,\text{ or }\\
p\equiv 1\bmod 4\text{ and }p\equiv 1\bmod 3, \end{cases}\\[0.1in]
-1 & \text{ if }\begin{cases}p\equiv 3\bmod 4 \text{ and }p\equiv 1\bmod 3,\text{ or }\\
p\equiv 1\bmod 4\text{ and }p\equiv 2\bmod 3, \end{cases}
\end{cases}$$
The Chinese remainder theorem tells you that any statement of the form
$$n\equiv a\bmod 3\quad\text{ and }\quad n\equiv b\bmod 4$$
can be converted, essentially uniquely, into a statement of the form
$$n\equiv c\bmod 12.$$
The best way of solving this sort of thing in general is to find an $x$ and $y$ such that
$$x\equiv 1\bmod 3 \quad\text{ and }\quad x\equiv 0\bmod 4$$
$$y\equiv 0\bmod 3\quad\text{ and }\quad y\equiv 1\bmod 4$$
so that the statement "$n\equiv a\bmod 3$ and $n\equiv b\bmod 4$" is equivalent to
$$n\equiv xa+yb\bmod 3\quad\text{ and }n\equiv xa+yb\bmod 4,$$
hence
$$n\equiv xa+yb\bmod 12.$$
For example, one choice that works is $x=4$ and $y=9$. Thus, to reformulate the statement that $$p\equiv 1\bmod 4\quad\text{ and }\quad p\equiv 2\bmod 3,$$
 you have that $9\cdot 1+4\cdot 2=17$, and
$$p\equiv 1\equiv 17\bmod 4\quad\text{ and }\quad p\equiv 2\equiv 17\bmod 3,$$ so that $$p\equiv 17\equiv 5\bmod 12.$$
You can check that this is correct:
$$\begin{array}{c|c|c|c|c|c|c|c|c|c|c|c|c|}
n \bmod 12 & 0 & 1 & 2 & 3 & 4 & \color{red}{\large \mathbf{5}} & 6 & 7 & 8 & 9 & 10 & 11 \\\hline
n\bmod 3 & 0 & 1 & 2 & 0 & 1 & \color{red}{\large \mathbf{2}} & 0 & 1 & 2 & 0 & 1 & 2 \\\hline
n\bmod 4 & 0 & 1 & 2 & 3 & 0 & \color{red}{\large \mathbf{1}} & 2 & 3 & 0 & 1 & 2 & 3
\end{array}$$

A: It's easy. You've shown $\rm\:(3\mid p) = ab,\:$ for $\rm\ a = (p\ mod\ 4) = \pm1,\:$ and $\rm\: b = (p\ mod\ 3) = \pm1.\:$  From CRT, $\rm\:p \equiv (a,b)\ mod\ (4,3)\iff p\equiv 4b\!-\!3a\,\ (mod\ 12).$  Thus for $\rm\:p\ne 2,3\:$ we have
$$\rm \left(\dfrac{3}p\right) = \left(\frac{3}{4b\!-\!3a}\right) = ab$$
e.g. $\rm\quad \begin{eqnarray}\rm 17\,=\,4(8)\!-\!3(5)\\ \rm so\ \ (a,b)=(5,8)\end{eqnarray}\,\bigg\rbrace\ \Rightarrow\ \left(\dfrac{3}{17}\right) = ab = (5\ mod\ 4)(8\ mod\ 3) = (1)(-1) = -1.$


text:
Q: How to ask Clang++ not to cache function result during -O3 optimization? This is my code:
int foo(int x) {
  return x + 1; // I have more complex code here
}
int main() {
  int s = 0;
  for (int i = 0; i < 1000000; ++i) {
    s += foo(42);
  }
}

Without -O3 this code works for a few minutes. With -O3 it returns the same result in no time. Clang++, I believe, caches the value of foo(42) (it's a pure function) and doesn't call it a million times. How can I instruct it NOT to apply this particular optimization for this particular function call?

A: Out of curiosity, can you share why you would want to disable that optimization?
Anyway, about your question:
In your example code, s is never read after the loop, so the compiler would throw the whole loop away. So let's assume that s is used after the loop.
I'm not aware of any pragmas or compiler options to disable a particular optimization in a particular section of code.
Is changing the code an option?
To prevent that optimization in a portable manner, you can look for a creative way to compute the function call argument in a way such that the compiler is no longer able to treat the argument as constant. Of course the challenge here is to actually use a trick that does not rely on undefined behavior and that cannot be "outsmarted" by a newer compiler version.
See the commented example below.

*

*pro: you use a trick that uses only the language that you can apply selectively

*con: you get an additional memory access in every loop iteration; however, the access will be satisfied by your CPU cache most of the time

I verified the generated assembly for your particular example with clang++ -O3 -S. The compiler now generates your loop and no longer caches the result. However, the function gets inlined. If you want to prevent that as well, you can declare foo with __attribute__((noinline)), for example.
int foo(int x) {
  return x + 1; // I have more complex code here
}

volatile int dummy = 0; // initialized to 0 and never changed

int main() {
  int s = 0;
  for (int i = 0; i < 1000000; ++i) {
    // Because of the volatile variable, the compiler is forced to assume
    // that the function call argument is different for each loop
    // iteration and it is no longer able to use a cached result.
    s += foo(42 + dummy);
  }
}


text:
Q: What is the specific feature delta between Salesforce.com and Force.com app licenses? I am aware of the differences between Salesforce.com and Force.com but I am unsure what the specific, granular feature differences between the two licenses are.
For example, what standard objects can one have with a Force.com app license? It seems to be Opportunity, Account and User only but some say Case as well. And if Case, then are cases to be sent externally and internally supported or just internally?
It seems that such a feature delta document doesn't actually exist and to get it, one would need to liaise with the Salesforce Account Executive.
I am curious to see if there is a specific and granular feature delta document that is available to view?

A: you can find these references useful

*

*Difference between force.com and salesforce.com?

*https://www.zarantech.com/blog/difference-between-salesforce-com-and-force-com/


text:
Q: How to filter on calculated model values using list comprehension I have a model where I calculate totals
class Material(models.Model):
    version = IntegerVersionField( )
    code = models.CharField(max_length=30)
    name = models.CharField(max_length=30)
    slug = models.SlugField(max_length=80, blank=True)
    description = models.TextField(null=True, blank=True)
    min_quantity = models.DecimalField(max_digits=19, decimal_places=10)

    def _get_totalinventory(self):
        from inventory.models import Inventory
        return Inventory.objects.filter(warehouse_Bin__material_UOM__UOM__material=self.id, is_active = True).aggregate(Sum('quantity'))

    total_inventory = property(_get_totalinventory)

    def _get_totalpo(self):
        from purchase.models import POmaterial
        return POmaterial.objects.filter(material=self.id, is_active = True).aggregate(Sum('quantity'))

    total_po = property(_get_totalpo)

    def _get_totalso(self):
        from sales.models import SOproduct
        return SOproduct.objects.filter(product__material=self.id ,  is_active=True ).aggregate(Sum('quantity'))

    total_so = property(_get_totalso)

So far so good , my calculate fields calculate correctly and are displayed in template without any problem
Since I can not filter directly by the property As suggested i  am using python  list comprehension
So this is what I wrote that does give me output and no errors .
    po_list = [n for n in Material.objects.all()

if ((F('total_inventory') + F('total_po') - F('total_so')) < F('min_quantity'))]

However  Current list comprehension doesn't filter correctly
I am getting output that should be filtered out. What i am doing  wrong?
It is not filtering anything it is just returning the list a it is

A: I doubt you can call F on model class methods. You can instead call the methods directly from the objects in the list comprehension:
po_list = [n for n in Material.objects.all() if (n.total_inventory['quantity__sum']
                                                 + n.total_po['quantity__sum']
                                                 - n.total_so['quantity__sum'])
                                                 < n.min_quantity]


text:
Q: How do I hide a text box in html I am a newbie in programming and I started learning programming a few days ago and I want to add a hidden text box about the browser how do I do it with thanks to everyone.
<input type="text" name="url" value="<?php echo $w2;?>"/>

A: Just use type="hidden":
<input type="hidden" name="url" value="<?php echo $w2;?>" />

A: You can do this by changing type form text to hidden
try this
<input type="hidden" name="url" value="<?php echo $w2;?>"/>

A: There are two things you can do, create a hidden type input
<input type="hidden" name="url" value="<?php echo $w2;?>"/>

or hide input using css
.hidden{
   display:none;
}

<input type="text" class="hidden" name="url" value="<?php echo $w2;?>"/>

Both ways work, utilities vary from case to case, css is best used if at some point is going to show the input.

A: <input type="hidden" id="custId" name="custId" value="3487">

The "type="hidden"" would hide it.


text:
Q: android app development multiple screen size We are developing an android application. Actually we are iPhone developers. One challenge we faced during the android development than iOS development is, the wide variety of devices the android application going to be used. From the link http://developer.android.com/guide/practices/screens_support.html we got some useful information.
1)
But we think that the testing effort we need to more than that of iOS in android based on the screen sizes. Can somebody suggest us to the method the do various sized device testing for android devices.
2)
Or at least we can inform our customer that we will test in such devices only. But our point is how can we say that, like device names like Samsung S2, Samsung Galaxy Note or Devices like 640X480 size, 320X240 size etc? Please advise us.
3)
Do we have any size specification for images for small, normal, large, xlarge and ldpi, mdpi, hdpi, xhdpi ?

A: Developing for multiscreen, First make sure that the AndroidManifest.xml specifies the correct target SDK. For android 2.2, the target SDK level is 8. For processing it requires at least SDK level 7 to run.
<user-sdk android:minSdkversion="7" android:targetSdkversion="8"></user-sdk>

Use this <user-sdk> element, so that the platform will consider that your android app is for 2.2, otherwise, it takes it as for Android 1.5.
The Display metrics values for "normal-hdpi" screen is
DisplayMetrics{density=1.5, width=854, height=480, scaledDensity=1.5, xdpi=240.0, ydpi=240.0}

For size classification use this configuration class
Configuration config = getResources().getConfiguration();
int size = config.screenLayout & config.SCREENLAYOUT_SIZE_MASK;
if (size == config.SCREENLAYOUT_SIZE_SMALL)
{
  // use special layout for small screens
}

Hopefully this solution will be useful to you.


text:
Q: Opacity and grayscale filter of background image. Making it black and white and transparent I wanted to make my background image semi-transparent and in grayscale / black and white. I made the following code by combining codes from two different threads of Stackoverflow)
body {
    position: relative;
    background-size: 100% 100%;
    background-repeat: no-repeat;
}
body::after {
  content: "";
  background: url('<?php echo $background[0]; ?>');
  opacity: 0.5;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  position: absolute;
  z-index: -1;
    filter: grayscale(100%); /* Current draft standard */
    -webkit-filter: grayscale(100%); /* New WebKit */
    -moz-filter: grayscale(100%);
    -ms-filter: grayscale(100%);
    -o-filter: grayscale(100%); /* Not yet supported in Gecko, Opera or IE */
    filter: url(resources.svg#desaturate); /* Gecko */
    filter: gray; /* IE */
    -webkit-filter: grayscale(1); /* Old WebKit */
}

This is how this is working :
Chrome : working
Firefox : background image is not visible
Safari : opacity works, filter does not
IE recent version : opacity works, filter does not
Can anyone enlighten me ?
Thanks.

A: The unprefixed should be at the bottom!
Also, if you don't have content on your page, you should give min-height to the body:

    html{
      height: 100%;
    }
    body {
        position: relative;
        background-size: 100% 100%;
        background-repeat: no-repeat;
      min-height: 100%;
    }
    body::after {
      content: "";
      background: url('http://jsequeiros.com/sites/default/files/imagen-cachorro-comprimir.jpg') no-repeat center center;
      background-size:cover;
      opacity: 0.5;
      top: 0;
      left: 0;
      bottom: 0;
      right: 0;
      position: absolute;
      z-index: -1;
      -webkit-filter: grayscale(1); /* Old WebKit */
      filter: grayscale(1);
    }
A Tiger!

Also, you don't need the moz, ms or o prefix as they whether support it unprefixed or don't support it at all.
Codepen: http://codepen.io/vandervals/pen/VLmbpx


text:
Q: Xampp not accessing htdocs folder on localhost My localhost is not pointing to ht docs when I type in browser localhost it directly points to a sub-directory which is in ht docs like this ht docs>> blog>>'index. Php it is directly pointing to index.php which is inside blog folder and blog folder is inside ht docs. What should I do?
This  blog  folder  is a Laravel project.


text:
Q: Redirect Wordpress tags to homepage htaccess I want to delete all tag product pages and I want to redirect all my wordpress product tags to homepage.
I found a lot of answers on the web and on the stackoverflow but the general answers doesn't work for me and I don't know why.
I changed the permalink in WP from tag to eticheta-produs, so my product tags looks like:
https://www.domain.tld/eticheta-produs/present
instead of default WP tags
https://www.domain.tld/tag/present
So, I tried:
# Redirect tag 301
RewriteEngine On
RewriteRule ^eticheta-produs/(.*)$ http:/www.domain.tld/ [R=301,L]

And https:
# Redirect tag 301
RewriteEngine On
RewriteRule ^eticheta-produs/(.*)$ https:/www.domain.tld/ [R=301,L]

I stoped caching throw litespeed plugin, I tried opening tag pages throw incognito sessions of different browsers but the redirect doesn't work.

A: Try this. It will redirect anything from eticheta-produs and its subfolders to your root domain.
RewriteEngine On
RewriteBase /
RedirectMatch 301 ^/eticheta-produs/(.*)$ http://domain\.tld/


text:
Q: ng-repeat in table , multi-level json data I have some table html and having trouble ng-repeating from json data with multiple levels.
I have the TR working, creating a list of employee names each in a TD, however I cannot make the second TD repeat for each Timestamp in each first row of absence which should create 7 TDs.
Any idea what might I be doing wrong?
Output I would like to have:
| DisplayName | 0 | 1 | 2 | 3 | 4 | 5 | 6 |

staff-calendar-table-row.html

  {{row.Details.DisplayName}}
  cell - {{$index}}

Json Data:
{
  "d": {
    "__type": "IntegratedCalendarDetails:#Common.Entities.Integrated_Calendar",
    "Employee": [{
        "__type": "Employee:#Common.Entities.Integrated_Calendar",
        "Absence": [{
            "__type": "Absence:#Common.Entities.Integrated_Calendar",
            "Timestamp": ["\/Date(-62135596800000)\/", "\/Date(-62135596800000)\/", "\/Date(-62135596800000)\/", "\/Date(1443650400000+0200)\/", "\/Date(-62135596800000)\/", "\/Date(-62135596800000)\/", "\/Date(-62135596800000)\/"],
            "Type": "Vacation Leave"
          }
        ],
        "Details": {
          "__type": "User:#Common.Entities",
          "DisplayName": "Alan"
        }
      }, {
        "__type": "Employee:#Common.Entities.Integrated_Calendar",
        "Absence": [{
            "__type": "Absence:#Common.Entities.Integrated_Calendar",
            "Timestamp": ["\/Date(-62135596800000)\/", "\/Date(1443477600000+0200)\/", "\/Date(-62135596800000)\/", "\/Date(-62135596800000)\/", "\/Date(-62135596800000)\/", "\/Date(-62135596800000)\/", "\/Date(-62135596800000)\/"],
            "Type": "Other Leave"
          }
        ],
        "Details": {
          "__type": "User:#Common.Entities",
          "DisplayName": "Alistair"
        }
      }, {
        "__type": "Employee:#Common.Entities.Integrated_Calendar",
        "Absence": [{
            "__type": "Absence:#Common.Entities.Integrated_Calendar",
            "Timestamp": ["\/Date(-62135596800000)\/", "\/Date(-62135596800000)\/", "\/Date(-62135596800000)\/", "\/Date(-62135596800000)\/", "\/Date(1443736800000+0200)\/", "\/Date(-62135596800000)\/", "\/Date(-62135596800000)\/"],
            "Type": "Vacation Leave"
          }, {
            "__type": "Absence:#Common.Entities.Integrated_Calendar",
            "Timestamp": ["\/Date(-62135596800000)\/", "\/Date(-62135596800000)\/", "\/Date(1443564000000+0200)\/", "\/Date(-62135596800000)\/", "\/Date(-62135596800000)\/", "\/Date(-62135596800000)\/", "\/Date(-62135596800000)\/"],
            "Type": "Working from Home"
          }
        ],
        "Details": {
          "__type": "User:#Common.Entities",
          "DisplayName": "Andrew"
        }
      }
    ]
  }
}

Table HTML:

Directive Code:
  module.directive('staffCalendarTableRow', [function(){
    return {
      restrict: 'A',
      templateUrl: 'features/staff-calendar/partials/staff-calendar-table-row.html',
      controller: function($scope) {

      },
      controllerAs: 'StaffCalendarController'
    }
  }]);


text:
Q: Has Chrome improperly implemented the dataTransfer object? When I do this in dragstart event:
e.dataTransfer.setData('text/plain', 'text');
e.dataTransfer.setData('text/html', 'html');
e.dataTransfer.setData('application/x-bookmark', 'bookmark');

and this in drop event:
for (var i = 0; i < e.dataTransfer.types.length; i++) {
   var type = e.dataTransfer.types[i];
   console.log(type + ":" + e.dataTransfer.getData(type));
}

I was supposed to have:
text/plain:text
text/html:html
application/x-bookmark:bookmark

as what I got in FF, but actually I got:
Text:text
text/plain:text

in Chrome. Where are those data gone? Does this mean chrome did not implement the dataTransfer object properly? And what can I do about this?
I ran this in Chrome 4.0.266.0

A: Yes it is a bug in Chrome. See issues 31037 and issue 30240 in the chromium issue tracker (chromium is the open source version of google chrome). I see no other solution than waiting for the bug to be fixed. You can help them fixing it by providing a simple test case.


text:
Q: google marker filter using javascript from json data I have this json object:
{
   "tcu_pos_list": [
      {
         "latitude":"23",
         "tcu_id":1,
         "longitude":"23"
      },
      {
         "latitude":"11",
         "tcu_id":4,
         "longitude":"11"
      },
      {
         "latitude":"3",
         "tcu_id":5,
         "longitude":"34"
      }
   ]
}

In order to set all the markers in the map I create this function:
var map;
var marker = [];

function setMarker() {
    $.getJSON('http://127.0.0.1:8000/locator/tcu/position/', function(car_pos) {

        for (var i = 0; i < car_pos["tcu_pos_list"].length; i++){

            marker [i] = new google.maps.Marker({
                map: map,
            });

            var userLat = car_pos["tcu_pos_list"][i].latitude;
            var userLon = car_pos["tcu_pos_list"][i].longitude;
            var position = new google.maps.LatLng(userLat,userLon);
            marker[i].setPosition(position);
            map.setCenter(position);

        }
    });
}

I want to check if my Json object has new positions so I check it every 5 seconds:
setInterval(function() {
    setMarker();
}, 5000);

This is working good, the problem is when I try to filter a google marker. The idea is to select a tcu_id and display only that marker position.
For that in a html selector I create a function onchange.
<div class="select-style">
    <select id="Selector" onchange="filter_tcu()">
        <option value="">Please select
        <option value="1">1
        <option value="4">4
        <option value="5">5
    </select>
</div>

<script>
function filter_tcu() {
    var tcu_id = document.getElementById("Selector").value;
    console.log(tcu_id)

    $.getJSON('http://127.0.0.1:8000/locator/tcu/position/', function(car_pos) {

        for (var i = 0; i < car_pos["tcu_pos_list"].length; i++){

            if( tcu_id == car_pos["tcu_pos_list"][i].tcu_id) {

                marker [i] = new google.maps.Marker({
                    map: map,
                });

                var userLat = car_pos["tcu_pos_list"][i].latitude;
                var userLon = car_pos["tcu_pos_list"][i].longitude;
                var position = new google.maps.LatLng(userLat,userLon);
                marker[i].setPosition(position);
                map.setCenter(position);
            }

            else {
                marker [i].setMap(null);
            }

        }
    });
}

When I select a value the marker is filtered but after 5 seconds (set Interval) all markers are shown again. I would be gratefull if somebody could help me.

A: Get rid of your setMarker function.
Update your setInterval to just call the filter_tcu instead.
Update the filter_tcu function to check if no filter is selected, just display the marker.  e.g.
if (tcu_id.length == 0 || tcu_id == car_pos["tcu_pos_list"][i].tcu_id) {


text:
Q: How was this dot identified as a mystery planet originally (Pluto in this case)? I was watching a documentary on a mission to study Pluto. At 21:11, an image is presented with an arrow mark pointing a small dot which is now identified as Pluto.
As there are hundreds of dots on the image (I'm not sure what kind of an image this is as I'm not an astrophysicist), how can stars, planets, asteroids and other objects be distinguished in this image? And what kind of an image is this?

A: One point doesn't tell you much of anything, other than that there is probably something in that direction. Pluto was discovered the same way many asteroids are, by comparing pictures of the same star field at different times, seeing if anything changes.
Below is the discovery image from Wikipedia.

The dot moved across the image, while all the stars stayed the same. Of course this is not conclusive proof. More followup was done to ascertain that we really were seeing something orbiting the Sun far away. After all, it is possible that the two dots are unrelated - they could be fleeting glimpses of two different asteroids, or two unfortunate cosmic rays (though the photographic plates used are less susceptible to this than CCD's).
By the way, they had a special machine back in the old days for doing this sort of search - a blink comparator. Astronomers would mount the (glass) photographic plates in the machine, and rapidly switch the view from one to the other. They simply relied on their eyes to detect differences between the frames.

Once you know the orbit, you can predict precisely where Pluto will be at any given time. This enables you to figure out which "dot" it is in other photographs.
I should also mention that with more information than a single broadband image, one can infer more things about point sources. If you can take images in multiple bands, or better yet do spectroscopy, you can see if the light emitted by the object is consistent with various types of stars, for instance.


text:
Q: How to create least-cost path between two polygons with GRASS? I am completely a beginner in GRASS but I would like to use it to have the cumulative cost of moving between two polygons. More exactly, I would like to get the smallest cost from any point situated at the edge of one polygon (polygon A) to any point situated at the edge of another polygon (polygon B).
Until now, I used the function CostDistance and CostPath of ArcGIS like this:
CostDistance("start_polygon", "costs.tif", "", "outCostLink.tif")
CostPath("end_polygon", "outCostDist.tif", "outCostLink.tif", "EACH_ZONE","FID")

I would like to do the same thing with GRASS. I think that the function r.cost allows to do this. But the problem is that I don't understand how to specify in parameters the two polygons in GRASS ?
I have :

*

*a cost raster where each cell has a cost value.

*a shapefile for the first polygon

*a shapefile for the second polygon

Have you got an example of how to use r.cost with two polygons ?
Thanks very much for your help.

A: I know this is an old question, but here's a crack at the answer. My approach seems a little convoluted to me, but it's the best I could think of. I used GRASS 6.4.
g.region s=0 w=0 e=100 n=100 res=1

# set up some polygons
echo "B 4
10 10
10 20
20 10
10 10" | v.in.ascii -n input=- output=polygonA format=standard

echo "B 4
90 90
90 80
80 90
90 90" | v.in.ascii -n input=- output=polygonB format=standard

r.mapcalc cost=1.0

# generate points on the edges of the polygons
# dmax should probably be set to less than your raster resolution
v.to.points -i input=polygonA output=polygonA_pts dmax=1
v.to.points -i input=polygonB output=polygonB_pts dmax=1

# compute the least cost path
# this starts the lcp from the center of polygon B, but I imagine the lcp will
# pass through the polygon boundary at the point that would result in the lcp
r.cost input=cost output=cummulative_cost start_points=polygonA_pts stop_points=polygonB_pts
v.centroids input=polygonB output=polygonB_cent
v.to.points input=polygonB_cent output=polygonB_cent_only type=centroid
r.drain input=cummulative_cost output=lcp voutput=lcp vector_points=polygonB_cent_only

# since the lcp starts at the center of polygonB,
# split the lcp at the polygon edge to get a new starting point on the edge of the polygonB
# then run r.drain again to get the final result from edge of polygon to edge of polygon
v.patch input=lcp,polygonB output=temp
v.clean input=temp output=lcp_from_edge tool=break error=new_starting_point
r.drain input=cummulative_cost output=lcp voutput=lcp vector_points=new_starting_point --o


text:
Q: How to deal with different lengths of dependent variables for Multiple Multivariate regression? So this question is probably part statistics and part r studio related.
I want to run a Multiple Multivariate Regression with 13 dependent variables and 4 predictors.
The 13 variables are scales from 1-6, which I coded as a numeric variable.
Unfortunately, some of these variables don't show the full range, therefore have different lengths.
Question 1: I believe I read somewhere, that this poses a problem for the calculations and should therefore be addressed. Is that true for this type of code?
Question 2: If it does pose a problem in interpreting results, how can I fix this? Is it enough to standardize the dependent variables maybe? How do I do this in R though?
(As an example I am using the Quartet data set from R, just rounding each variable)
Quartet

Quartet$y1 <- round(Quartet$y1, 0)
Quartet$y2 <- round(Quartet$y2, 0)
Quartet$y3 <- round(Quartet$y3, 0)
Quartet$y4 <- round(Quartet$y4, 0)

summary(Quartet)

M <- lm(cbind(y3, y4) ~ x + x4, data = Quartet)

summary(M)

Keep in mind, this code runs smoothly without an error, that isn't the issue.
I would need to do extra diagnostic checking at this point. But I don't know just in how far the results are rigged just by having different ranges for y3 (5-12) and y4 (5-13).
Thank you!


text:
Q: Play Games Achievements not getting unlocked I've looked all over the web for this one and I couldn't find anything, what am facing here is that whenever I try to unlock an achievement via the code:
Games.achievements.unlock(getApiClient(), "id");

the damn thing won't unlock ! and I have published my app on the play games and its live, the hash keys are sure to be correct because it logs into the play games, I've checked the key hash for each achievements and nothing is wrong there either, I started pulling my hair after trying:
Games.achievements.unlockImmediate();

So I came running to you guys :)

A: When you use unlockImmediate(), you can set a listener to check for the outcome of unlocking an achievement.
Use this code:
Games.Achievements.unlockImmediate(getApiClient(), "id").setResultCallback(new ResultCallback<UpdateAchievementResult>() {

            @Override
            public void onResult(UpdateAchievementResult res) {
                System.out.println(res.getStatus().getStatusCode());
            }

        });

This will unlock the achievement, then give you a status code to tell you the result. Check the code you get against this list of codes. It should be STATUS_OK which has a status code of 0. If it isn't, you can check what it returned to see why it went wrong.
Good Luck.


text:
Q: How to PIN TabLayout I want set my animated ImageView like background for all AppBarLayout. But I can't set app:layout_collapseMode="pin" in TabLayout.
Example expanded: ExpandedAppBar;
Example collapsed: CollapsedAppBar.
My code (PanningView extends ImageView):
<android.support.design.widget.AppBarLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/appBarLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/transparent">

<android.support.design.widget.CollapsingToolbarLayout
    android:id="@+id/collapsingToolbarLayout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    app:contentScrim="?attr/colorPrimary"
    app:layout_scrollFlags="scroll">
    <com.peter.press.widget.panningView.PanningView xmlns:custom="http://schemas.android.com/apk/res-auto"
        android:id="@+id/panningView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="matrix"
        android:src="@drawable/test"
        custom:panningDurationInMs="@integer/panning_view_fade_duration"
        app:layout_scrollFlags="scroll|enterAlwaysCollapsed|exitUntilCollapsed"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        app:layout_scrollFlags="scroll|enterAlwaysCollapsed|exitUntilCollapsed">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:color/transparent" />

        <ImageView
            android:id="@+id/toolbar_image"
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:src="@drawable/test" />
    </LinearLayout>
    <android.support.design.widget.TabLayout
        android:id="@+id/tabLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/transparent"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:tabMode="scrollable"
        app:layout_collapseMode="pin"
        android:layout_gravity="bottom"
        />
</android.support.design.widget.CollapsingToolbarLayout>


text:
Q: Ejercicio condicionales javaScript Estoy intentando hacer un ejercicio simple en javaScript pero por alguna razón no me sale correctamente.
Tengo que lanzar una ventana que le pida al usuario introducir el precio del viaje y en otra ventana que introduzca el dinero del que dispone.
Si el dinero del que dispone es mayor o igual que el precio del viaje muestra "Sácate el billete" y actualiza el dinero disponible.
En caso negativo lanza un mensaje que traiga: "No dispones de suficiente dinero para viajar".
Por alguna razón siempre me entra por el else.
Espero vuestras respuestas,
gracias.

Introduje 400 en "Introduzca precio de viaje" y 1000 en "Introduzca dinero disponible"

    Ejercicio condicionales

    Viaje a Punta Cana
<script>
    var precioViaje= prompt("Introduzca el precio del viaje");
    var dineroDisponible= prompt("Introduzca el dinero disponible");

    if(dineroDisponible>=precioViaje){

        alert("Sácate el billete");
        dineroDisponible=dineroDisponible-precioViaje;
    }else{

        window.alert("No dispones de suficiente dinero para viajar");
    }

    window.alert("Te quedan "+ dineroDisponible +" euros.");

</script>

A: convierte los prompt en int de esta manera
var precioViaje= prompt("Introduzca el precio del viaje");
var dineroDisponible= prompt("Introduzca el dinero disponible");
var num1 = parseInt(precioViaje);
var num2 = parseInt(dineroDisponible);

if(num2>=num1){

    alert("Sácate el billete");
    num2=num2-num1;
}else{

    window.alert("No dispones de suficiente dinero para viajar");
}

window.alert("Te quedan "+ num2 +" euros.");

La función parseInt te devuelve el primer numero de la cadena, si el primer número de una cadena no se puede convertir en int el valor que devuelve es NaN. En el caso de querer convertir por ejemplo "123.45" devolvería el primer número 132 y en el caso de "1234 prueba 34" el valor devuelto sería 1234.