How to select sequenc data

Question: I dont know how can I start with filttering the data were are 3 and more sequenc data.For example my basic data are numbers under the column stevilo (188774,18775,18814) or even more than 3 (maybe is posibility to change the sequece number (more than 3, more than 2 or exactly number 3)).
    stevilo             cas F
1   Pattern number : 1  B3341
2   Pattern number : 2  B3342
7   18774               18.11.2019 11:07
8   18775               18.11.2019 11:09
8   18776               18.11.2019 11:20
26  Pattern number : 1  B2633-CELA
56  18814               18.11.2019 12:44
57  18815               18.11.2019 12:45
63  Pattern number : 1  B3343
70  18819               18.11.2019 12:52
76  Pattern number : 1  B1822A
327 19022               18.11.2019 19:21
328 19023               18.11.2019 19:23
329 19024               18.11.2019 19:25
330 19025               18.11.2019 19:26
331 19026               18.11.2019 19:27
332 19027               18.11.2019 19:28
333 19028               18.11.2019 19:30
334 19029               18.11.2019 19:31
335 19030               18.11.2019 19:32
345 19040               18.11.2019 19:46
346 19041               18.11.2019 19:48
349 19044               18.11.2019 20:21

I want to copy the data when are 3 sequence data for example (19022, 19023, 19024) and my out put data will be like :
1   Pattern number : 1  B3341
2   Pattern number : 2  B3342
7   18774               18.11.2019 11:07
8   18775               18.11.2019 11:09
8   18776               18.11.2019 11:20
76  Pattern number : 1  B1822A
327 19022               18.11.2019 19:21
328 19023               18.11.2019 19:23
329 19024               18.11.2019 19:25
330 19025               18.11.2019 19:26
331 19026               18.11.2019 19:27
332 19027               18.11.2019 19:28
333 19028               18.11.2019 19:30
334 19029               18.11.2019 19:31
335 19030               18.11.2019 19:32

Comment: Do you truly need to verify there is a pattern by checking the difference between consecutive rows, or like in your example, is it enough to just assume everything below a row with `'Pattern number : XX'` belongs to the same "pattern"?
Comment: I need sequence datas like my out put up.
Answer: First we add an auxillary column group to indicate what group (starts with 'Pattern number ...' row) the row belongs to. Then we transform this column based on the numbers in the stevilo column into a True/False indicator using the find_pattern function:

groups with just the header and no numbers (length of 1) are included
groups with less than 4 rows (including header row) are excluded
all remaining groups are (partially) included up to the first row where the numbers are non-consequtive

def find_pattern(x):
    if len(x) == 1:
        return True
    if len(x) < 4:
        return False
    x = pd.to_numeric(x, 'coerce')
    diff = x.values - x.shift().values
    with np.errstate(invalid='ignore'):
        end = np.argwhere(diff > 1)
    if len(end) == 0:
        return True
    else:
        end = end[0][0]
        diff[:end] = True
        diff[end:] = False
        return diff

Example for your sample data:
import pandas as pd
import numpy as np
import io

s = """    stevilo             cas F
1   Pattern number : 1  B3341
2   Pattern number : 2  B3342
7   18774               18.11.2019 11:07
8   18775               18.11.2019 11:09
8   18776               18.11.2019 11:20
26  Pattern number : 1  B2633-CELA
56  18814               18.11.2019 12:44
57  18815               18.11.2019 12:45
63  Pattern number : 1  B3343
70  18819               18.11.2019 12:52
76  Pattern number : 1  B1822A
327 19022               18.11.2019 19:21
328 19023               18.11.2019 19:23
329 19024               18.11.2019 19:25
330 19025               18.11.2019 19:26
331 19026               18.11.2019 19:27
332 19027               18.11.2019 19:28
333 19028               18.11.2019 19:30
334 19029               18.11.2019 19:31
335 19030               18.11.2019 19:32
345 19040               18.11.2019 19:46
346 19041               18.11.2019 19:48
349 19044               18.11.2019 20:21"""

df = pd.read_fwf(io.StringIO(s), [(0,3),(4,23),(24,222)]).set_index('Unnamed: 0')
del df.index.name

df['group'] = np.where(df.stevilo.str.startswith('Pattern'), df.index, np.nan)
df.group = df.group.ffill()

df.group = df.groupby('group').stevilo.transform(find_pattern).astype(bool)
res = df[df.group].drop('group',1)

Outpuf of print(res):
                stevilo             cas F
1    Pattern number : 1             B3341
2    Pattern number : 2             B3342
7                 18774  18.11.2019 11:07
8                 18775  18.11.2019 11:09
8                 18776  18.11.2019 11:20
76   Pattern number : 1            B1822A
327               19022  18.11.2019 19:21
328               19023  18.11.2019 19:23
329               19024  18.11.2019 19:25
330               19025  18.11.2019 19:26
331               19026  18.11.2019 19:27
332               19027  18.11.2019 19:28
333               19028  18.11.2019 19:30
334               19029  18.11.2019 19:31
335               19030  18.11.2019 19:32

(if multiple group header rows should have the same index value you'll have to reset the index to a range index and use this new index for the group values)
Comment: Thank you very much. It s very helpfull. But I have another error:  ValueError: operands could not be broadcast together with shapes (436,) (5135,) ().
Comment: in the example data or in your real data? At what line of code?
Comment: In my real data, I will try again.
----> 4 g['group'] = np.where(g.stevilo.str.startswith('Pattern'), df.index, np.nan)
Comment: Its working! Thank you again, I made mistake (wrong datafram name).

How to select sequenc data


How to create a matrix without a loop

Question: I would like to know if it is possible to create a matrix without writing any loop. I try to start with a simple list of range but I don't know how to go further.
Enumerable.Range(1, 4).ToList()

Here the code with 3 loops :
    private static int[][] calculPossibleCombinaison(){
    int l;
    for (int i = 1; i < 5; i++) {
        for (int j = 1; j < 5; j++) {
            for (int k = 1; k < 5; k++) {
                l = (i*j*k)-1;
                combinaison[l][0] = i;
                combinaison[l][1] = j;
                combinaison[l][2] = k;
                console.writeline("["+combinaison[l][0]+","+combinaison[l][1]+","+combinaison[l][2]+"]");
            }
        }
    }
    return combinaison;
}

This is the result of my matrix

[1,1,1]
[1,1,2]
[1,1,3]
[1,2,1]
[1,2,2]
[1,2,3]
[1,3,1]
[1,3,2]
[1,3,3]
[2,1,1]
[2,1,2]
[2,1,3]
[2,2,1]
[2,2,2]
[2,2,3]
[2,3,1]
[2,3,2]
[2,3,3]
[3,1,1]
[3,1,2]
[3,1,3]
[3,2,1]
[3,2,2]
[3,2,3]
[3,3,1]
[3,3,2]
[3,3,3]

Do you think it's possible ?
Thx a lot
Comment: you need to use linq or lambda expression for it Check these link: http://stackoverflow.com/questions/3183626/convert-nested-for-loops-into-single-linq-statement;
http://codereview.stackexchange.com/questions/105336/convert-foreach-loop-into-linq-in-c
Comment: What is the point of avoiding loops? Even with Linq you´d use them internally. There is no way on going through all the cells without iterating the list/matrix/whatever.
Answer: Try this
Enumerable.Range(1, 3)
.SelectMany(x => Enumerable.Range(1, 3), (x, y) => new[] {x, y})
.SelectMany(x => Enumerable.Range(1, 3), (x, y) => new[] {x[0], x[1], y}).ToArray();

Answer: You may use LINQ instead of for loops but still you can get rid of loops. using Linq is cool but it has loop implantation inside it. as if you put those for loops inside a function and then call it.
It can't be done without loops.
Enumerable.Range(1, 4).ToList().ForEach(i=>{
      Enumerable.Range(1, 4).ToList().ForEach(j=>{
             Enumerable.Range(1, 4).ToList().ForEach(k=>{
                    l = (i*j*k)-1;
                combinaison[l][0] = i;
                combinaison[l][1] = j;
                combinaison[l][2] = k;
            });
      });
});

Recursive:
int i=0,j=0,k=0;

    public void MakeMartix(){

         if(i>3){i=0;j++;}
         if(j>3){j=0;k++;}
         if(k>4)return;
         l = (i*j*k)-1;
         combinaison[l][0] = i;
         combinaison[l][1] = j;
         combinaison[l][2] = k;
              i++;
              MakeMatirx();
    }

Comment: Can it be done with link or something else and how? I would like to have one line for that like Enumerable.Range(1, 4).ToList()
Comment: It can but as I said its like hiding the loops and not, not using them
Comment: Do you know how to do it? because I do not. And I know it's like hidding them.
Comment: @stix I added a recursive version code. have a look at it.
Comment: Thx but this is not what I asked. Look the answer of @tym32167

How to create a matrix without a loop


Yii2 - Save and display DateTime in different formats

Question: I need save attribute "created_at" in MySQL formatt "yyyy-mm-dd hh:mm:ss", but display in php format "d-m-Y".
It´s works fine in create scenario but when i update any attribute and save, its overwrite "created_at" and set like "0000-00-00 00:00:00" automatically in DB.
I use two functions in the model beforeValidade() and afterFind().
common\models\Oficios.php
public function beforeValidate()
{
    if ($this->scenario == self::SCENARIO_CREATE){
        $this->created_at = date('Y-m-d H:i:s');
    }else {
        $this->created_at = $this->created_at;
    }

    return parent::beforeValidate();
}

public function afterFind ()
{
    // convert to display format
    $this->created_at = strtotime ($this->created_at);
    $this->created_at = date ('d-m-Y', $this->created_at);

    parent::afterFind ();
}

Answer: Why don't you use TimestampBehavior in your data model? You could handle this issue easily with this behavior (https://www.yiiframework.com/doc/guide/2.0/en/concept-behaviors#using-timestamp-behavior) without doing manually.
As it is stated in the documentation:

This behavior supports automatically updating the timestamp attributes
  of an Active Record model anytime the model is saved via insert(),
  update() or save() method
Comment: happens the same, when i use afterFind() :(
Comment: the result is the same.
Answer: you could try this:
public function rules()
{
    return array(
        ...
        array('created_at','default',
              'value'=>date('Y-m-d H:i:s'),
              'setOnEmpty'=>false,'on'=>'insert')
    );
}

and eliminate the function "beforeValidate"
I hope it helps you.
Comment: thanks, but happens the same. i think the problem is with the function afterFind().
Answer: You always can use behaviors. This is more clean and advanced way. You can control all events that model has. Here is example:
public function behaviors()
    {
        return [
            [
                'class' => TimestampBehavior::class,
                'createdAtAttribute' => 'created_at',
                'updatedAtAttribute' => 'created_at',
                'value' => date('Y-m-d H:i:s')
            ],
            [
                'class' => AttributeBehavior::class,
                'attributes' => [
                    ActiveRecord::EVENT_AFTER_FIND => 'created_at'
                ],
                'value' => function ($model) {
                    // Any Format you want
                    return date('d-m-Y', strtotime($model->created_at));
                }
            ]
        ];
    }

Comment: the result is the same when i change to `` return date("d-m-Y", strtotime($model->created_at)); ``
Comment: Try out this one. It should help you
Comment: no, because in this way every time i make "update" the "created_at" will be replaced.
Comment: the only way I found, is formatting date to "d-m-Y" in own view (e.g. in _DetailView_ or _GridView_).
I think is not a best solution but...
Answer: If created_at is saved as Unix like use Yii::$app->formatter->asDate($model->created_at,'d-m-Y')


Dummy sound on NUC10i5FNH and Ubuntu 21.10

Question: I just bought a NUC10i5FNH and installed Ubuntu 21.10 and i don't have sounds. In parameters i can see this ("Sortie fictive" == "Dummy sound"):

Note this computer have a HDMI output only.
Sometime (rarely) sound works, and in place of "Dummy sound", i can see HDMI sound output (something like this).
I followed some other answers without success. There is some information :
salon@salon-NUC10i5FNH:~$ lsmod | grep snd_hda_intel
snd_hda_intel          53248  1
snd_intel_dspcfg       28672  2 snd_hda_intel,snd_sof_intel_hda_common
snd_hda_codec         147456  3 snd_hda_codec_hdmi,snd_hda_intel,snd_soc_hdac_hda
snd_hda_core           94208  7 snd_hda_codec_hdmi,snd_hda_intel,snd_hda_ext_core,snd_hda_codec,snd_sof_intel_hda_common,snd_soc_hdac_hda,snd_sof_intel_hda
snd_pcm               118784  10 snd_hda_codec_hdmi,snd_hda_intel,snd_hda_codec,soundwire_intel,snd_sof,snd_sof_intel_hda_common,snd_compress,snd_soc_core,snd_hda_core,snd_pcm_dmaengine
snd                    94208  13 snd_seq,snd_seq_device,snd_hda_codec_hdmi,snd_hwdep,snd_hda_intel,snd_hda_codec,snd_timer,snd_compress,snd_soc_core,snd_pcm,snd_rawmidi

salon@salon-NUC10i5FNH:~$ lspci -nnk | grep -A2 Audio
00:1f.3 Audio device [0403]: Intel Corporation Comet Lake PCH-LP cAVS [8086:02c8]
    Subsystem: Intel Corporation Comet Lake PCH-LP cAVS [8086:2081]
    Kernel driver in use: snd_hda_intel

salon@salon-NUC10i5FNH:~$ tail /etc/modprobe.d/alsa-base.conf
options snd-usb-ua101 index=-2
options snd-usb-us122l index=-2
options snd-usb-usx2y index=-2
# Ubuntu #62691, enable MPU for snd-cmipci
options snd-cmipci mpu_port=0x330 fm_port=0x388
# Keep snd-pcsp from being loaded as first soundcard
options snd-pcsp index=-2
# Keep snd-usb-audio from beeing loaded as first soundcard
options snd-usb-audio index=-2
options snd-hda-intel model=auto

More here (alsa-info) : http://alsa-project.org/db/?f=342abfa7a51ddcfecd57a0ea7b6b5bdeab934244
What can i do to make sound working ?
Comment: See my answer at https://askubuntu.com/questions/1365905/ubuntu-21-04-no-sound-on-new-dell-inspiron-7700-aio and see if it works for you... even though you don't have a Dell... Report back.
Comment: Hello @heynnema, sadly, it doesn't work. I think i will reinstall a 20.04 LTS  and cross my fingers :(
Comment: :( Tried with Ubuntu 21.10, 20.04, Debian 11 and Fedora 34. Sound don't work each time ...
Comment: When you added the line from my other answer, did you just add the line, or did you modify the existing model= line to change from auto to dell-headset-multi? Did you reboot after?
Comment: @heynnema i modified the line and rebooted yes
Comment: Then I'm sorry, I don't know. However I think the fix is the same... you just have to find out the correct model # to use.
Answer: Surprisingly, after running the program pavucontrol, HDMI sound card is permanently seen. Sound works fine now.
Comment: I have the same problem, but this doesn't fix it for me :-(


What do the difficulty settings do?

Question: What do the difficulty settings in Tomb Raider: Anniversary do? Will setting the difficulty to easy just remove boss/enemy health, or will it also modify other aspects of the game?
(I like the gameplay a lot, but these boss battles are awful.)
Answer: The difficulty settings change how hard the enemies will hit you and also how many times you will have to hit the enemy before they die.
It does not remove the bosses from the game. And it doesn't change any of the puzzles either.
It's been answered here:
http://uk.gamespot.com/tombraider10thanniversaryedition/forum/messages/platform/ps2?topic_id=m-1-42458488&pid=934025
Comment: Does it change the damage received from environmental hazards such as the rotating flame traps?

What do the difficulty settings do?


Square Roots Modulo N

Question: x^2 = 71 mod 77   has four answers as x = 15 mod 77,  x = 29 mod 77 ,  x= −15 mod 77 and  x = −29 mod 77.  According to the formula when we know the solutions we can try to factorize n as follows:
<code> x = ±a,±b of x2 = y mod n where n = p × q
 a = b mod p and a = −b mod q.
</code>
However when I plug in a's and b's to the formula it doesnt give me the result ?
Comment: Use the solutions $29$ and $62$ and calculate $\gcd(62-29,77)$ and $\gcd(62+29,77)$ to get the non-trivial factors of $n$. Note that you only get a non-trivial solution, if the sum of the solutions is not divisible by $77$. Taking $15$ and $48$ works as well.
Answer: You mean $x^2\equiv71\pmod{77}$ etc.
If $a=15$ and $b=29$, then indeed $a\equiv b\pmod 7$ and $a\equiv -b\pmod{11}$ so you can take $p=7$ and $q=11$.
To factor $n$ what you do is find $a$, $b$ with $a^2\equiv b^2\pmod n$
but  $a\not\equiv \pm b\pmod n$ and compute the greatest common divisor
of $a-b$ and $n$. That will be a proper factor of $n$. Here $\gcd(a-b,n)=\gcd(-14,77)=7$.
Comment: Thanks for the answer by the way do they always have to be in the form like ( a, -a and b , -b) or can they be in the form of ( a,b,c,d)
Comment: @CemAytekin Well, if $n$ is a product of two distinct odd primes, and if $c$ is coprime to $n$ and has a square root modulo $n$, then it has four square roots modulo $n$, falling into two pairs $\pm a$ and $\pm b$ modulo $n$.
Comment: If $x^2=b \mod c$, then $(c-x)^2=b \mod c$

Square Roots Modulo N


How would I make my React search bar component render faster results and avoid any memory leaks?

Question: When I type in the search component I notice that there's a delay and after typing a few characters and after the 4th or 5th character I get a white screen and a message in my console stating "Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function".
Any ideas on how I can go about this? My goal is to just have a search bar that's able to properly render all of the results when someone searches for either a movie or actor.
This is the code for the interface:
export interface ActorAttributes {
    TYPE?: string,
    NAME?: string,
}

export interface MovieAttributes {
    OBJECTID: number,
    SID: string,
    NAME: string,
    DIRECTOR: string,
    DESCRIP: string,

App.tsx code:
import { useEffect, useState } from 'react';
import { searchMovies, searchActors, MovieAttributes, ActorAttributes } from "@utils/atts"

const Home: React.FC = () => {
    const [search, setSearch] = useState(false);
    const [movieSearch, setMovieSearch] = useState<MovieAttributes[]>([]);
    const [actorSearch, setActorSearch] = useState<ActorAttributes[]>([]);
    const [searchTerm, setSearchTerm] = useState('');

    useEffect(() => {
        if (searchTerm.length > 0) {
            setSearch(true);

            let newMovieSearch = [...movieSearch];

            searchMovies(searchTerm).then(results => {
                newMovieSearch = results;
                setMovieSearch(results);
            });

            searchActors(searchTerm, newMovieSearch[1].SID).then(results => {
                setActorSearch(results);
            });

            setSearch(false);
        }
    }, [searchTerm]);

    const handleSearchTermChange = (event: React.ChangeEvent<HTMLInputElement>) => {
        setSearchTerm(event.target.value);
    }

    return (

            <input type="text" value={searchTerm} onChange={handleSearchTermChange} />
            {search &&
Searching...
}
            {movieSearch.length > 0 &&
Found {movieSearch.length} movies
}
            {actorSearch.length > 0 &&
Found {actorSearch.length} actors
}

    );
}

Currently I'm only able to type 2-3 character in my search bar before it starts to delay and/or I would recieve an error message in my console. I'm new to react and this is my first time ever creating a search component so if anyone has any tips, ideas, suggestions, etc. please feel free to leave a comment. Thanks to anyone who took the time to read my post :)

        <input type="text" onChange={handleSearchTermChange} />
        {movieSearch.map((movie) => {
            if (searchTerm == "" || movie.NAME.toLowerCase().includes(searchTerm.toLowerCase())) {
                return (

{movie.NAME}

{movie.DIRECTOR}

{movie.DESCRIP}

                );
             }
            return null;
        )}

Comment: A big factor is how large the set you're searching is. If it's small enough you should do a synchronous search wrapped in `useMemo`. If it's larger (say at least 50-100k items) you might want to look at using `useEffect` instead and make it async. But then you should also add some kind of throttling and make sure you cancel any outdated/stale searches as soon as possible.
Comment: Rendering large sets to the screen is also expensive, so pagination is a good idea. Or virtual table implementations can be a solution. But I would look at some existing libraries for that instead of reinventing the wheel.
Answer: As the others saids, if the result of the Api calls are too large you may get problems, try to prevent sending the query if you know many results will be thrown (i.e if the string is less than less say 3 characters). Alongside with this you can use debounce or throttle functions from lodash to prevent updating the state on every key stroke.
Like this:
  const delayedQuery = useCallback(
    _.debounce((searchTerm: string) => sendQuery(searchTerm), 500),
    []
  );

Example sandbox: https://codesandbox.io/s/debounce-lodash-ivtm1p?file=/src/App.tsx:1508-1623
Answer: I think guess your problems. dear there is details explaination about this console message "Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function" i will try my best to explain too short there and sorry for that.
problem: after typing 4th to 5th character get white screen.
why: when you typing something, for each character update the "searchTerm" state after updating this state run useEffect for every character and inside useEffect callback have promise function, they are async function and for this reason crash your hole application.
solution short explain: there is no need any useEffect. you can directly use promise function inside onChange handler function as like your "handleSearchTermChange". see my little code solution. i hope you get your solution idea from this little code.

const handleSearchTermChange = (event: any): void => {
    const value = event.target.value;

    if (value.trim() !== "") {
      axios
        .get(`https://example.com/api/v1/product/search?searchProduct=${value}&fields=name`)
        .then((res) => {
          setOptions(res.data.result);
        })
        .catch((e) => {console.log(e)});
    }
  };

after got promise result you can store this data in state. i don't know your hole purpose that's why i did't write here other logic. if you face any problem to understand please write comment.


Can't enable "Manage your WhatsApp Accounts" option in facebook embedded signup

Question: I am trying to integrate whatsapp embedded signup as business solution provider. I have implemented the embedded signup following their documentation. I can enable and disable the "Manage your WhatsApp Accounts" option from other 3rd party bsp. So I have created a whatsapp business account and added a whatsapp number. Here is a embedded signup flow:
[[Embedded signup flow](https://i.stack.imgur.com/6NPrH.png)](https://i.stack.imgur.com/ULv7B.png)
Here is the code we followed:
`
<code>$_Company_WHATSAPP_OPENAPI = {
    APP_ID: "xxxxxxxxxxxxxxxxx",
    system_user_access_token : "token",
    getOpenAPiPage: function () {
            $_Company_WHATSAPP_OPENAPI.loadAPI();
    },

    getBtnHtml: function () {
        return '<button id="loginButtonWhatsApp" onClick="$_Company_WHATSAPP_OPENAPI.launchWhatsAppSignup()" style="background-color: #1877f2; border: 0; border-radius: 4px; color: #fff; cursor: pointer; font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: bold; height: 40px; padding: 0 24px;">Login with Facebook</button>';
    },

    loadAPI: function () {
        window.fbAsyncInit = function () {
            // JavaScript SDK configuration and setup
            FB.init({
                appId: $_Company_WHATSAPP_OPENAPI.APP_ID, // Facebook App ID
                cookie: true, // enable cookies
                xfbml: true, // parse social plugins on this page
                version: 'v15.0' //Graph API version
            });
        };
        // Load the JavaScript SDK asynchronously
        (function (d, s, id) {
            var js, fjs = d.getElementsByTagName(s)[0];
            if (d.getElementById(id)) return;
            js = d.createElement(s);
            js.id = id;
            js.src = "https://connect.facebook.net/en_US/sdk.js";
            fjs.parentNode.insertBefore(js, fjs);
        }(document, 'script', 'facebook-jssdk'));
    },

    launchWhatsAppSignup: function () {
        function waitForFbq(callback){
            if(typeof fbq !== 'undefined'){
                callback()
            } else {
                setTimeout(function () {
                    waitForFbq(callback)
                }, 100)
            }
        }
        waitForFbq(function () {
           fbq && fbq('track', 'WhatsAppOnboardingStart', {
                appId: $_Company_WHATSAPP_OPENAPI.APP_ID,
                feature: 'whatsapp_embedded_signup'
            });
        })

        // Launch Facebook login
        FB.login(function (response) {
            if (response.authResponse) {
                const accessToken = response.authResponse.accessToken;
                if (response.status === 'connected') {
                    console.log("FB login access token : ",accessToken);
                }
            }
            else {
                console.log('User cancelled login or did not fully authorize.');
            }
        }, {
            scope: 'business_management,whatsapp_business_management,email,public_profile,whatsapp_business_messaging',
            extras: {
                feature: 'whatsapp_embedded_signup',
                setup: {
                    business: {
                        name: 'Some company.',
                        email: 'email@example.com',
                        phone: {
                            code: 1,
                            number: '6505551234'
                        },
                        website: 'https://www.company.com',
                        address: {
                            streetAddress1: '1 Acme Way',
                            city: 'Acme Town',
                            state: 'CA',
                            zipPostal: '94000',
                            country: 'BD'
                        },
                        timezone: 'UTC-08:00'
                    },
                    phone: {
                        displayName: 'Acme Inc.',
                        category: 'ENTERTAIN',
                        description: ''
                    }
                }
            }
        });
    },
}
</code>
`
Is there any permission that I am missing?
I have added whatsapp_business_management permission in the scope.As it is responsible for managing whatsapp accounts, I have expected that it will enable "Manage your WhatApp accounts" option.
Answer: The Solution is try creating a new app from developer.facebook.com. My thinking is after becoming solution partners we have to create a new app to see this options!! I faced this same problem for over 2 weeks. finally solved it.


Why my react-query request data won't show?

Question: This is my first time using react-query and I having problem request data from API.
This is the code:
import { useQuery } from "@tanstack/react-query";
import axios from "axios";
import "./App.css";

function App() {

  const fetchData = async () =>{
    const { data } = await axios.get("https://api.jikan.moe/v4/anime");
    const response = data.data;
    return response
  }

  const { isLoading,data,isError } = useQuery(
    ["posts"],
    fetchData,
      {
        retry: false,
        refreshInterval: 0,
        staleTime: 0
      }
  );
  if (isLoading) return
...Loading
;
  if (isError) return
Fail
;

  console.log(data)

  return (

      {data.map((datas)=>{

          {datas.title}

      })}

  );
}

export default App;

When I console.log(data) it does show the list of data Array of 25 object element.
But when I try the use data.map to show the data in the web site nothing appear but It does appear if I only try the show one of the array like

{data[0].title}

the data does appear but when I try the show all array element with data.map but nothing seems to appear. Can someone help me?
Answer:
the data does appear but when I try the show all array element with data.map but nothing seems to appear. Can someone help me?

Your Array#map does not return anything.
 {data.map((datas) => {
    return ( // return the JSX

        {datas.title}

    );
 })}

Comment: @JoshLee Nop, it's just related with the syntax. Nothing to do with react-query :)
Comment: oh ok, thanks mate appreciate it for your help. :)
Comment: oh yeah, thanks. But is this a react-query thing? cause I don't remember that I have to return anything when using normal useEffect fetch.


Suggestions for connecting a small UPC (battery backup) to a single receptacle/outlet that will power a wifi mesh router

Question: tl:dr What is a safe way to connect a simple plug-in UPC battery back-up so that it can power a single receptacle on another side of a wall?
We have an older farm house that has been expanded a few times.  I have a second wifi mesh router that I want to put on a shelf in our kitchen to improve the wifi. The shelf is about eye level and I will put a power receptacle on the shelf along with a CAT6 connection.  I can fish the wires easily enough for the new outlet by going down the wall and connecting to an existing outlet that is on the opposite side of the wall (and hidden in a closet strangely enough).
Anyway, what I really want to do though is have this wifi mesh router on the shelf connected to a UPC battery but there isn't enough space on the shelf (and it would be an eye sore anyway, the little wifi puck is tiny).
So how can I power just that outlet from a cheap UPS?
Idea one: cut off the female end of an extension cord and hard wire it to the new outlet on the kitchen shelf and fish the male end down and out the bottom of the wall (hidden in the closet) and plug into the UPC.  (Downsides: male plug stickup out of hole in the wall!)
Idea two: put a second outlet in the closet next to the hot outlet but only wire this new outlet directly to the shelf outlet (so the outlet is not actually hot - just two outlets connected together).  Then use a male-to-male power plug and connect the UPC battery backup into the new outlet so it can power the plug above it on the shelf.  Like: reversing the flow of electricity.
The second idea seems a little tidier and less gaping holes but also seems stranger so I wonder if there is something I am not thinking of.
Appreciate anyone's help!
Edit: The wifi router I am using is a Google Nest Router (not "point").  The back of the router indicates 14V ⎓ 1.1A.
Comment: How long do you want the power to work for? UPS's are not general-use inverters/"solar generators".  They are sized for exactly one task: giving a computer 10 minutes of power so you can save work, flush databases and write caches, and do an orderly "shutdown -h now".  They are wrong for longer jobs.  Also, what voltage does the router actually run on?
Comment: Why don't you just put the router in the closet?  Then you can plug it into the UPS and the UPS into the wall using regular power cords the way they are intended.  The router being on the other side of the wall should not matter that much, and is partly why you're installing a mesh network right?  Sure the signal may be a bit weaker in the kitchen but it could be fine, you can try it first, and you'll have zero wires or equipment in your kitchen, no construction and zero sketchy wires running through walls.
Comment: @MosheKatz — Thanks for that tip.  I hadn't though about the danger of the plugging and unplugging.  Hmm.  Is there a better way to do this?
Comment: I just finished writing up an answer. I wanted to post that comment before I had time to write the whole answer, since it is so important.
Comment: @Harper-ReinstateMonica — I was originally thinking just 30-60 mins (which is how long I am getting from these 425VA backups).  I have a whole house generator I can turn on.  Its the frequent power "blips" this property gets that I am targeting.  The router is `14V ⎓ 1.1A` — I updated my question with that info. Thanks for any other ideas you may have!
Comment: @jay613 — I can test putting it in the closet and it may be just fine, as you say.  The kitchen is in the new part of the house (also main bedroom above it).  There is an "outside" wall between the closet and the kitchen and the other route is another outside wall away on the other side.  Was aiming to get both ends of the house as best as possible with the mesh in the middle where I don't need it..  Will experiment!
Comment: If you're looking for great coverage in an old house, the main thing to avoid is multiple brick walls or multiple lath-and-plaster walls between mesh node and user.  If that is your situation, for example if the kitchen is a great place to have just ONE heavy wall to many other rooms,  do consider @ecnerwal suggestion of running LV through walls, which gives you great freedom to do minimal damage to walls and to be visually unobtrusive.
Answer: A common name for a male-to-male power cord as described in your second idea is a "suicide cord". It's an incredibly bad idea.
The problem with your first idea is that extension cords are not rated for use inside a wall.
Instead, you should use something like this Locking Inlet. You don't strictly need the locking version, but it will prevent someone from accidentally unplugging the cord because you have to twist it in order to unplug.
They also make non-locking inlets that take a regular extension cord, but that relies on the friction within the extension cord's female end to be able to support the weight of the cord.
A third option would be something that uses a computer-style power connector since this type of connector is also specifically designed to support the weight of the cord.
Comment: Thanks for the detailed answer.  Much better than my idea.  The computer style one looks pretty straight forward; I'm not seeing how that round inlet would attach to a standard old work box.  Thanks again!
Comment: Oh so much irony here.  So much cabling infrastructure in aid of a wifi mesh network so the nodes can be right in the living space.  And that Crutchfield link ... a Decora *wall* outlet for rack mount equipment.   The ultimate in vanity electronics.  Ouch.
Answer: You fail to provide details on what, exactly, your "tiny WiFi puck" is, but since virtually all such things that are not inherently POE operated (truly the best solution - one UPS at the router/switch powers them all, no extra power wires needed, just the network wires) use a DC adapter plugged into the wall, and are powered by low-voltage DC, not by AC line voltage directly, often the simplest solution is to extend (or simply use, if it's long enough) that low-voltage DC supply cord.
Comment: @jay613 Ubiquiti Unifi
Comment: — I updated the question.  It's a Google Nest Router (not point) that runs at `14V ⎓ 1.1A`.  I have two of them already our house is 2500 sq feet.  I didn't even know POE so thanks for pointing out that option!  When you say its simple to extend ... do you mean fish the DC supply cord from the router down the inside of the wall?
Comment: Yes put the UPS in the closet, plug in the Nests's wall wart THERE, and run its DC cable through the wall in any manner you want.   Just shove it through the drywall with a wire hanger, it doesn't matter.  If it's not long enough cut it in half and extend it with phone wire.  You can't go wrong.  But then, why not just put the nest in the closet too?  The wifi signal will go through the wall and you don't even need a wire hanger!
Comment: @ecnerwal I'm on the lookout for an affordable residential mesh with PoE.  The commercial ones are all too expensive (IMO) for home use.  I know it's not a shopping forum but since you mentioned it ... wouldn't mind any pointers if such exists.   I'm using a bunch of  Asus routers, they have great mesh capability and you can get them for $40 second hand.


Do Wscript.Shell shortcuts support file extensions longer than 3 characters

Question: I am trying to use Wscript.Shell to create a desktop shortcut in a Powershell script.  The target path is a HTML file on a network drive.  I specified the full path, but when the shortcut was created, the file extension was truncated to .htm.  Since the file ends in .html, this obviously doesn't work.
Is there any way to avoid truncating the file name?  My guess is that Wscript.Shell doesn't support target file extensions longer than 3 characters.  Is this correct?
Here is my code (Powershell):
$wshell = New-Object -ComObject WScript.Shell
$shortcut = $wshell.CreateShortcut("C:\users\parts.AGRISERVICELLC\Desktop\AgriWeb.lnk")
$shortcut.TargetPath = "S:\Service\agriweb_dairy\home.html"
$shortcut.WorkingDirectory = "S:\Service\agriweb_dairy"
$shortcut.IconLocation = "C:\arch2.ico"
$shortcut.Save()

This code creates the shortcut, complete with my icon.  But the target path is truncated to S:\Service\agriweb_dairy\home.htm.
Update:  Interestingly enough, this problem does not occur if I run the commands above in a local Powershell session.  However, if I remote into another computer using Enter-PSSession, the extension truncates to 3 characters.  The issue isn't the length of the path - if I shorten the path and change the extension to ".htmll", it still shortens the extension to ".htm".
Also, the extension does not truncate if the path is on the C: drive.  But when I use a network drive, the extension truncates.
Comment: That doesn't happen here. The .html extension is still in the link. The link is also functional.
Comment: I experimented a little more, and it does work fine as long as I am running the commands in a local Powershell session.  When I remote into another computer with Enter-PSSession, the extension truncates to 3 characters again.
Comment: I can confirm the problem: `powershell "$shortcut=(New-Object -COM WScript.Shell).CreateShortcut('%userprofile%\Desktop\test.lnk');$shortcut.TargetPath='Z:\test.docx';$shortcut.Save(); Write-Host $shortcut.TargetPath"` truncates the extension to `Z:\test.doc`. But `powershell "$shortcut=(New-Object -COM WScript.Shell).CreateShortcut('%userprofile%\Desktop\test.lnk');$shortcut.TargetPath='C:\test.docx';$shortcut.Save(); Write-Host $shortcut.TargetPath"` works fine: `C:\test.docx`. The only difference in the two command lines before are the volume letter `c:` vs. `z:`
Answer: Maybe this is related to https://web.archive.org/web/20060709170134/https://support.microsoft.com/?kbid=263324
If the target drive letter does not exist on the machine where the shortcut is created, Windows assumes the drive can only handle filenames in the 8.3 format


Comparing an Array of Comparables in Java

Question: I want to compare an array of comparables. The simplest way seems the following (details not shown):
public class ArrayComparable implements Comparable<ArrayComparable>{
ArrayList<Comparable<?>> list = new ArrayList<Comparable<?>>();

@Override
public int compareTo(ArrayComparable ac) {
    Iterator<Comparable<?>> itr = ac.list.iterator();
    for(Comparable<?> l : list) {
        Comparable<?> itrNext = itr.next();
        if(itrNext.getClass() == l.getClass()) {
            if(itrNext.compareTo(l)) {
                //something
            } else {
                //other stuff
            }
        } else {
            //some other thing
        }
    }
}

Of course the problem here is that the compareTo as in itrNext.compareTo(l) will not work giving the error: The method compareTo(capture#6-of ?) in the type Comparable<capture#6-of ?> is not applicable for the arguments (Comparable<capture#7-of ?>)
which I understand why (as far as the method is concerned I might be comparing apples to oranges). On the other hand, I know I am not as I check for the class of things before comparing them.
So is there a way I can make this work? Don't worry about the sanity of comparing arrays of any comparables, as I have a good reason why I want to do that.
EDIT- SO why would I want to do something like this. Say I wanted to have an array of comparables, and I didn't care what was contained in each index, as long as the types corresponded, and they could be compared. Then I could do a general lexicographical compare between these arrays. This way I don't have to write a comparable for (int,int) and (int, string), and (string, double, string) or whatever you need. I just write one, and as long as I make sure that the types match (and I can), I am good to go.
Comment: "On the other hand, I know I am not as I check for the class of things before comparing them." So? Just because two objects are the same class doesn't mean you can compare them.
Answer: Make ArrayComparable a generic class so that you can properly parameterize the generics rather than using <?> everywhere. Oh, and you might as well implement Iterable as well.
public class ArrayComparable<T> implements Comparable<ArrayComparable<T>>, Iterable<T>
{
    List<Comparable<T>> list = new ArrayList<Comparable<T>>();

    @Override
    public int compareTo(ArrayComparable<T> ac)
    {
        // snip
    }

    @Override
    public Iterator<T> iterator()
    {
        return list.iterator();
    }
}

Comment: i suspect the OP wants the array to contain different comparables, not just of one type (i.e. he is crazy but he knows it)
Comment: You should restrict `>` to make sure that `T` is comparable to itself
Comment: I think this class (and the `List` by extension) contains `Comparable`s of any type, not just a specific type `T`.
Comment: If that's the case, then _ew_. ...oh hey, Claudiu!
Comment: Yes, I am fully aware of my insanity. But there are applications where one needs this sort of a thing. This particular one comes from hadoop.
Answer: Using the raw type Comparable wherever you're currently using Comparable<?> should work. Actually, you could just do that in one place if you want:
if (((Comparable) itrNext).compareTo(l) == 0)

Comment: Shedding the template does indeed work. It is too bad I need to live with warnings. What I wanted was not that unreasonable. But I guess this is going to be the way to go.
Comment: @delmet: Add an `@SuppressWarnings("unchecked")` to the method with a comment explaining why it should be safe that you're doing this.
Answer: Try this:
    if(itrNext.getClass().cast(itrNext).compareTo(l.getClass().cast(l))) {
        //something
    } else {
        //other stuff
    }

Answer: public class GenericDemo<T>{
  T g;
 public <T extends Comparable<T>> void printData(T a[]){
    T max = a[0];
    if(a[1].compareTo(max)>0){
        max=a[1];
    }
    if(a[2].compareTo(max)>0){
    max=a[1];
    }
    System.out.println(max);
    System.out.println("DataType: " +a.getClass().getName());

      }
    public static void main(String[] ar)
    {
     Integer a[]={1,2,3};
     Byte b[]= {4,6,7};
     Short c[]={6,8,9};

     GenericDemo g = new GenericDemo();
     g.printData(a);
     g.printData(b);
     g.printData(c);
     }
}

Answer: A good answer to this would be:
public final class ArrayComparable<T extends Comparable<T>>
    implements Comparable<ArrayComparable<T>> {

    private final ArrayList<T> list = new ArrayList<>();

    @Override
    public int compareTo(final ArrayComparable<T> other) {

        final Iterator<T> it = other.list.iterator();

        for (final T element : list) {
            final T otherElement = it.next();

            final int comparison = element.compareTo(otherElement);
            if (comparison < 0) {
                // something
            } else if (comparison > 0) {
                // other stuff
            } else {
                // other stuff
            }
        }
        return 0;
    }
}


joSQL query with double quotes parsing resulting org.josql.parser.TokenMgrError: Lexical error

Question: Trying to run following code, in this the SQL statement trying to find values where colName2 like group/test" (name having double quote in the end), and passing the querySQL string to josql parser.
<code>public static void main(String a[])
{
    String querySQL = new String("Select * from tabName WHERE ((colName1) = ((\"type\" )) AND (colName2) LIKE ((\"%group/test\"%\" ))) ORDER BY colName2 asc");
    org.josql.Query josql = new org.josql.Query();
    try
    {
        josql.parse(querySQL);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    System.out.println(josql.toString());
}
</code>

Following exception has been occurring when I run it, as colName2 contains a string with double quote in it. Does anyone has any idea on how to pass the double quote to josql parser?
Exception in thread "main" org.josql.parser.TokenMgrError: Lexical error at line 1, column 150.  Encountered:  after : "\" ))) ORDER BY colName2 asc"
at org.josql.parser.JoSQLParserTokenManager.getNextToken(JoSQLParserTokenManager.java:1420)
at org.josql.parser.JoSQLParser.jj_scan_token(JoSQLParser.java:3725)
.........
.........
at org.josql.parser.JoSQLParser.Query(JoSQLParser.java:298)
at org.josql.parser.JoSQLParser.parseQuery(JoSQLParser.java:86)
at org.josql.Query.parse(Query.java:2032)
at main.JoSqlTest.main(JoSqlTest.java:12)
Answer: Why do you need double quotes?
You can/should use single quotes here...
"Select * from tabName WHERE colName1 = 'type' AND colName2 LIKE '%group/test\"%' ORDER BY colName2 asc"


Need a fast way to count and sum an iterable in a single pass

Question: Can any one help me? I'm trying to come up with a way to compute
>>> sum_widths = sum(col.width for col in cols if not col.hide)

and also count the number of items in this sum, without having to make two passes over cols.
It seems unbelievable but after scanning the std-lib (built-in functions, itertools, functools, etc), I couldn't even find a function which would count the number of members in an iterable.  I found the function itertools.count, which sounds like what I want, but It's really just a deceptively named range function.
After a little thought I came up with the following (which is so simple that the lack of a library function may be excusable, except for its obtuseness):
>>> visable_col_count = sum(col is col for col in cols if not col.hide)

However, using these two functions requires two passes of the iterable, which just rubs me the wrong way.
As an alternative, the following function does what I want:
>>> def count_and_sum(iter):
>>>     count = sum = 0
>>>     for item in iter:
>>>         count += 1
>>>         sum += item
>>>     return count, sum

The problem with this is that it takes 100 times as long (according to timeit) as the sum of a generator expression form.
If anybody can come up with a simple one-liner which does what I want, please let me know (using Python 3.3).
Edit 1
Lots of great ideas here, guys. Thanks to all who replied. It will take me a while to digest all these answers, but I will and I will try to pick one to check.
Edit 2
I repeated the timings on my two humble suggestions (count_and_sum function and 2 separate sum functions) and discovered that my original timing was way off, probably due to an auto-scheduled backup process running in the background.
I also timed most of the excellent suggestions given as answers here, all with the same model. Analysing these answers has been quite an education for me: new uses for deque, enumerate and reduce and first time for count and accumulate. Thanks to all!
Here are the results (from my slow netbook) using the software I'm developing for display:
┌───────────────────────────────────────────────────────┐
│                 Count and Sum Timing                  │
├──────────────────────────┬───────────┬────────────────┤
│          Method          │Time (usec)│Time (% of base)│
├──────────────────────────┼───────────┼────────────────┤
│count_and_sum (base)      │        7.2│            100%│
│Two sums                  │        7.5│            104%│
│deque enumerate accumulate│        7.3│            101%│
│max enumerate accumulate  │        7.3│            101%│
│reduce                    │        7.4│            103%│
│count sum                 │        7.3│            101%│
└──────────────────────────┴───────────┴────────────────┘

(I didn't time the complex and fold methods as being just too obscure, but thanks anyway.)
Since there's very little difference in timing among all these methods I decided to use the count_and_sum function (with an explicit for loop) as being the most readable, explicit and simple (Python Zen) and it also happens to be the fastest!
I wish I could accept one of these amazing answers as correct but they are all equally good though more or less obscure, so I'm just up-voting everybody and accepting my own answer as correct (count_and_sum function) since that's what I'm using.
What was that about "There should be one-- and preferably only one --obvious way to do it."?
Comment: The function should not take 100 times as long! Something strange is going on there.
Comment: i may be missing something embarrassingly obvious. but why not `sum(iter), len(iter)` ?
Comment: You realise that, if your timing information is accurate, the two-pass "rubs you the wrong way" solution is 50 times faster than your alternative? Sometimes it's better to be pragmatic :-)
Comment: @Timothy, I agree whole-heatedly in general but this obviously isn't one of those cases, given the timings provided. I don't like doing things twice either but, if the alternative is doing it once and slower (with no other benefits), I'll choose pragmatism over dogmatism :-)
Comment: @thefourtheye: I was intending ``count_and_sum`` to be a more general function and call it as: ``count, sum = count_and_sum(col.width for col in cols if not col.hide)`` but now that I've written it out I see the error of my plan. Thanks for pointing it out.
Comment: @paxdiablo There are situations in which you don't want to iterate twice, such as when the generator is costly.
Comment: Your first two samples have an extra condition `if not col.hide`, but that is missing in the `count_and_sum`. Why so?
Comment: @DonO'Donnell Exactly. That program is missing an important piece of information. Please fix it. And DSM's `accumulate` looks good.
Comment: Could you post a little about how you arrived at the 100x slowdown figure? The precise command/code you used would be ideal. 100x slowdown doesn't smell right for that code.
Comment: Slapping `@numba.autojit` on `count_and_sum` makes it as fast as the deque method. Adding inn some logic for the conditional filtering and adding numba in the mix, might be quite good.
Answer: Using complex numbers
z = [1, 2, 4, 5, 6]
y = sum(x + 1j for x in z)
sum_z, count_z = y.real, int(y.imag)
print sum_z, count_z
18.0 5

Comment: Ah, but what if the sequence contains complex numbers :P +1 for making me laugh
Comment: @Morwenn *Imaginary*, not *irrational*.
Comment: It's certainly clever but, as per Matt, I'm not sure if I mean that in a good way or in a "you're frackin' crazy" way :-)
Comment: @TylerDeWitt `j` is the suffix for irrational numbers. When you compute the sum of some real numbers and add `1j` for each element, you are incremeting the irrational part of the complex number; therefore, you are using the irraitonal part as a counter while the real part holds the sum of the real numbers.
Comment: Use complex numbers for **everything**.
Comment: Can be optimised to `sum(map(1j.__add__(z))`.
Comment: @JBernardo, not sure i understand. I tried it with float numbers in the list and it calculated the correct sum
Comment: @1_CR Yes, it does calculate correctly (until some value that does not fit into float or, like gnibbler said, a complex number)
Comment: This is...amazing. It could use a proper explanation, simply with the idea that comments are supposed to be disposable. If all these comments were tossed out I'd have absolutely no idea what on earth this code was doing.
Comment: @nikhil, please refer Morwenn's explanation in the comments. He has expressed about 10 times better than  i ever could ;-)
Comment: If it wasn't for float numbers this would be a nice hack
Comment: I've added an answer that does the same thing but with numpy arrays, I think that's slightly cleaner but the idea is stolen from this.
Comment: @RemcoGerlich cleaner, but an order of magnitude slower.
Comment: I think next time i will post the solution with `Trignometry`
Comment: I can bet that this dude has just studied `Complex Numbers` in his `Math` class :)
Comment: I didn't understand this. My math is probably a little rusty. Care to explain a bit?
Answer: I don't know about speed, but this is kind of pretty:
>>> from itertools import accumulate
>>> it = range(10)
>>> max(enumerate(accumulate(it), 1))
(10, 45)

Comment: @DSM Correct. Do you mind adding this to the answer?
Comment: @thefourtheye: given that the above executed in Python 3.3.1, I'm pretty sure you're wrong. :^)
Comment: @DSM Sorry :) It is available from [3.2](http://docs.python.org/3.2/library/itertools.html#itertools.accumulate) itself. +1
Comment: @DSM One more thing. If you look at the first two examples in the question, there is one extra condition `if not col.hide`, that is missing in the last example. `accumulate` may not be able to handle it.
Comment: @thefourtheye: I'm not sure I follow.  Why wouldn't that be entirely handled on the iterable side?  If I write `accumulate(col.width for col in cols if not col.hide)`, `accumulate` doesn't see, much less care, about what's going on inside.
Answer: Adaption of DSM's answer. using deque(... maxlen=1) to save memory use.
import itertools
from collections import deque
deque(enumerate(itertools.accumulate(x), 1), maxlen=1)

timing code in ipython:
import itertools , random
from collections import deque

def count_and_sum(iter):
     count = sum = 0
     for item in iter:
         count += 1
         sum += item
     return count, sum

X = [random.randint(0, 10) for _ in range(10**7)]
%timeit count_and_sum(X)
%timeit deque(enumerate(itertools.accumulate(X), 1), maxlen=1)
%timeit (max(enumerate(itertools.accumulate(X), 1)))

results: now faster than OP's method
1 loops, best of 3: 1.08 s per loop
1 loops, best of 3: 659 ms per loop
1 loops, best of 3: 1.19 s per loop

Comment: Yeah i was a bit surprised myself on the relatively big difference. I just had a hunch that allocating memory for the list could be a bottleneck. For more complex generators, where the calculation of values take more time. The difference should be insignificant though.
Comment: But `max` doesn't allocate memory for the list.  At any instant only two tuples are stored, the one you're looking at and the last maximum.  I think it must be just that the deque implementation is very fast and/or the tuple comparison is slow.
Comment: No, because the tuples that it's comparing -- the ones produced by `enumerate`, remember -- are always of the form `(i, value)` and `(i+1, next_value)`.  The values never come into play because it always decides which is greater based on the first element, the index.
Comment: @DSM ahh, well then all the unnecessary comparisons would be the problem. since we're only interested in the last element.
Comment: @DSM btw, wouldnt using `max` give the wrong value if the last element was negative? The second to last elements would then be larger then the last one
Answer: Here's some timing data that might be of interest:
import timeit

setup = '''
import random, functools, itertools, collections

x = [random.randint(0, 10) for _ in range(10**5)]

def count_and_sum(it):
    c, s = 0, 0
    for i in it:
        c += 1
        s += i
    return c, s

def two_pass(it):
    return sum(i for i in it), sum(True for i in it)

def functional(it):
    return functools.reduce(lambda pair, x: (pair[0]+1, pair[1]+x), it, [0, 0])

def accumulator(it):
    return max(enumerate(itertools.accumulate(it), 1))

def complex(it):
    cpx = sum(x + 1j for x in it)
    return cpx.real, int(cpx.imag)

def dequed(it):
    return collections.deque(enumerate(itertools.accumulate(it), 1), maxlen=1)

'''

number = 100
for stmt in ['count_and_sum(x)',
             'two_pass(x)',
             'functional(x)',
             'accumulator(x)',
             'complex(x)',
             'dequed(x)']:
    print('{:.4}'.format(timeit.timeit(stmt=stmt, setup=setup, number=number)))

Result:
3.404 # OP's one-pass method
3.833 # OP's two-pass method
8.405 # Timothy Shields's fold method
3.892 # DSM's accumulate-based method
4.946 # 1_CR's complex-number method
2.002 # M4rtini's deque-based modification of DSM's method

Given these results, I'm not really sure how the OP is seeing a 100x slowdown with the one-pass method. Even if the data looks radically different from a list of random integers, that just shouldn't happen.
Also, M4rtini's solution looks like the clear winner.

To clarify, these results are in CPython 3.2.3. For a comparison to PyPy3, see James_pic's answer, which shows some serious gains from JIT compilation for some methods (also mentioned in a comment by M4rtini.
Comment: @JBernardo: while I agree this answer is very helpful, I'm not sure what senshin would be comparing the OP's methods *against* if other people hadn't written answers.
Comment: @utdemir All the function definitions and variable assignments are in the setup, which doesn't count towards the time actually taken.
Comment: @utdemir Yes, but you have to spend time initialzing variables, creating lambdas, etc. if you actually want to use these functions. Not counting the time taken to do that would defeat the entire purpose of this exercise.
Comment: @senshin could you add my answer to the timings?
Comment: @JBernardo: the first sentences ask "Can any one help me? I'm trying to come up with a way to compute [stuff] without having to make two passes over cols."  The final sentence says "If anybody can come up with a simple one-liner which does what I want, please let me know (using Python 3.3)."  I think a fair reading of the OP's question is that one-pass, simplicity, and speed are all desiderata.
Comment: Can you try with some larger value? So that creation of lambdas and initial assignments become insignificant.
Comment: we create a list and a lambda in `functional` method, initialize two variables in `count_and_sum` method etc. But as your results suggest, they are too tiny to affect the result.
Comment: This is actually the only helpful answer. Instead of writing bogus code like many others, it shows how good the original code is.
Comment: @DSM But you don't see any timings on other answers and while some may yield pretty code, they do not fulfill the original problem
Comment: @senshin The 100x slowdown was mostly due to the ``count_and_sum`` being a function call, the ``sum(genexp)`` form was executed directly in the ``timeit`` param, which is how it would be done in my project's code. Your results, while informative, do not reflect the way in which the final code would be executed.
Comment: @DonO'Donnell Could you shed some light on the way the code will be executed? If it's possible to test code in a representative way, then we may be able to give you better info.
Answer: As a follow-up to senshin's answer, it's worth noting that the performance differences are largely due to quirks in CPython's implementation, that make some methods slower than others (for example, for loops are relatively slow in CPython). I thought it would be interesting to try the exact same test in PyPy (using PyPy3 2.1 beta), which has different performance characteristics. In PyPy the results are:
0.6227 # OP's one-pass method
0.8714 # OP's two-pass method
1.033 # Timothy Shields's fold method
6.354 # DSM's accumulate-based method
1.287 # 1_CR's complex-number method
3.857 # M4rtini's deque-based modification of DSM's method

In this case, the OP's one-pass method is fastest. This makes sense, as it's arguably the simplest (at least from a compiler's point of view) and PyPy can eliminate many of the overheads by inlining method calls, which CPython can't.
For comparison, CPython 3.3.2 on my machine give the following:
1.651 # OP's one-pass method
1.825 # OP's two-pass method
3.258 # Timothy Shields's fold method
1.684 # DSM's accumulate-based method
3.072 # 1_CR's complex-number method
1.191 # M4rtini's deque-based modification of DSM's method

Answer: You can keep count inside the sum with tricks similar to this
>>> from itertools import count
>>> cnt = count()
>>> sum((next(cnt), x)[1] for x in range(10) if x%2)
25
>>> next(cnt)
5

But it's probably going to be more readable to just use a for loop
Comment: @JBernardo, it's just a different way of solving the count(0) problem
Comment: This is practically the same as  Steinar Lima's answer, but with an overhead of creating tuples for side effects...
Comment: Well I don't think it was a problem, since you can simply do `cnt - 1` at the end... `next(cnt)*0 or x` should also work. Or even `~next(cnt) and x`
Answer: You can use this:
from itertools import count

lst = range(10)
c = count(1)
tot = sum(next(c) and x for x in lst if x % 2)
n = next(c)-1
print(n, tot)

# 5 25

It's kind of a hack, but it works perfectly well.
Answer: I don't know what the Python syntax is off hand, but you could potentially use a fold.  Something like this:
(count, total) = fold((0, 0), lambda pair, x: (pair[0] + 1, pair[1] + x))

The idea is to use a seed of (0,0) and then at each step add 1 to the first component and the current number to the second component.
For comparison, you could implement sum as a fold as follows:
total = fold(0, lambda t, x: t + x)

Comment: That syntax would be `reduce(lambda pair, x: (pair[0]+1, pair[1]+x), a, (0,0))` after importing `functools.reduce`.
Comment: And this would be fast how?
Answer: 1_CR's complex number solution is cute but overly hacky. The reason it works is that a complex number is a 2-tuple, that sums elementwise. The same is true of numpy arrays and I think it's slightly cleaner to use those:
import numpy as np
z = [1, 2, 4, 5, 6]
y = sum(np.array([x, 1]) for x in z)
sum_z, count_z = y[0], y[1]
print sum_z, count_z
18 5

Comment: off all the different ways you could use numpy for this, this gotta be the absolutely worst performing one of them out there. just create an array of z. sum it and check it's size.
Comment: You're probably right. I rejected that because storing all the results might use too much memory, but now that I think about it, that's really quite unlikely.
Answer: Thanks for all the great answers, but I decided to use my original count_and_sum function, called as follows:
>>> cc, cs = count_and_sum(c.width for c in cols if not c.hide)

As explained in the edits to my original question this turned out to be the fastest and most readable solution.
Answer: Something else to consider: If it is possible to determine a minimum possible count, we can let the efficient built-in sum do part of the work:
from itertools import islice

def count_and_sum(iterable):
    # insert favorite implementation here

def count_and_sum_with_min_count(iterable, min_count):
    iterator = iter(iterable)
    slice_sum = sum(islice(iterator, None, min_count))
    rest_count, rest_sum = count_and_sum(iterator)
    return min_count + rest_count, slice_sum + rest_sum

For example, using the deque method with a sequence of 10000000 items and min_count of 5000000, timing results are:
count_and_sum: 1.03
count_and_sum_with_min_count: 0.63

Answer: How about this?
It seems to work.
from functools import reduce

class Column:
    def __init__(self, width, hide):
        self.width = width
        self.hide = hide

lst = [Column(10, False), Column(100, False), Column(1000, True), Column(10000, False)]

print(reduce(lambda acc, col: Column(col.width + acc.width, False) if not col.hide else acc, lst, Column(0, False)).width)

Answer: You might only need the sum & count today, but who knows what you'll need tomorrow!
Here's an easily extensible solution:
def fold_parallel(itr, **fs):
    res = {
        k: zero for k, (zero, f) in fs.items()
    }

    for x in itr:
        for k, (_, f) in fs.items():
            res[k] = f(res[k], x)

    return res

from operator import add

print(fold_parallel([1, 2, 3],
    count = (0, lambda a, b: a + 1),
    sum = (0, add),
))
# {'count': 3, 'sum': 6}


Multiplying the probabilities of two events that aren't independent

Question: If you have two events which aren't independent, say $A$ and $B$, and you multiply $P(A)\cdot P(B)$, why is this probability always smaller than $P(A\mid B)P(B)$?
Comment: It's not. ${}\qquad{}$
Answer: Simple counterexample: $A$ and $B$ are mutually exclusive, and each have non-zero probability thus: $P(A|B)P(B)=0 \neq P(A)P(B)$
Comment: Thanks, I had misread some information from 'Maths on Trial' where the statement was referring to a particular example. Why is the first probability = 0 in your above answer?
Comment: @Hayley - ah, that's a great book! Note that if A and B are mutually exclusive, its impossible for both of them to happen, hence, if we know B occurred, then A cannot occur.
Comment: Ah of course, **thank you**


Lua: Can't copy .png file

Question: I try to copy files by reading source file and write data to target - fail.
I try to use C extension like that:
    static int copy(lua_State *L)
{
    char ch;
    FILE *source, *target;
    const char * source_file = lua_tostring(L, 1);
    const char * target_file = lua_tostring(L, 2);
    source = fopen(source_file, "r");
    if( source == NULL )
    {
        lua_pushnumber(L, 1);
    }
    target = fopen(target_file, "w");
    if( target == NULL )
    {
        fclose(source);
        lua_pushnumber(L, 1);
    }
    while( ( ch = fgetc(source) ) != EOF )
        fputc(ch, target);
        fclose(source);
        fclose(target);
    return 1;
}

This code is working - i successfully copy text files, but when i try to copy .png image - i get fail again - in all of this methods i get breaked images.
I only can copy images by:
os.execute("cp file1 file2")

but it's very sloooow...
How to copy file without using os.execute?
Comment: Are you on Windows or a Unixoid?
Comment: Yes, i use Windows XP. I realy like unix, but now i need to write Windows app.
Answer: There are various problems with your code. In order of appearance:

ch must be an int, otherwise one of the 256 valid characters might compare equal to EOF.
lua_tostring could return NULL. You should check for that or use luaL_checkstring.
As others have already said: Open both files in binary mode ("rb" and "wb").
Make sure that you call fclose, fgetc, and fputc on non-NULL file handles only. There are probably some returns missing in there.
You don't check whether EOF signals the end of the file or an I/O error.
The return value (1 in your case) tells Lua how many values from the Lua stack to pass back to the calling function. You return one value, but in some cases you don't push any values onto the Lua stack, and in other cases you push more than one.
Answer: First thing, while on unixoids text-mode and binary-mode are identical, that happy state is not found on any Windows box.
Use binary mode unless you want your text-file translated!

Second issue, of course it is slow if you go character by character, as your multi-threading-enabled runtime must lock and unlock for each call.
Get some decent buffer, 212 bytes shoud be nice, and use fread / fwrite.
Answer: You need to open the file in binary mode when reading/writing on Windows, otherwise there may be end-of-line and end-of-file processing that breaks the file. Add "b" modifier.
Comment: He's using the C library, not the Lua one.
Comment: Right, but the "b" mode explanation is the same: "This string is exactly what is used in the standard C function fopen."; it was just faster to reference Lua manual ;)
Comment: I tried to open image with "r" mode and read icon line by line - fail. And i try to open image with "rb" mode and read data - fail. I get just "%PNG" file heder...
Comment: Is this a public image we can try this on?
Comment: Every image/file are broken. All examples just copy file header, and no copy data.

Lua: Can't copy .png file


Use 3 prong microwave on 2 wire ungrounded outlet?

Question: I have a dedicated, ungrounded 15A outlet. Can I use a microwave with a 3 prong plug on it if I install an AFCI/GFCI combo outlet? Or do I need to also ground the outlet?
The microwave owners manual says the outlet must be at least 15A.
Comment: Grounding is for safety, so "can I use" is going to be a little subjective.  The microwave doesn't need a ground to function.
Comment: You don't need an AFCI. I like to stack up two or three of those 3-to-2 adapters, you know, to be sure. :P
Comment: Does the microwave's labeling or instructions say anything about a grounded outlet or groundless GFCI?  It is a Code violation to install any equipment contrary to the labeling and instructions under which it was listed.  To answer your question @user1594257 ...listing is the result of testing, and the testing was done only for the uses described in the labeling and instructions.
Comment: Does code allow it? The GFCI would protect the user, but not necessarily the equipment?
Answer: The capacitor of a microwave oven, stores voltage of over 2,000, even when plugged out; I would not take a chance with ungrounding it;;;
Comment: Since the microwave _is_ ungrounded when you unplug it, what do you do with the microwave when you need to move it? Do you call in an electrician? The bomb squad? This seems more like irrational scare tactics than practical advice. Please [edit] your answer to expand on this.
Comment: This is relevant to *repair* of microwave ovens. I don't think it is relevant to consumer usage.


Recursive javascript function that converts nested object keys to string and store all keys in arrray

Question: I am trying to write a javascript recursive function that receives one parameter - nested JSON object.
The function goes through the potentially infinitely nested object and converts all the keys (property names) to a string that is stored in array. Array is returned to a place where the function was called.
Example of JSON object:
{
  OBJECT1: {
    ATTRIBUTE3: {
      PARAMETER2: {
        PROPERTY1: {

        }
      }
    }
  }
}

The object does not hold any values.
What i tried and did not work:
function convertKeysToString(obj) {
  let keys = [];
  for (let key in obj) {
    if (typeof obj[key] === 'object') {
      keys = keys.concat(convertKeysToString(obj[key]));
    } else {
      keys.push(key.toString());
    }
  }
  return keys;
}

As a result, I expected that returned key is pushed to an array, but the funciton didnt get the key at all or was not pushed to keys array.
Another code I tried:
function getNestedObjectKeys(obj) {
  var keys = []
  var firstLevel = null

  var property = Object.keys(obj)
  property = property[0]
  firstLevel = Object.keys(obj[property])[0]
  if (firstLevel == undefined) {
    return 0
  }
  let returnedValue = keys.unshift(getNestedObjectKeys(obj[property]))

  if (returnedValue == 0) {
    return Object.keys(obj[property])[0]
  }
  returnedValue = Object.keys(obj[property])[0]
  if (returnedValue != obj[property[0]]) {
    return Object.keys(obj[property])[0]
  }
  else if (returnedValue == firstLevel) {
    return keys
  }
}

The function should return the key name and push (unshift) it to string and then return it, but the unshift doesnt do what I expect and in the returnedValue is not a expected returned string.
I approached it the way that the function findd the deepest (empty) object, and starts returning the name of the key. The thing is that I must return the key name AND push it to the string, which I can't find the way to accomplish at once.
Comment: @Konrad I have a code that should call this recursive function. Array should be returned to that place in code where the recursive function is called. I am sorry for bad interpretation and I hope it is more clear now.
Comment: @NinaScholz I am sorry I dont get what you are asking.
Comment: *Array is returned to a place where the function was called.* - what does it mean? What is the expected output?
Comment: do you have only a sinlge nested property?
Answer: Your first solution is pretty close, but has one problem (well, one main problem): when the value is type object, you don't add its key to the array. So how is it supposed to get into the array? Give this a shot:
function convertKeysToString(obj) {
  let keys = [];
  for (let key in obj) {
    keys.push(key.toString());
    if (typeof obj[key] === 'object') {
      keys = keys.concat(convertKeysToString(obj[key]));
    }
  }
  return keys;
}

Other things you may want to consider:

typeof null is object.
typeof [] is also object.
Comment: Thank you so much! This worked like a miracle after spending more than 6 hours on this function. Does just what I expected.

My approach was first check if it is an object and if so, check if it does contain any key or not (if it is empty). This approach was to get the key from the deepest level to the most shallow one, but your approach goes the other way. I mean, not realyl thanks to recursion, but you first get the current key and store it in a variable and THEN call the recursion.

Much love to you.
Answer: You could have a look to object, which are truthy and typeof object.

const
    getKeys = object => (keys => [
        ...keys.flatMap(key => object[key] && typeof object[key] === 'object'
            ? [key, ...getKeys(object[key])]
            : [key]
        )
    ])(Object.keys(object)),
    data = { OBJECT1: { ATTRIBUTE3: { PARAMETER2: { PROPERTY1: {} } } } },
    result = getKeys(data);

console.log(result);
Comment: I already have a solution from @Aurast but I really appreciate your input and will have a look at your solution!


Mysql single table very slow

Question: I have a single InnoDB table in MySQL containing 50+ columns. In the table there are over 500000 rows. I only use a DATETIME column (dt) and a VARCHAR(245) column (code) for searching. I created an index for both columns.
The following query is fast:
SELECT COUNT(*) FROM TABLE WHERE `code` IN ('name1', 'name2') LIMIT 0,1000

This is also fast:
SELECT COUNT(*) FROM TABLE WHERE `dt` BETWEEN '2014-01-01' AND  '2014-12-01' LIMIT 0,1000

But combining both takes minutes:
 SELECT COUNT(*) FROM TABLE WHERE `code` IN ('name1', 'name2') AND `dt` BETWEEN '2014-01-01' AND  '2014-12-01' LIMIT 0,1000

Can somebody explain me why the last query takes very long while the two first queries are superfast?
The output of explain for the last query is:
Select type: Simple
Type: Range
possible keys: dt_index, code_index
key: ts_index

Comment: Create a composite index containing both columns.
Comment: Do you have 2 seperate indexes or a combined one? What is the `explain select ...` output?
Comment: two separate indexes. Here is the explain output:
Select type: Simple
Type: Range
possible keys: dt_index, code_index
key: ts_index
Comment: Add the output to the question please
Comment: That did it!! Creating a composite index solved the problem.
Answer: MySQL will only use one index and since neither of your two indexes hold values for both criteria it potentially have to scan lots of rows to find 1000 that matches. I think it could potentially be as fast as the first query if your date interval was big enough, say between 1970 and 2015.
To fix it you can add a index covering both columns (and drop the now unneeded one one)
alter table TABLE add index dt_code_index (dt, code), drop index dt_index;

or
alter table TABLE add index code_dt_index (code, dt), drop index code_index;

Answer: It was fairly simple. I needed to add a composite index to the table as suggested by xQbert:
create index fast_index ON traces (dt, code);

Now all 3 queries run fast.

Mysql single table very slow


What is the best way to design the GUI in javafx 2.0?

Question: In javafx 2.0 it is possible to create the layout by using FXML approach or by using normal java code.
What is the best way with respect to a well designed set of UIs. In my application there is about 100 sub UIs.
Thanks
Comment: Focus on your user's needs first. Worry about technology seconds.
Answer: FXML looks more logical for that purpose. By using FXML

you split business logic from view
you get option to edit design without recompiling project.
you get design as structured xml tree which is much easier to edit comparing to potentially randomly ordered java code
with SceneBuider tool you get an option to use visual editor for your fxml files
Answer: Get JavaFX Scenebuilder here.
Answer: FXForm2 is a library providing automatic JavaFX 2.0 form generation.
however FXForm2 is not full WYSIWYG GUI design tool.
http://dooapp.github.io/FXForm2/
Answer: Scene builder should be a good starting point to create unique UIs of your application. Considering you have 100s of UIs, I assume that some of their "appearances" should be identical with slightly different functions. You can load the FXML dynamically and assign controller at run time. Which means 1 FXML file can be used with multiple controllers. Which can save you some time while keeping the code dynamic for easier maintenance.
<code>    FXMLLoader loader = new FXMLLoader(getClass().getResource("DBedit.fxml"));
    loader.setController(new DBeditEntityUser());
</code>
So, to make use of the same FXML with a different controller.
<code>    FXMLLoader loader = new FXMLLoader(getClass().getResource("DBedit.fxml"));
    loader.setController(new DBeditEntityUserLevel());
</code>
Hope this helps.
Answer: fyi,
road map for Java fx http://javafx.com/roadmap/  shows that the scene builder will be released around middle of the year. From the above web page:
"JavaFX Scene Builder is a WYSIWYG GUI design tool for the
JavaFX platform. It enables designing user interface screens by simply
dragging and positioning  GUI components from a palette onto a scene.
The tool generates files in FXML format2 that can be used within a project
in any IDE such as NetBeans or Eclipse. The JavaFX Scene Builder can be
used to create GUI for desktop applications and applets that run in a browser."


My keybindings.json has no effect on VSCode

Question: I am trying to change the default behaviour from "ctrl + d" to "editor.action.copyLinesDownAction".
I added the required setting in keybindings.json:
<code>{
    "key": "ctrl+d",
    "command": "editor.action.copyLinesDownAction",
}
</code>
But still the default behaviour for "ctrl + d" is executed ("Add selection to next find match")
My keybindingService-Log is looking good:
<code>Received  keydown event - modifiers: [ctrl], code: ControlLeft, keyCode: 17, key: Control
Converted keydown event - modifiers: [ctrl], code: ControlLeft, keyCode: 5 ('Ctrl')
Keyboard event cannot be dispatched in keydown phase.
Received  keydown event - modifiers: [ctrl], code: KeyD, keyCode: 68, key: d
Converted keydown event - modifiers: [ctrl], code: KeyD, keyCode: 34 ('D')
Resolving ctrl+D
From 1 keybinding entries, matched editor.action.copyLinesDownAction, when: no when condition, source: user.
Storing single modifier for possible chord ctrl.
Clearing single modifier due to 300ms elapsed.
</code>
What am i missing?
edit: provide full log
edit: I did some more testing and my keybindings.json seems to have no effect at all. I'm jusing Jupyter Notebooks for VSCode. Maybe there is something to override it?
Comment: I see that any find match on a line to be duplicated "goes with" the duplicated line - and leaves the original line.  Is that what you are referring to and trying to avoid?  If so, try binding `editor.action.copyLinesUpAction`  to `Ctrl+D` instead.
Comment: Not really, i can't duplicate any line with ctrl+d.
Instead the default keybinding for ctrl+d is executed (even though I deleted it and set a new keybinding for ctrl+d.
I edited my question for clarification.
Comment: It works for me and I don't have to disable `"-editor.action.addSelectionToNextFindMatch"` either. So very strange.
Comment: I did some more testing and my keybindings.json seems to have no effect at all. I'm using Jupyter Notebooks for VSCode. Maybe there is something to override it?
Answer: Seems like VSCode does only host a Jupyter instance and can not change the keybindings inside. So there is no way to edit keybindings for Jupyter Notebooks in VSCode


Prob. 2, Sec. 30, in Munkres' TOPOLOGY, 2nd ed: Every basis of a second-countable space contains a countable basis

Question: Here is Prob. 2, Sec. 30, in the book Topology by James R. Munkres, 2nd edition:

Show that if $X$ has a countable basis $\left\{ B_n \right\}$, then every basis $\mathscr{C}$ for $X$ contains a countable basis for $X$. [Hint: For every pair of indices $n, m$ for which it is possible, choose $C_{n, m} \in \mathscr{C}$ such that $B_n \subset C_{n, m} \subset B_m$.]

My Attempt:

As each set $C \in \mathscr{C}$ is an open set of the topological space $X$ and as $\left\{ B_n \right\}$ is a basis for the topology of $X$, so $C$ is a union of some of the sets $B_n$ and thus there exists a set $B_n$ such that $B_n \subset C$, by Lemma 13.1 in Munkres.

Conversely, as each set $B_m$ is an open set in $X$ and as $\mathscr{C}$ is a basis for $X$, so $B_m$ can be written as a union of some sets from $\mathscr{C}$ and thus there exists a set $C \in \mathscr{C}$ such that $C \subset B_m$, again by Lemma 13.1 in Munkres.

Moreover, the collection $\left\{ C_{n,m} \right\}$ is indexed by a subset $J$ of $\mathbb{N}\times\mathbb{N}$ and so is at most countable.

Finally, let $U$ be any open set of $X$ and let $x \in U$. Then there exists a set $B_m$ such that
$$ x \in B_m \subset U. \tag{1} $$
Next, as $B_m$ is an open set in $X$, as $x \in B_m$,  and as $\mathscr{C}$ is a basis for the topology of $X$, so there exists a set $C_x \in \mathscr{C}$ such that
$$ x \in C_x \subset B_m. \tag{2} $$
And, as $C_x$ is an open set of $X$ and as $x \in C_x$, so there exists a set $B_n$ such that
$$ x \in B_n \subset C_x.  \tag{3} $$
From (2) and (3) we obtain
$$ B_n \subset C_x \subset B_m, $$
which implies that set $C_{n, m}\in \mathscr{C}$ is well-defined such that
$$ B_n \subset C_{n,m} \subset B_m. \tag{4} $$

Finally, from (3), (4), and (1) above, we obtain
$$ x \in B_n \subset C_{n, m} \subset B_m \subset U, $$
and so
$$ x \in C_{n, m} \subset U. \tag{5} $$

Thus for every open set $U$ in $X$ and for every point $x \in U$, there exists a set $C_{n, m}$ such that (5) above holds.

Hence by Lemma 13.2 in Munkres the countable collection $\left\{ C_{n,m} \right\}$ is indeed a basis for $X$.

Is my proof correct and clear enough in each and every detail? Or, are there errors and confusions in it?
Answer: The first two paragraphs are superfluous; just follow the hint:
If, for some $(n,m) \in \Bbb N^2$, the set $\mathscr{C}_{n,m}$ given by
$$
\mathscr{C}_{n,m} := \left\{C \in \mathscr{C} |  B_n \subseteq C \subseteq B_m \right\}$$
is non-empty, pick $C_{n,m} \in \mathscr{C}_{n,m}$. So the collection we pick is indexed by the set
$$ J := \left\{ (n,m) \in \mathbb{N}^2 | \mathscr{C}_{n,m} \neq \emptyset \right\} $$ and this set $J \subseteq \Bbb N^2$, so this collection is (at most) countable.
The claim is that the collection $\mathscr{C}^\prime$ given by
$$
\mathscr{C}^\prime := \left\{ C_{n,m} | (n,m) \in J \right\}$$ is a basis.
The rest of the argument is fine: If $x \in O$, $O$ open, and by succesive applications of $\mathscr{B}, \mathscr{C}, \mathscr{B}$ being a basis, we get $N, M \in \mathbb{N}$ and $C_x \in \mathscr{C}$ such that
$$ x \in B_N \subseteq C_x \subseteq B_M \subseteq O,
$$
and so by definition $\mathscr{C}_{N, M}  \neq \emptyset$ and thus $(N, M) \in J$ and hence  $C_{N, M} \in \mathscr{C}^\prime$ can be used in the same "squeeze" and
$$
x \in C_{N,M} \subseteq O,
$$
and as $O$ and $x$ were arbitary, $\mathscr{C}^\prime$ is a (countable) basis for the topology of  $X$.
The fact that $\mathscr{B}$ is a basis for $X$ iff
$$
\forall O \text{ open }: \forall x \in O: \exists B \in \mathscr{B}: x \in B \subseteq O
$$
is just a reformulation of the definition, and is constantly used almost implicitly. I gather that you quote it as lemma 13.1?
Comment: I have just made some edits to your answer. Hope you won't find these edits to be too unacceptable.
Comment: @SaaqibMahmood they seem very minor like changing $n,m$ to $N,M$ e.g.? Why is that better?
Comment: while the point you've made is a valid one, don't you think that the way I've changed the notation from your $J(n, m)$ to the $\mathscr{C}_{n,m}$ makes your beautiful proof a bit easier to follow, especially for a novice?
Comment: @SaaqibMahmood I don't think it makes a difference that I would notice. But I won't revert as the essence is still the same.


How to determine empty row?

Question: How I can determine empty rows in .xls documents using Apache POI?
Answer: I'm using the following method in my POI project and it's working well. It is a variation of zeller's solution.
public static boolean isRowEmpty(Row row) {
    for (int c = row.getFirstCellNum(); c < row.getLastCellNum(); c++) {
        Cell cell = row.getCell(c);
        if (cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK)
            return false;
    }
    return true;
}

Comment: I have used the same piece of code but it returns false for cell value empty. If I check if(cell.getStringCellValue != null && cell.getNumericValue != null) it works for String value but for BigDecimal value it returns IllegalStateException: Cannot convert text to numeric value. Can you suggest me how to handle isRowEmpty to return true for empty row?
Comment: And what if Cell Type is of Formula?
Answer: The row iterator returns only rows that contain data, however if they are completely empty then iterating by row index, getRow(index)  returns null
Solution:
Up to POI version 3.14 (thanks to Sergii Lisnychyi):
private boolean checkIfRowIsEmpty(Row row) {
    if (row == null) {
        return true;
    }
    if (row.getLastCellNum() <= 0) {
        return true;
    }
    for (int cellNum = row.getFirstCellNum(); cellNum < row.getLastCellNum(); cellNum++) {
        Cell cell = row.getCell(cellNum);
        if (cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK && StringUtils.isNotBlank(cell.toString())) {
            return false;
        }
    }
    return true;
}

From POI version 3.15 to 4.2 (int getCellType() is deprecated):
    private boolean checkIfRowIsEmpty(Row row) {
    if (row == null) {
        return true;
    }
    if (row.getLastCellNum() <= 0) {
        return true;
    }
    for (int cellNum = row.getFirstCellNum(); cellNum < row.getLastCellNum(); cellNum++) {
        Cell cell = row.getCell(cellNum);
        if (cell != null && cell.getCellTypeEnum() != CellType.BLANK && StringUtils.isNotBlank(cell.toString())) {
            return false;
        }
    }
    return true;
}

From POI version 4 (CellTypeEnum getCellTypeEnum() will return the Enum not int):
private boolean checkIfRowIsEmpty(Row row) {
    if (row == null) {
        return true;
    }
    if (row.getLastCellNum() <= 0) {
        return true;
    }
    for (int cellNum = row.getFirstCellNum(); cellNum < row.getLastCellNum(); cellNum++) {
        Cell cell = row.getCell(cellNum);
        if (cell != null && cell.getCellTypeEnum() != CellType.BLANK && StringUtils.isNotBlank(cell.toString())) {
            return false;
        }
    }
    return true;
}

From POI version 5.1 (CellTypeEnum getCellTypeEnum() renamed to getCellType()):
private boolean checkIfRowIsEmpty(Row row) {
    if (row == null) {
        return true;
    }
    if (row.getLastCellNum() <= 0) {
        return true;
    }
    for (int cellNum = row.getFirstCellNum(); cellNum < row.getLastCellNum(); cellNum++) {
        Cell cell = row.getCell(cellNum);
        if (cell != null && cell.getCellType() != CellType.BLANK && StringUtils.isNotBlank(cell.toString())) {
            return false;
        }
    }
    return true;
}

Comment: From POI version 3.15 to 4.2 cell.getCellTypeEnum()  does not exist, instead can use    if (cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK && !cell.toString().isEmpty()) {
    return false;
   }
Comment: Not sure when it was introduced, but I'm on 5.2.3 and (assuming you dont need all the special isBlank checks) it seems like you can just do `if (row.getLastCellNum() == -1) {return true; }
Answer: You have to iterate through all cells in the row and check if they are all empty. I don't know any other solution...
 short c;
 for (c = lastRow.getFirstCellNum(); c <= lastRow.getLastCellNum(); c++) {
     cell = lastRow.getCell(c);
     if (cell != null && lastRow.getCell(c).getCellType() != HSSFCell.CELL_TYPE_BLANK) {
          nonBlankRowFound = true;
     }
 }

The code is from here
Answer: Assuming you want to check if row n is empty, remembering that rows in Apache POI are zero based not one based, you'd want something like:
 Row r = sheet.getRow(n-1); // 2nd row = row 1
 boolean hasData = true;

 if (r == null) {
    // Row has never been used
    hasData = false;
 } else {
    // Check to see if all cells in the row are blank (empty)
    hasData = false;
    for (Cell c : r) {
       if (c.getCellType() != Cell.CELL_TYPE_BLANK) {
         hasData = true;
         break;
       }
    }
 }

Answer: Yes, but if in some row we will have in some cell =  " " and empty values in another cells.
                                                               This method will be work better:
  boolean isEmptyRow(Row row){
     boolean isEmptyRow = true;
         for(int cellNum = row.getFirstCellNum(); cellNum < row.getLastCellNum(); cellNum++){
            Cell cell = row.getCell(cellNum);
            if(cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK && StringUtils.isNotBlank(cell.toString())){
            isEmptyRow = false;
            }
         }
     return isEmptyRow;
   }

Answer: If you are using apache-poi [4+]:
Then the below method works for you. As the other methods suggested did not work for me, I had to do it this way.
public static boolean isRowEmpty(Row row) {
    boolean isEmpty = true;
    DataFormatter dataFormatter = new DataFormatter();
    if(row != null) {
        for(Cell cell: row) {
            if(dataFormatter.formatCellValue(cell).trim().length() > 0) {
                isEmpty = false;
                break;
            }
        }
    }
    return isEmpty;
}

The method dataFormatter.formatCellValue(cell) would return "", an empty / ZERO length string when the cell is either null or BLANK.
The import statements for your reference:
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Cell;

Hope this helps!
Answer: boolean isEmptyRow(Row row) {
    boolean isEmpty=true;
    String data="";
    for(Cell cell:row) {
        data=data.concat(cell.getStringCellValue());
    }
    if(!data.trim().isEmpty()) {
        isEmpty=false;
    }
    return isEmpty;
}

Answer: try using if(iterator.hasNext)
Row nextRow = null;
Cell nextCell = null;
Iterator<Row> iterator = firstSheet.rowIterator();
if(iterator.hasNext) {
    return true;
}
else {
    return false;
}

Comment: That iteration would be while file has any row and it would be despite row has empty cells
Answer: get the instance of CellReference and use formatAsString() on the instance. compare it with an empty String
`
if("".equals(cellRef.formatAsString())){
     System.out.println("this is an empty cell");
   }else{
      System.out.println("Cell value : "+cellRef.formatAsString());
   }

`
Reference : http://www.javabeat.net/2007/10/apache-poi-reading-excel-sheet-using-java/
Answer: Row == null is work in my case.
int total_row = mySheet.getLastRowNum();
int current_row = 0;
HSSFRow hssf_Row;

while (current_row <= total_row) {
    hssf_Row = mySheet.getRow(current_row);
    if (hssf_Row == null) Log.d("empty row","row=" + String.valueOf(current_row));
    current_row++;
}

Answer: you could also use row.cellIterator() method which returns a iterator of the row containing all the cells.
If the row is blank
Iterators.size(row.cellIterator()) would be zero
Answer: At least as of poi-ooxm 5.2.3 it seems like you can do:
for (Row row : sheet) {
    if (row.getLastCellNum() == -1) {
        continue;
    }

    //do processing
}

This would not check for empty text etc, you would probably want @EpicPandaForce's robust answer.
But for the case where someone on your team added a bunch of blank rows, this seems to be all you need.

How to determine empty row?


System.StackOverflowException too much recursion

Question: I am doing an Algorithm class and I am building an implementation of Kosaraju's algorithm as part of the homework.
I have several small datasets where the algorithm is returning the correct results and performing fine. However, when I attempt my homework assignment which has 5,105,043 edges and 875,714 nodes in it I am getting a System.StackOverflowException which seems to be because there is too much recursion.
However, this recursion is required to solve the question. So what I am asking is there a way to configure .Net to allow more recursion?
Comment: How deep *is* your recursion at the moment?
Comment: How do I discern that from the exception? Sorry I am not too familiar with debugging this error.
Comment: Can`t you modify your DFS to be iterative?
Comment: @JonSkeet I believe I have processed 7149 nodes in the first pass so hardly scratching the surface unfortunately.
Comment: @dwrd I can modify my Depth First Search to be iterative. Am I not likely to be able to get this to work recursively?
Comment: @baynezy, take a look [here](http://www.atalasoft.com/cs/blogs/rickm/archive/2008/04/22/increasing-the-size-of-your-stack-net-memory-management-part-3.aspx), but your amount of nodes and adges is really large, I think that iterative way is better for this.
Comment: The thing to remember about recursion is, it's nice in theory, but when it comes to implementing it, practical people try real hard not to and come up with an iterative solution. As soon as it starts getting bit too deep, we run into practical hardware limits.
Answer:
So what I am asking is there a way to configure .Net to allow more recursion?

The recursion limit is based on the stack size allocated for the current thread.   This can be changed via editbin /stack for the program, or edited for a specific thread upon the thread's construction.
That being said, any recursive algorithm can be switched to using a stack instead.  This would likely prove more maintainable over time, as it would no longer be dependent on having a very large stack to process appropriately.
Comment: I totally appreciate that it is not ideal to be recursing to this degree. I was just trying to follow the idea through the it's conclusion. Your advice on using a thread solved it for me thank you.


Can not access ubuntu computer on my windows xp pc

Question: I can see my ubuntu machine in the work group of my windows xp pc but when i click it says that it is not accessible/no permission/the parameter is incorrect etc.
Answer: There are a few steps to follow..
First you have to install Samba on your Ubuntu machine
sudo apt-get install samba smbfs

Then you have to modify smb.conf
sudo gedit /etc/samba/smb.conf

and find the line
workgroup = WORKGROUP

based on your workgroup inside WinXP, modify this line accordingly. Maybe you don't have to modify this file at all. If you did modify it, restart Samba
sudo service samba restart

Now go back to WinXp and try again
Answer: Make sure you have your folder permissions so you can access it on the network