text:
Q: Solve $|3-x|=x-3$.
Solve: $|3 - x| = x - 3$.
Answer: $|u| = -u$ when and only when $u \le 0$. So, $|3 - x| = x - 3$ when and only when $3 - x \le 0$; that is, $3 \le x$.

Hi! I'm new here. I'm working out of this book called Schaum's Outlines 3,000 Solved Problems in Calculus. I understand that when solving for absolute values that you have to draw two equations, for example when solving for $|x+3|<5$ you must solve for both $x+3<5$ AND $x+3>-5$. But can someone please explain the process above to me? I don't understand it. Thanks!

A: This is the definition of the absolute value of a real number that we are using:
$$|x| = \begin{cases}x; & x > 0 \\ 0; & x = 0 \\ -x; & x < 0\end{cases}$$
The equation to be considered is:
$$|3 - x| = x - 3 = \begin{cases}3 - x; & 3 - x > 0 \\ 0; & 3 - x = 0 \\ -(3 - x); & 3 - x < 0\end{cases}$$
We see that we don't need to consider $ 3 - x > 0$ because that case doesn't make sense. Only $3 - x = 0$ and $3 - x < 0$ will give you sensible answers. Conclude $ 3 \le x$.

A: $|-u|=|-1 \cdot u|=|-1| \cdot |u|=1 \cdot |u|=|u| \\ |u|=u \text{ if } u \ge0 \\ |3-x|=|(-1)(x-3)|=|x-3| \\ |x-3|=x-3 \text{ if } x-3 \ge 0$

A: the graph of $y = |3-x|$ is $v$-shaped with the vertex at $(3,0)$ and it lies in the upper half plane. on the left of $x = 3$ is the line $y = 3 - x$ and to the right is  the line $y = x - 3$  the equation $|3-x| = x - 3$ is satisfied for all $x \ge 3.$


text:
Q: Do tmpfs and devtmpfs share the same memory region? My system disk usage is like this:
# df -h
Filesystem             Size  Used Avail Use% Mounted on
/dev/mapper/rhel-root   50G   39G   12G  77% /
devtmpfs               5.8G     0  5.8G   0% /dev
tmpfs                  5.8G  240K  5.8G   1% /dev/shm
tmpfs                  5.8G   50M  5.8G   1% /run
tmpfs                  5.8G     0  5.8G   0% /sys/fs/cgroup
/dev/mapper/rhel-home  1.3T  5.4G  1.3T   1% /home
/dev/sda2              497M  212M  285M  43% /boot
/dev/sda1              200M  9.5M  191M   5% /boot/efi
tmpfs                  1.2G   16K  1.2G   1% /run/user/1200
tmpfs                  1.2G   16K  1.2G   1% /run/user/1000
tmpfs                  1.2G     0  1.2G   0% /run/user/0

I have 2 questions about devtmpfs and tmpfs:
(1)
devtmpfs               5.8G     0  5.8G   0% /dev
tmpfs                  5.8G  240K  5.8G   1% /dev/shm
tmpfs                  5.8G   50M  5.8G   1% /run
tmpfs                  5.8G     0  5.8G   0% /sys/fs/cgroup

All the above spaces are 5.8G, do they share the same memory space?
(2)
tmpfs                  1.2G   16K  1.2G   1% /run/user/1200
tmpfs                  1.2G   16K  1.2G   1% /run/user/1000
tmpfs                  1.2G     0  1.2G   0% /run/user/0

Does each user has his dedicated memory space, not shared space in /run/user partition?

A: For all the tmpfs mounts, "Avail" is an artificial limit.  The default size for tmpfs mounts is half your RAM.  It can be adjusted at mount time.  (man mount, scroll to tmpfs).
The mounts don't share the same space, in that if you filled the /dev/shm mount, /dev would not show any more "Used", and it would not necessarily stop you from writing data to /dev
(Someone could contrive tmpfs mounts that share space by bind-mounting from a single tmpfs.  But that's not how any of these mounts are set up by default).
They do share the same space, in that they're both backed by the system memory.  If you tried to fill both /dev/shm and /dev, you would be allocating space equal to your physical RAM.  Assuming you have swap space, this is entirely possible.  However it's generally not a good idea and would end poorly.

This doesn't fit well with the idea of having multiple user-accessible tmpfs mounts.  I.e. /dev/shm + /tmp on many systems.  It arguably would be better if the two large mounts shared the same space.  (Posix SHM is literally an interface to open files on a user-accessible tmpfs).
/dev/, /run, /sys/fs/cgroups are system directories. They should be tiny, not used for sizeable data and so not cause a problem.  Debian (8) seems to be a bit better at setting limits for them; on a 500MB system I see them limited to 10, 100, 250 MB, and another 5 for /run/lock respectively.
/run has about 2MB used on my systems.  systemd-journal is a substantial part of it, and by default may grow to 10% of "Avail".  (RuntimeMaxUse option), which doesn't fit my model.
I would bet that's why you've got 50MB there.  Allowing the equivalent of 5% of physical RAM for log files... personally it's not a big problem in itself, but it's not pretty and I'd call it a mistake / oversight.  It would be better if a cap was set on the same order as that 2MB mark.
At the moment it suggests the size for /run should be manually set for every system, if you want to prevent death by a thousand bloats.  Even 2% (from my Debian example) seems presumptuous.

A: Each tmpfs instance is independent so it's possible to overallocate memory, and if you fill up the entire memory with large files on tmpfs, the system will eventually halt due to no more memory available and not possible to free any (without deleting tmpfs files or umounting it).
tmpfs can use swap partitions to swap out data, but even that does not help if you're reading/writing those files actively at which point it has to be swapped back in.
Basically systems that have lots of instances of tmpfs mounted, usually operate under the assumption that although tmpfs is there, it won't actually be filled to the limit.

If you want to try this - preferably on a Live CD with nothing mounted - then it works like this:
mkdir a b c
mount -t tmpfs tmpfs a
mount -t tmpfs tmpfs b
mount -t tmpfs tmpfs c
truncate -s 1T a/a b/b c/c
shred -v -n 1 a/a b/b c/c

That creates three instances of tmpfs, by default each has a 50% memory limit so it's 150% in total (not counting swap, if you do have swap feel free to add d e f ...).
Output of shred will look something like this:
shred: a/a: pass 1/1 (random)...
shred: a/a: error writing at offset 1049104384: No space left on device
shred: b/b: pass 1/1 (random)...
# system hangs indefinitely at this point, without swap it never reaches c/c #

A: (1) All file systems based on tmpfs are sharing the OS available virtual memory as back-end. devtmpfs happens to use the same space but unlike the former, doesn't contain data so shouldn't grow.
(2) /run/users subdirectories are created by systemd as personal, transcient /tmp directories. They also share the same virtual memory space with all other tmpfs based file systems. The fact they appear smaller is due to a capping put in place to prevent a single user to affect all other users by filling this directory.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Partition Key for CosmosDB Graph vertices and edges I am creating a graph and initially used a partition key that seems like the only logical one given the set of data. However, the number of vertices and edges ends up being too large for a single partition. I did not create a partitioned collection yet but only created a single 10GB collection.  I ran this out of space and filled it up as I wasn't sure how many vertices and edges I would have.  The data is a set of categories with varying number of subcategories(and subcategories of those subcats down to an arbitrary depth).  The data is a category id and name and a market for which the category applies.  The partition key is currently the market.  Within a given market there are a bunch of category/subcat/subcat/... that exhausted the 10GB partition for that given market.
If all I have is a category id which is unique, a category name, and a market (as a vertex), and then a parentOf edge the connects a parent category to its children, then what else would make sense as a partition key?  If I have a parent category (vertex) with id of 1, a market of 'US', and it has 100 subcategories each with their own id and the corresponding 100 edges for the parentOf connections all with same market of 'US', then the only other option I have for a partition key other than the market is the category id.  The issue is, how efficient would lookups and traversals be if the children and children of those children(and edges) are in other partitions?
How do you build a very large graph with a scenario like this?
Given an arbitrary category id, what would the performance be like to find all the children and walk the edges down to find all the children in the hierarchy of those edges?
What would the partition key attribute for the edges need to be?  The same partition key as the parent vertex or the same partition key as the child vertex?
Am I thinking about this wrong?

A: My recommendation for any non-trivial graph implementation is to make a super generic property that all your docs must include such as (quite literally) partitionKey. Then you're free to use the value for market in that field where it makes sense and something else to support a different query pattern.
The important thing to understand is that queries across multiple partitions are going to be slow. So as much as possible you should tailor your partition key to support the best balance between reads and writes.
Ask yourself "What queries will I need to perform against this data most often?" and then adjust the partitionKey for the various documents accordingly.
As for edges, when you add an edge between two vertices using Gremlin, Cosmos automatically places the edge document in the same partition as the out vertex.


text:
Q: BHO/Toolbar: prevent Internet Explorer from recording history I've got a fairly elaborate BHO/Toolbar thing in place that has a "login" feature. My goal is to make sure that IE does not record history while toolbar is "logged-in".
I can't just delete history entries, since they might have been added while toolbar was "logged-out".
Is there a mechanism that would notify me when a history entry is about to be added?
EDIT1: Related post on social.msdn.com: http://social.msdn.microsoft.com/Forums/en-US/ieextensiondevelopment/thread/843eea9c-6de7-47b5-aecd-0515ce894cd1/
Thanks,
Yuriy

A: From jeffdav:
No.  What you want to do will not be easy.  The only access to Url History that you get is IUrlHistoryStg (and IUrlHistoryStg2).  Neither interface provides what you want.  I'm fairly certain there is no "onBeforeWriteToHistory" event.  If such an event existed, I would expect it to be in DWebBrowserEvents2.  And you'll see that there is no such event.
Writing to history is really an internal thing for IE.


text:
Q: Finding last number generated by a sequence before it got deleted We found that there is a sequence "_SEQUENCE" is not present in one of our client's UAT instance. We don't how it got deleted and when. It is a very crucial sequence because the numbers generated by this sequence are used as unique column values in many tables across DB. In other words, no two columns (of specific column types) in any two tables in the DB will have the same number as value. On few of these columns, we have unique index also.
We can create the sequence again but we don't know what should be the initial value of the sequence because we don't know what was the last number the old sequence generated. If we set a wrong number as the initial value and by chance, if it generates the same number for the same column of a table which is already present, we may end up getting unique key violation exception.
We can set the initial value to a very big number but that is the last option. Now;

*

*Is it possible to find the last number the sequence "_SEQUENCE" generated before it got deleted?

*Is it possible to find which process deleted the sequence "_SEQUENCE" and when?

A: The flashback operation is not available for a sequence, while it's available for tables. A mechanishm might be produced by the contribution of a DDL trigger mostly created in SYS or SYSTEM database users. As an example consider this procedure :
create or replace procedure pr_ddl_oper as
  v_oty          varchar2(75) := ora_dict_obj_type;
  v_don          varchar2(75) := ora_dict_obj_name;
  v_evt          varchar2(75) := ora_sysevent;
  v_olu          varchar2(75) := nvl(ora_login_user,'Unknown Schema');
  v_sql          ora_name_list_t;
  v_stm          clob;
  v_sct          owa.vc_arr;
  n              pls_integer;
  n_max          pls_integer := 10000; -- max number of rows for CLOB object
                                       -- to hold object's source.
begin
      v_sct(1) := 'SESSIONID';
      v_sct(2) := 'IP_ADDRESS';
      v_sct(3) := 'TERMINAL';
      v_sct(4) := 'OS_USER';
      v_sct(5) := 'AUTHENTICATION_TYPE';
      v_sct(6) := 'CLIENT_INFO';
      v_sct(7) := 'MODULE';
      for i in 1..7
      loop
       v_sct(i) := sys_context('USERENV',v_sct(i));
      end loop;
      select decode(v_sct(1),0,null,v_sct(1)),decode(upper(v_sct(3)),
            'UNKNOWN',null,v_sct(3))
        into v_sct(1),v_sct(3)
        from dual;

       n := ora_sql_txt( v_sql );
      if n > n_max then
       n := n_max;
      end if;
      for i in 1..n
      loop
       v_stm := v_stm || v_sql(i);
      end loop;

       insert into log_ddl_oper(event_time,usr,evnt,stmt,sessionid,ip,terminal,os_user,
         auth_type,object_type,object_name,client_info,module_info)
       values(sysdate,v_olu,v_evt,v_stm,v_sct(1),v_sct(2),v_sct(3),v_sct(4),v_sct(5),
         v_oty,v_don,v_sct(6),v_sct(7));
end;

which could be called by this trigger as to be a future reference  :
--| Compiling this trigger, especially for Production Systems, should be handled with care |

create or replace trigger system.trg_admin_ddl before ddl on database
declare
begin
 pr_ddl_oper;
end;

By connecting SYS user you can query the last_number column for your dropped Sequence :
select last_number
  from dba_sequences
  as of timestamp to_timestamp('2018-11-27 23:50:17', 'YYYY-MM-DD HH24:MI:SS') s
 where s.sequence_name = 'MYSEQ';

where the timestamp value could be detected by
select l.event_time
--> returns to_timestamp('2018-11-27 23:50:17', 'YYYY-MM-DD HH24:MI:SS')
--> to use for the above SQL Select statement
  from log_ddl_oper l
 where l.object_name = 'MYSEQ'
   and l.evnt = 'DROP'


text:
Q: How to stick table header(thead) on top while scrolling down the table rows with fixed header(navbar) in bootstrap 3? Bootstrap layout with fixed-navbar. Having table with so many rows in body.
Issue? As i scroll the page navigation-bar will be there because it is fixed. as i scroll more i want table header to be fixed under navigation-bar and the content of table(table-body) scrolls without scroll bar!
Something like This - Codepen

**Fiddle ** Bootstrap table

Working Fiddle after referring to the answer!

HTML

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

        </button>
        Project name

Home

About

Contact

            Dropdown

Action

Another action

Something else here

Nav header

Separated link

One more separated link

Sticky footer with fixed navbar

Pin a fixed-height footer to the bottom of the viewport in desktop browsers with this custom HTML and CSS. A fixed navbar has been added within #wrap with padding-top: 60px; on the .container.

            #
            First Name
            Last Name
            Username

            1
            Mark
            Otto
            @mdo

            2
            Jacob
            Thornton
            @fat

            3
            Larry
            the Bird
            @twitter

            1
            Mark
            Otto
            @mdo

            2
            Jacob
            Thornton
            @fat

            3
            Larry
            the Bird
            @twitter

            1
            Mark
            Otto
            @mdo

            2
            Jacob
            Thornton
            @fat

            3
            Larry
            the Bird
            @twitter

            1
            Mark
            Otto
            @mdo

            2
            Jacob
            Thornton
            @fat

            3
            Larry
            the Bird
            @twitter

Example courtesy Martin Bean and Ryan Fait.

A: This can now be done without JS, just pure CSS. So, anyone trying to do this for modern browsers should look into using position: sticky instead.
Currently, both Edge and Chrome have a bug where position: sticky doesn't work on thead or tr elements, however it's possible to use it on th elements, so all you need to do is just add this to your code:
th {
  position: sticky;
  top: 50px;  /* 0px if you don't have a navbar, but something is required */
  background: white;
}

Note: you'll need a background color for them, or you'll be able to see through the sticky title bar.
This has very good browser support.
Demo with your code (HTML unaltered, above 5 lines of CSS added, all JS removed):

body {
    padding-top:50px;
}
table.floatThead-table {
    border-top: none;
    border-bottom: none;
    background-color: #fff;
}

th {
  position: sticky;
  top: 50px;
  background: white;
}
<link rel="stylesheet" type="text/css" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

            </button> Project name

Home

About

Contact

 Dropdown

Action

Another action

Something else here

Nav header

Separated link

One more separated link

Sticky Table Headers

If the page is tall and all of the table is visible, then it won't stick. Make your viewport short.

If the page is tall and all of the table is visible, then it won't stick. Make your viewport short.

If the page is tall and all of the table is visible, then it won't stick. Make your viewport short.

                #
                First Name
                Last Name
                Username

                1
                Mark
                Otto
                @mdo

                2
                Jacob
                Thornton
                @fat

                3
                Larry
                the Bird
                @twitter

                1
                Mark
                Otto
                @mdo

                2
                Jacob
                Thornton
                @fat

                3
                Larry
                the Bird
                @twitter

                1
                Mark
                Otto
                @mdo

                2
                Jacob
                Thornton
                @fat

                3
                Larry
                the Bird
                @twitter

                1
                Mark
                Otto
                @mdo

                2
                Jacob
                Thornton
                @fat

                3
                Larry
                the Bird
                @twitter

If the page is tall and all of the table is visible, then it won't stick. Make your viewport short.

If the page is tall and all of the table is visible, then it won't stick. Make your viewport short.

If the page is tall and all of the table is visible, then it won't stick. Make your viewport short.

If the page is tall and all of the table is visible, then it won't stick. Make your viewport short.

If the page is tall and all of the table is visible, then it won't stick. Make your viewport short.

If the page is tall and all of the table is visible, then it won't stick. Make your viewport short.

If the page is tall and all of the table is visible, then it won't stick. Make your viewport short.

Table 2

                #
                New Table
                Last Name
                Username

                1
                Mark
                Otto
                @mdo

                2
                Jacob
                Thornton
                @fat

                3
                Larry
                the Bird
                @twitter

                1
                Mark
                Otto
                @mdo

                2
                Jacob
                Thornton
                @fat

                3
                Larry
                the Bird
                @twitter

                1
                Mark
                Otto
                @mdo

                2
                Jacob
                Thornton
                @fat

                3
                Larry
                the Bird
                @twitter

                1
                Mark
                Otto
                @mdo

                2
                Jacob
                Thornton
                @fat

                3
                Larry
                the Bird
                @twitter

A: I faced the same issue and as majority of the answers indicated, you have to apply position: sticky; and top: 0; ( mostly but can vary if there is a navbar which is fixed as well) to 'th' element. These properties do not apply to thead or tr.
One more thing, if it still doesn't work, you have to look for 'overflow' properties of the parent. If any parent component has an overflow set, i.e. overflow: hidden, then position: sticky just doesn't work. Make sure to remove all such parent properties. Chao!

A: Use: https://github.com/mkoryak/floatThead
Docs: http://mkoryak.github.io/floatThead/examples/bootstrap3/
$(document).ready(function(){
  $(".sticky-header").floatThead({top:50});
});

DEMO with 2 Tables and Fixed Header:  http://jsbin.com/zuzuqe/1/
http://jsbin.com/zuzuqe/1/edit

HTML

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

      </button>
      Project name

Home

About

Contact

          Dropdown

Action

Another action

Something else here

Nav header

Separated link

One more separated link

Sticky footer with fixed navbar

Pin a fixed-height footer to the bottom of the viewport in desktop browsers with this custom HTML and CSS. A fixed navbar has been added within #wrap with padding-top: 60px; on the .container.

        #
        First Name
        Last Name
        Username

        1
        Mark
        Otto
        @mdo

        2
        Jacob
        Thornton
        @fat

        3
        Larry
        the Bird
        @twitter

        1
        Mark
        Otto
        @mdo

        2
        Jacob
        Thornton
        @fat

        3
        Larry
        the Bird
        @twitter

        1
        Mark
        Otto
        @mdo

        2
        Jacob
        Thornton
        @fat

        3
        Larry
        the Bird
        @twitter

        1
        Mark
        Otto
        @mdo

        2
        Jacob
        Thornton
        @fat

        3
        Larry
        the Bird
        @twitter

Table 2

        #
        New Table
        Last Name
        Username

        1
        Mark
        Otto
        @mdo

        2
        Jacob
        Thornton
        @fat

        3
        Larry
        the Bird
        @twitter

        1
        Mark
        Otto
        @mdo

        2
        Jacob
        Thornton
        @fat

        3
        Larry
        the Bird
        @twitter

        1
        Mark
        Otto
        @mdo

        2
        Jacob
        Thornton
        @fat

        3
        Larry
        the Bird
        @twitter

        1
        Mark
        Otto
        @mdo

        2
        Jacob
        Thornton
        @fat

        3
        Larry
        the Bird
        @twitter

CSS
body{
  padding-top:50px;
}
table.floatThead-table {
  border-top: none;
  border-bottom: none;
  background-color: #fff;
}

A:

.contents {
  width: 50%;
  border: 1px solid black;
  height: 300px;
  overflow: auto;
}

table {
  position: relative;
}

th {
  position: sticky;
  top: 0;
  background: #ffffff;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

        colunn 1
        colunn 2
        colunn 3
        colunn 4

        Example 1
        Example 2
        Example 3
        Example 4

            Example 1
            Example 2
            Example 3
            Example 4

                Example 1
                Example 2
                Example 3
                Example 4

                    Example 1
                    Example 2
                    Example 3
                    Example 4

                        Example 1
                        Example 2
                        Example 3
                        Example 4

                            Example 1
                            Example 2
                            Example 3
                            Example 4

                                Example 1
                                Example 2
                                Example 3
                                Example 4

                                    Example 1
                                    Example 2
                                    Example 3
                                    Example 4

                                        Example 1
                                        Example 2
                                        Example 3
                                        Example 4

                                            Example 1
                                            Example 2
                                            Example 3
                                            Example 4

A: You can do it easily with puse CSS without any kind of JS. you have to add position: sticky; top: 0; z-index:999; in table th . But this won't work on Chrome Browser but other browser. To work on chrome you have to add those code in table thead th

.table-fixed {
  width: 100%;
}

/*This will work on every browser but Chrome Browser*/
.table-fixed thead {
  position: sticky;
  position: -webkit-sticky;
  top: 0;
  z-index: 999;
  background-color: #000;
  color: #fff;
}

/*This will work on every browser*/
.table-fixed thead th {
    position: sticky;
    position: -webkit-sticky;
    top: 0;
    z-index: 999;
    background-color: #000;
    color: #fff;
}

        Table Header 1
        Table Header 2
        Table Header 3

        Data
        Data
        Data

        Data
        Data
        Data

        Data
        Data
        Data

        Data
        Data
        Data

        Data
        Data
        Data

        Data
        Data
        Data

        Data
        Data
        Data

        Data
        Data
        Data

        Data
        Data
        Data

        Data
        Data
        Data

        Data
        Data
        Data

        Data
        Data
        Data

        Data
        Data
        Data

        Data
        Data
        Data

        Data
        Data
        Data

        Data
        Data
        Data

        Data
        Data
        Data

        Data
        Data
        Data

        Data
        Data
        Data

        Data
        Data
        Data

        Data
        Data
        Data

        Data
        Data
        Data

        Data
        Data
        Data

        Data
        Data
        Data

        Data
        Data
        Data

A: Anyone looking for this functionality past 2018: it's much cleaner to do this with just CSS using position: sticky.
position: sticky doesn't work with some table elements (thead/tr) in Chrome. You can move sticky to tds/ths of tr you need to be sticky. Like this:
thead tr:nth-child(1) th {
  background: white;
  position: sticky;
  top: 0;
  z-index: 10;
}

A: Here is a jsfiddle HERE (not created by me) that does what you are looking for with pure css in a table.  The thing to note here is the th header is set to a height of 0. Inside each th is and absolute positioned div that puts the header above the table and the scollable div that the table is in.

    #
#

    First Name
First Name

    Last Name
Last Name

    Username
Username

A: Okku's post worked for me in Edge.
In order to get desired result on the iPhone, I had to use:

which didn't effect Edge.

A: I accomplished something similar using jQuery Waypoints.
There's a lot of moving parts, and quite a bit of logic (that I hope to get on GitHub some day soon), but essentially what you could do is...

*

*Duplicate the table DOM structure in JavaScript and add a class called fixed.

*Add styles for table.fixed that make it invisible.

*Set a way point at the bottom of the header navigation that adds a class called sticky to table.fixed

*Add styles for table.sticky.fixed that position it just below the navbar and also make just the thead content visible. This also has a z-index so it is laid above the rest of the content.

*Add another waypoint, but in the downward scroll event, that removes .sticky from the table.fixed
You have to duplicate the entire table DOM in order to ensure column widths line up appropriately.
If that sounds really complicated, you might want to try playing around with the DataTables plugin and the FixedHeader extension: https://datatables.net/extensions/fixedheader/

A: If you want to have an affix on your header you can use this tricks, add position: relative on your th and change the position in eventListener('scroll')
I have created an example: https://codesandbox.io/s/rl1jjx0o
I use vue.js but you can use this, without vue.js

A: For anyone looking for a modern JS framework support like ReactJS or Vue
try this one instead https://github.com/johngerome/js-sticky-table-headers. Which supports overflow layout.
I'm using this one on my Svelte project.


text:
Q: An equivariant social choice in Mathematical economics Motivated by this paper and its  economics motivations, we recall that a social choice among $n$ objects is  a  continuous function $$f:\overbrace{M\times M\times\cdots\times M}^{\text{$n$ times}}\to  M$$
which satisfy the following conditions:
1) $f(x,x,\ldots,x)=x$
2) $f$ is unchanged  under all permutations  $\sigma \in S_{n},$ the symmetric group on $n$ elements.
Perhaps the following could be  considered as a social model for the above mathematical problem.
A  client has to choose one item among $n$ items $(x_{1},x_{2},\ldots,x_{n})$. His preference  function is denoted by the above $f$.
Now it is  natural that we assume that  the client faces with n different items, so $x_{i} \neq x_{j}$, $\forall i \neq j$. So we  consider the ordered  configuration space $$F_{n}(M)=\{(x_{1},x_{2},\ldots,x_{n})\in M^{n}\mid x_{i} \neq x_{j},\;\forall i \neq j\}  $$.
There is  an obvious  action of the  symmetric  group $S_{n}$ on $F_{n}(M)$.
Now the following question can be counted as an  equivariant analogy of the  social choice problem:

Assume that $M$ is  a manifold  which is acted  by the  symmetric  group $S_{n}$. Is there always an equivariant continuous  map $f:F_{n}(M)\to M$? If not, for  what type of  manifolds the answer is  affirmative? What type of algebraic topological obstructions would appear?
Can we find  an economics interpretation for this equivariant version?

Example: For $M=S^{1},\; n=2$, the  symmetric  group $S_{2}$ can act  on $S^{1}$  by complex conjugation $z\mapsto \bar{z}$ Then the function $f(z,w)=z\bar{w}$ satisfies $f(z,w)=\overline{f(w,z)}$.
In this example let's replace the conjugate action by antipodal action. Then $f(z,w)= (z-w)/|z-w|$ is  a  map $f:F_{2}(S^{1})\to S^{1}$  which satisfy $f(z,w)=-f(w,z)$?

A: I'll attempt an answer to the mathematical question, without discussing the motivation. As I understand it, $M$ is a manifold with $S_n$-action, and we are asking whether there exists an $S_n$-equivariant map $f:F_n(M)\to M$, where the action on $F_n(M)$ is by permutation of coordinates (and in particular has nothing to do with the action on $M$).
As a first observation, note that if $x\in M$ is a fixed point $x$, then such an $f$ exists; just map everything to $x$.
A general necessary condition for the existence of a $G$-map $f:X\to Y$ between $G$-spaces is given by the Faddell-Husseini index, as decribed for example in this paper:

Pavle V. M. Blagojević, Wolfgang Lück, Günter M. Ziegler, Equivariant Topology of Configuration Spaces, J. Topology 8 (2015) pp 377–413, doi:10.1112/jtopol/jtu029, arXiv:1207.2852.

Given a $G$-space $X$ and a commutative ring $R$, the Faddell-Husseini index of $X$ is the ideal in $H^*(BG;R)$ defined by
$$
\operatorname{Index}_G(X;R):=\ker(p^*:H^*(BG;R)\to H^*(EG\times_G X;R)),
$$
where $p:EG\times_G X\to BG$ is the projection of the Borel fibration. Then it is easy to see that if there exists a $G$ map $f:X\to Y$ then
$$
\operatorname{Index}_G(Y;R)\subseteq \operatorname{Index}_G(X;R)
$$
must hold. You can sometimes rule out existence of equivariant maps using this property. The index of the configuration space $F_n(M)$ is probably difficult to compute in general, but is done in the linked paper for $M=\mathbb{R}^d$.


text:
Q: Is there a collection for looking up items not only by key, but also properties of an item? I am trying to work out the most efficient way of finding items in my collection. First of all here is some more information/requirements:

*

*Order is not important.

*Must not look up using enumeration.

*Collection will be very large but won't be modified after it is initially
populated.

*Must be able to look up by key (string) but also be able to look up by one of two properties of the item type.

I am currently using a custom collection which inherits from KeyedCollection, which uses GetKeyForItem() to extract a string from the item, to be used as the key, which is fine so far.
The problem is with the way I want to be able to look up items. It is my understanding that aside from 'dirty' enumeration, items are looked up using the same method as they are added, whether that's using a custom equality comparer or a key.
Am I missing something? Is it acceptable practice to create three collections with the same items but with different GetKeyFoItem() implementations for each of the properties that I want to be able to look up by? Or is there another collection that I could use?
I hope this is enough information to illustrate my question. I'd appreciate any advice you have.

A: Try using Linq for this! Linq is very powerfull thing!
Here is small example...
    public class YourClass
    {
        public int ClassIntProperty { get; set; }
        public string ClassStringProperty { get; set; }
    }
    List<YourClass> YourClassItemsList = new List<YourClass>();

    public void SeekItem()
    {
        //Get several items
        var t = YourClassItemsList.Where(item => item.ClassIntProperty == 0).AsEnumerable();
        var tt = YourClassItemsList.Where(item => item.ClassStringProperty == "abc").AsEnumerable();

        //Get one item
        var ttt = YourClassItemsList.FirstOrDefault(item => item.ClassIntProperty == 0);
    }


text:
Q: PHP Unicode Character Detection I'm trying to get contents from a certain webpage , and replace the next mark : '  with another substring. It's not a regular apostrophe and even substr_count($content,"'") return 0.
It seems like I cannot detect that mark, and therefor can't replace him using substr_replace.
How could I handle this problem?
Thanks in advance.

A: Most likely the $content and the ' character in your source code are simply not in the same encoding. substr_count compares byte by byte. The ' character in your source code has the byte representation of however your PHP file is encoded. The $content has the encoding of whatever encoding it's in. If the two don't match, the substring won't be found.
Convert the $content to some standardized encoding you're working in.
Read What Every Programmer Absolutely, Positively Needs To Know About Encodings And Character Sets To Work With Text.

A: If you are working with unicode characters. it's wise to use the multibyte string functions
http://www.php.net/manual/en/function.mb-substr-count.php


text:
Q: Laravel how to catch yielded area has some content? I wonder how can we get yield() content. What if yield() area is empty. For example
<body>
@include('mains.includes.header')
@yield('content')
@include('mains.includes.footer')
</body>

If nothing pass anything to the yield('content') area, website displays header and footer. Instead i would like to abort 404 or smt. I wonder i can try to do like that?
<body>
@include('mains.includes.header')
@if(!empty(yield('content')))
@yield('content')
@else
@php abort(404) @endphp
@endif
@include('mains.includes.footer')
</body>

A: If i understand you correctly you could use this in your blade files, though if you are trying to show 404 page that can be done by using error handlers in laravel https://laravel.com/docs/5.7/errors
 @if(!View::hasSection('content'))
 // more blade stuff here
 @endif


text:
Q: ggplot Axis scaling Following script is used to plot data on one common x and two distinctly scaled y-axes:
scale <- max(data$one) / max(data$two)
#See https://stackoverflow.com/questions/3099219/plot-with-2-y-axes-one-y-axis-on-the-left-and-another-y-axis-on-the-right

ggplot(data3, aes(x=time)) +
  labs(title = "Title", x="Time") +
  geom_line(aes(x=time, y=one, col="cf_media")) +
  geom_line(aes(x=time, y=two * scale, col="two")) +
  scale_x_date(breaks=scales::pretty_breaks(n = 6), expand = c(0,0)) +
  scale_color_manual(values = c("red", "blue")) +
  scale_y_continuous(name="Left Axis",
                     sec.axis=sec_axis(~./scale,
                                       breaks = scales::pretty_breaks(n = 6),
                                       name="Right Axis"),
                     minor_breaks=NULL,
                     breaks = scales::pretty_breaks(n = 6)) +
  theme(legend.position = c(.90, .95),
        legend.title=element_blank())

Out:

The problem with this graph is, that, for some reason, the left axis (red line) doesn't scale appropriately. The minimum axis value is way below the true min. Among 20 graphs, this is the only one that seems to have this error. The right axis (blue) seems just fine.
Question: What's the best way to plot these two time series appropriately with two distinct y-axes, possibly without adding limits=?
The data is pasted below.
Thanks for your help!
dput(data):
structure(list(time = structure(c(15431, 15461, 15492, 15522,
15553, 15584, 15614, 15645, 15675, 15706, 15737, 15765, 15796,
15826, 15857, 15887, 15918, 15949, 15979, 16010, 16040, 16071,
16102, 16130, 16161, 16191, 16222, 16252, 16283, 16314, 16344,
16375, 16405, 16436, 16467, 16495, 16526, 16556, 16587, 16617,
16648, 16679, 16709, 16740, 16770, 16801, 16832, 16861), class = "Date"),
    one = c(18.4221796200761, 18.3967231898903, 16.335633117503,
    16.730296027773, 18.1514409360143, 17.7199441162588, 16.799170250284,
    15.4179238554614, 17.4392839966129, 17.595792430154, 16.9553497988467,
    16.4953670246957, 17.5849417055811, 17.9678266256, 17.1739918955819,
    17.6002431353711, 17.9595179193721, 17.999935039935, 17.7524652108263,
    17.7177489902007, 17.3588650113878, 17.6725182139017, 17.4405657957642,
    17.6704974950091, 17.8875447511326, 16.9658703405016, 17.4780706514254,
    18.1277851044477, 18.1761216072241, 17.1620759199987, 18.4686443856938,
    18.5762732410043, 17.4880377648686, 17.829055609543, 18.3096877847122,
    16.9076887297865, 17.8248723024602, 17.9126225373526, 17.6292589941241,
    18.5179618982914, 18.5366398684046, 18.0677764393526, 16.6418177564593,
    16.9211415340111, 17.9654709207359, 17.6361844282822, 18.2270338206168,
    16.4429651207772), two = c(16.6582662387643, 16.6291067627203,
    16.6371145606996, 16.4961540261816, 17.0596826781454, 16.7062765725755,
    16.7162150801773, 16.5497433654548, 16.289748798776, 16.2175637229181,
    16.2087465723472, 16.7917693011438, 17.0844034991311, 17.1252018488917,
    17.035226133743, 16.7162471713475, 16.7691021105687, 16.2972221957997,
    16.708788985733, 16.7827078467867, 16.4754347061264, 16.0403929689546,
    16.2594260331233, 16.6004611360169, 16.6892567341726, 16.7962173532738,
    16.4205670536356, 16.9984920528234, 16.3600444060327, 16.2367171945242,
    16.5735658839198, 16.5205739998051, 16.483858284178, 15.7240973247951,
    17.0266878151606, 16.9142806023417, 16.788529867979, 16.5935730790947,
    16.424863694705, 17.0269967594955, 16.3278055932357, 16.3832866771369,
    16.6118799527132, 16.8515435281064, 16.8155186621117, 15.5626066989097,
    16.2053235276769, 16.9638862520006)), .Names = c("time",
"one", "two"), row.names = c(NA, 48L), class = "data.frame")

A: If I understand correctly, the OP wants to scale the second time series two so that the scaled values lie within the same interval as the values of time series one.
To achieve this, we need to scale the range as well as to consider an offset, i.e.,
one = scl * two + ofs
The values of scl and ofs can be determined from the min() and max() values of one and two, resp.:
scl <- (max(dat$one) - min(dat$one)) / (max(dat$two) - min(dat$two))
ofs <- min(dat$one) - scl * min(dat$two)

library(ggplot2)
ggplot(dat, aes(x = time)) +
  labs(title = "Title", x = "Time") +
  geom_line(aes(x = time, y = one, col = "one")) +
  geom_line(aes(x = time, y = two * scale + ofs, col = "two")) +
  scale_x_date(breaks = scales::pretty_breaks(n = 6), expand = c(0, 0)) +
  scale_color_manual(values = c("red", "blue")) +
  scale_y_continuous(
    name = "Left Axis",
    sec.axis = sec_axis(~ (. - ofs) / scl,
                        name = "Right Axis"),
    minor_breaks = NULL,
    breaks = scales::pretty_breaks(n = 6)) +
  theme(legend.position = c(.90, .95),
        legend.title = element_blank())

Now, the min and max values, resp., of both time series are plotted at the same y-values.
Please, note that the scale on the left side belongs to time series one (red line) and the scale on the right side belongs to times series two (blue line).


text:
Q: Using phone memory instead of SDCARD
Possible Duplicate:
Android how to create file in Phone memory

I am recording my voice in android using MediaRecorder,But am using SDCARD to store this recorded voice.I want to use phone memory instead of SDCARD.
recorder.setOutputFile("/sdcard//a.wav); how can i use phone memory here instead of sdcard where "recorder" is a MediaRecorder object.

A: Try using the methods in the Context class
Context.getFilesDir()
Context.openFileOutput( name, mode )


text:
Q: Updating textbox asynchronously I am creating an email software which send email to some accounts. I want to append text every time new email is sent or failed. But textbox shows me report after sending all emails. If the toList is very large like 30+ emails the app screen goes white and after sending all emails GUI comes back with the updated OutPutTextBox. Here is the code inside the SendButton_Click method
foreach (String to in toList)
{
    bool hasSent = SendMail(from, "password", to, SubjectTextBox.Text, BodyTextBox.Text);

    if (hasSent)
    {
        OutPutTextBox.appendText("Sent to: " + to);
    }
    else
    {
        OutPutTextBox.appendText("Failed to: " + to);
    }
}

A: What you actually want to do is invoke SendMail asynchronously. There are several ways to do this in .NET 4.0. I recommend starting a Task object in your foreach loop, and scheduling a task continuation for each one to the UI thread:
string subject = SubjectTextBox.Text;
string body = BodyTextBox.Text;
var ui = TaskScheduler.FromCurrentSynchronizationContext();
List<Task> mails = new List<Task>();
foreach (string to in toList)
{
  string target = to;
  var t = Task.Factory.StartNew(() => SendMail(from, "password", target, subject, body))
      .ContinueWith(task =>
      {
        if (task.Result)
        {
          OutPutTextBox.appendText("Sent to: " + to);
        }
        else
        {
          OutPutTextBox.appendText("Failed to: " + to);
        }
      }, ui);
  mails.Add(t);
}

Task.ContinueWhenAll(mails.ToArray(), _ => { /* do something */ });

(syntax might be slightly off; I didn't compile it).

A: This seems to work (assumes a WinForm application):
namespace WindowsFormsApplication5
{
    using System;
    using System.Threading;
    using System.Windows.Forms;

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        TextBox OutPutTextBox = new TextBox();

        /// <summary>
        /// Represents Send Mail information.
        /// </summary>
        class MailInfo
        {
            public string from;
            public string password;
            public string to;
            public string subject;
            public string body;
        }

        void ProcessToDoList( string[] toList )
        {
            foreach ( var to in toList )
            {
                MailInfo info = new MailInfo();
                info.from = "xx"; //TODO.
                info.password = "yy"; //TODO.
                info.to = "zz"; //TODO.
                info.subject = "aa"; //TODO.
                info.body = "bb"; //TODO.
                ThreadPool.QueueUserWorkItem( this.SendMail, info );
            }
        }

        /// <summary>
        /// Send mail.
        /// NOTE: this occurs on a separate, non-UI thread.
        /// </summary>
        /// <param name="o">Send mail information.</param>
        void SendMail( object o )
        {
            MailInfo info = ( MailInfo )o;
            bool hasSent = false;

            //TODO: put your SendMail implementation here. Set hasSent field.
            //

            // Now test result and append text.
            //

            if ( hasSent )
            {
                this.AppendText( "Sent to: " + info.to );
            }
            else
            {
                this.AppendText( "Failed to: " + info.to );
            }
        }

        /// <summary>
        /// Appends the specified text to the TextBox control.
        /// NOTE: this can be called from any thread.
        /// </summary>
        /// <param name="text">The text to append.</param>
        void AppendText( string text )
        {
            if ( this.InvokeRequired )
            {
                this.BeginInvoke( ( Action )delegate { this.AppendText( text ); } );
                return;
            }

            OutPutTextBox.AppendText( text );
        }
    }
}


text:
Q: How can I write an .odt programmatically? I would like to write an .odt file programmatically e.g. include figures from a directory or use different style writing code (like a LaTeX document).
I wonder how can I compile an .odt file and if there are any, which is the best python libraries to do that.

A: Writing a library to do this would be considerably harder then your are anticipating.
Instead, convert the .tex file into an intermediary format, such as HTML (or PDF) and then convert it again into .odt using already existing tools.
Source/Example


text:
Q: Paging not updating when data is empty ZK I recently got assigned to maintaining an app at work which uses ZK Framework. Just getting into it.
It's made with pure Java, no zul. Mostly divided into Richlet and Render classes.
I have a grid that shows info based on search parameters. When two subsequent searches have results, the paging refreshes correctly, but when I perform a search with results, and a search without results afterwards, the information disappears (as expected) but the paging stays the same. For example, if the first search returned 18 pages of data, the second search (with no data) clears the grid but the 18 empty pages stay. Isn't setModel supposed to refresh paging?
This loads the results into the grid:
protected void loadProperties(List<GdiLogDTO> lista, Boolean keepActualPage) {
    if (!keepActualPage) {
        ZKDisplayUtils.cleanComponent(this.ventana);
        this.drawGrid();
    }
    grid.setModel(new SimpleListModel(lista));
}

And this is where the grid is created:
this.grid = new Grid();
grid.setMold("paging");
grid.setPageSize(15);
grid.setSclass("tabla");
grid.setOddRowSclass("oddClass");
grid.setStyle("border:1px solid #CECECE");
grid.setRowRenderer(new GdiLogsRender());

Thanks in advance!

A: This sounds like issue ZK-1869 - likely fixed since version 6.5.4
Which version are you using?


text:
Q: Android Google Analytics - adding to which xml? I was instructed to add the following to some file but not sure which one, please help me.
Mark application entry – Manifest
Add Analytics as application name on Manifest entry as below :

<application
       android:allowBackup="true"
       android:icon="@drawable/ic_launcher"
       android:label="@string/app_name"
       android:theme="@style/AppTheme"
       android:name=".Analytics">

but my current project manifest already have the following:
<application
    android:allowBackup="true"
    android:hardwareAccelerated="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

What should it become now?

A: This means you have Analytics  application class in your app
android:name=".Analytics"

will consider as your application base class.
for more info please refer this link http://developer.android.com/reference/android/app/Application.html

A: Assuming you are using SDK v4, use the link
The documentation is very straight forward so you shouldn't have any issues integrating it.


text:
Q: application layout not supporting with smaller screen size tablet I have created an application for 10" tablet and set the layout related to screen size but my application is not supported with 7" tablet though i design folder in resource as
res/layout-w320dp
res/layout-w600dp
res/layout-w720dp
so please tell me how to set with other screen sizes.

A: The following is a list of resource directories in an application that provides different layout designs for different screen sizes and different bitmap drawables for medium, high, and extra high density screens.
  res/layout/my_layout.xml             // layout for normal screen size ("default")
  res/layout-small/my_layout.xml       // layout for small screen size
  res/layout-large/my_layout.xml       // layout for large screen size
  res/layout-xlarge/my_layout.xml      // layout for extra large screen size
  res/layout-xlarge-land/my_layout.xml // layout for extra large in landscape orientation

  res/drawable-mdpi/my_icon.png        // bitmap for medium density
  res/drawable-hdpi/my_icon.png        // bitmap for high density
  res/drawable-xhdpi/my_icon.png       // bitmap for extra high density

For further reference check here: http://developer.android.com/guide/practices/screens_support.html


text:
Q: Trying to do close and open command quick.db const db = require("quick.db");

module.exports.run = async (client, message, args) => {
  let botfetch = db.fetch(`ddoskoruma_${message.guild.id}`);
  let kapaç = args[0];

    if (kapaç === "aç") {
      db.set(`ddoskoruma_${message.guild.id}`)
      console.log("Open")
    } else if (botfetch) {
      console.log("Already open.")
    }

    if (kapaç === "kapat") {
      db.delete(`ddoskoruma_${message.guild.id}`)
      console.log("Closed.")
    } else if (!botfetch) {
      console.log("Already close.")
    }
    }

module.exports.conf = {
  name: "ddoskoruma"
};

I am trying to do close and open commands with quick.db. I want to do if command already closed, reply "It's already closed/opened." but I'm trying this code for it but I'm getting this error:
(Sorry for my bad english)

(node:26756) UnhandledPromiseRejectionWarning: TypeError: Input cannot be undefined @ ID: ddoskoruma_640958795643617284

A: You need to provide a key and a value when you use db.set(). For example:
db.set(`ddoskoruma_${message.guild.id}`, 1);

Just edit this line and it will work.


text:
Q: Permission denied while mounting windows share wih cifs-utils I want to access a windows share from my vbox ubuntu machine (I have all proxies set up correctly).
The problem is that I get a permission denied error with no extra reasons when trying to mount via :
 mount -t cifs "//server/share" /windowsshare/myshare -o username=<activediruname>,password=<pass>,domain=<ADdomain>,ro

I get this error:
mount error(13): Permission denied
Refer to the mount.cifs(8) manual page (e.g. man mount.cifs)

I have an $ character inside the password but I don't think that is the problem because I have also tried setting the PASSWD env var and removing the password= option and still permission denied error.
Any ideas, clues or information about how to debug the information further will be greatly appreciated .

A: In general, if you use an unescape or not-single-quoted dollar sign on the command line, it is subject to parameter expansion, i.e. the parameter value is substituted for the parameter name. Let's assume your password is foo$bar. I use echo to display to actual executed command line:
$ echo mount -t cifs ... -o username=user1,password=foo$bar,domain=WIN,ro
mount -t cifs ../../ -o username=user1,password=foo,domain=WIN,ro
$ PASSWD=foo$bar
$ echo $PASSWD
foo

You can see the $bar part is replaced by nothing, because in this example there is no bar parameter set. To prevent this, use single-quotes around the $ or the whole term:
$ echo mount -t cifs ... -o 'username=user1,password=foo$bar,domain=WIN,ro'
mount -t cifs ../../ -o username=user1,password=foo$bar,domain=WIN,ro
$ PASSWD='foo$bar'
$ echo $PASSWD
foo$bar

So, the reason for the mount error(13): Permission denied error is, the server rejects your password, because the shell replaced some parts of it.


text:
Q: What is the grammatical function of the bold it in the sentence?
Family planning policy in China takes place against one stark fact.
  This is that China has 22% of the people in the world, but only 7% of
  the total land. To allow such a huge population to expand unchecked
  would soon result in it outstripping the ability of the
  countryside to feed it.

What is the grammatical function of the first 'it' in the second sentence in the above paragraph related to the Present participial phrase after?
To me, 'it' is the object of the verbal phrase 'result in', and the phrase after it is the apposition of 'it'.
Another possibility might be that the actual object of the phrase 'result in' is 'outstripping the ability of the countryside to feed it', and the first it is the logical subject of the phrase.
Which one of my understandings is correct?
Add information:
Except for the two understandings above, I strongly believe that the first 'it' is used as anticipatory object of 'result in' and the Present participial phrase after 'it' is the real object.

A:
Another possibility might be that the actual object of the phrase 'result in' is 'outstripping the ability of the countryside to feed it', and the first it is the logical subject of the phrase.

That I think is the way to parse the construction.
And I think this "it" as well as the "it" at the end of the sentence are both referring to 'China'.


text:
Q: Commands taking very long time to execute on ssh Strangely on few on my linux servers, intermittently, when i try to login through ssh and run commands, they take about 15-30 secs to execute every command. Every commands is executed very slow.
 But as soon as the command executes, then it performs normal funtion, (i mean does not slows down).
I have checked, CPU, RAM, IO, Network, everything is in normal condition. so what could be the issue?

A: Check swap memory(free -h) utilization.
If some processes consume high amounts of swap memory this may cause slowness of the system which in turn takes more time to execute commands.

A: Most modern OSs tend to cache as much as they can in RAM. The first time you run a command, it might take long to retrieve all information from disk. On subsequent attempts the data is already cached and things run much faster. A common scenario in which you expèrience this is on DB servers: a heavy SQL query can take long to execute, if you then run the query again the execution is immediate, as the data is already there.


text:
Q: Stopwatch iOS app w/ concurrent process bug This is my first post so I hope this is a valid question. I've searched the forums for an answer to this with no luck. Below is my code for a stopwatch app. Problem I am having is when the play button is clicked multiple times it is ticking multiple seconds at a time. How do I safely stop this from happening?
ViewController
import UIKit

class ViewController: UIViewController {
    // MARK: Properties

    @IBOutlet weak var timerLabel: UILabel!

    var timer = NSTimer()
    var time = 0

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    // MARK: Functions
    func increaseTimer() {
        time++
        let formattedTime = String(format:"%02d:%02d", (time/60), time%60)
        timerLabel.text = "\(formattedTime)"
    }

    // MARK: Actions
    @IBAction func btnPlay(sender: AnyObject) {
        timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self,
            selector: Selector("increaseTimer"), userInfo: nil, repeats: true)
    }

    @IBAction func btnStop(sender: AnyObject) {
        timer.invalidate()
    }

    @IBAction func btnReset(sender: AnyObject) {
        timer.invalidate()
        time = 0
        timerLabel.text = "00:00"
    }

}

EDIT: SOVED http://imgur.com/mqw1Xnp

A: Make your button into a start/stop button. Use a boolean instance variable to keep track of whether the timer is running or not. If it is, stop it. If it's not, start it.
Alternately, make the code that starts the timer set button.disabled = true


text:
Q: Call a function from an external script I have 2 scripts:
/home/bin/test.sh
#!/bin/bash
. /home/bin/test_functions.sh
test

/home/bin/test_functions.sh
#!/bin/sh
test()
{
    echo "this is a test"
}

I wanted to call the function from the external script and execute it in the main script. Yet I've been receiving these errors:
'home/bin/test_functions.sh: line 2: syntax error near unexpected token `
'home/bin/test_functions.sh: line 2: `test()

What could be wrong with what I'm doing?

A: It appears that test_functions.sh is in DOS format and bash is choking on the \r\n line endings. Use dos2unix to convert it to UNIX line endings.
You can tell because what bash is trying to output is this:
/home/bin/test_functions.sh: line 2: syntax error near unexpected token `\r'
/home/bin/test_functions.sh: line 2: `test()\r'

But the carriage returns \r cause the single quotes to end up at the beginning of the error messages, overwriting the leading /.


text:
Q: Compatibility of homomorphisms and quotient maps of abelian groups Suppose $A$ and $C$ are abelian groups with subgroups $A'$ and $C'$ respectively. Let $f:A\to C$ be a group homomorphism. I was wondering if the following statements are equivalent:

*

*There exists a homomorphism $g:A'\to C'$ such that $fi=jg.$

*There exists a homomorphism $h:A/A'\to C/C'$ such that $hp=qf.$

$$\begin{array}
AA' & \stackrel{i}{\longrightarrow} & A & \stackrel{p}{\longrightarrow} & A/A'\\
\downarrow{g} & & \downarrow{f} & & \downarrow{h} \\
C' & \stackrel{j}{\longrightarrow} & C  & \stackrel{q}{\longrightarrow} & C/C'
\end{array}
$$
where $i$ and $j$ are inclusions, and $p$ and $q$ are projections.
It seems to me that (1) means the restriction of $f$ to $A'$ is g, so to prove (1) implies (2), I define $h(a+A')=f(a)+g(A')$. But $g(A')\neq C'$ in general, and I'm confused about if I made the right definition.

A: Yes, these statements are equivalent, and you're approach is right. Note only that in order to describe an element of $C/C^{\prime}$, when the latter is realized by $C^{\prime}$-cosets in $C$, you have to put $h(a + A^{\prime}) := f(a) + C^{\prime}$. However, more conceptually you should try to prove the equivalence using universal properties of kernel and cokernel only - this has the advantage of directly generalizing to arbitrary abelian categories.

A: For (2) $\Rightarrow$ (1):
Take $a'\in A'$, we want to define an element in $C'$.  The only map available to use is $i:A'\to A$ which gets you to $A$.  As I mentioned in the comment, one way to get something in $C'$ is to get $[0]=0+C'\in C/C'$.  So we push our element $i(a')\in A$ to element in $C/C'$ there is only one way to do it: so you have $qfi(a')=hpi(a)\in C/C'$.
Note that $pi=0$, so $hpi(a)=q(fi(a))=[0]$.  Hence $fi(a)\in \ker(q)=\text{im}(j)$.  That is, there is some $c'\in C'$ such that $j(c')=fi(a)$.
If there is another $c''\in C'$ with $j(c'')=fi(a)$, then $j(c'')=j(c')$, but $j$ injective, so $c''=c'$.  Hence, the assignment $h:a'\mapsto c'$ is well-defined. In particular, you get (1).
(1) $\Rightarrow$ (2) is the "dual" argument; I will leave it to you to attempt again.
When you finished the exercise, it is perhaps good to have a look at "pullback and pushforward".  You can find them in most homological algebra textbook.


text:
Q: convergence of series $\sum_{n=1}^{\infty} a_n$ with $|a_n| \le \frac{n+1}{n^2}$ Let us consider series:
$$S=\sum_{n=1}^{\infty} a_n$$
$$a_n=\frac{n\cos(n)+\sin(n^2+2n-5)}{n^2}$$
The bounds for $a_n$ is shown in this MSE question to be:
$$|a_n| \le \frac{n+1}{n^2}$$
Is it possible to prove that this series is convergent?
Numerical results showed that
$$\sum_{n=1}^{10^5} a_n=-0.931506$$
$$\sum_{n=1}^{10^6} a_n=-0.931501$$
Here is a plot of Christian Blatter's bounds $\pm (n+1)/n^2$ and $a_n$:

From the plot the series, we can see that the terms are oscillating, but not like $(-1)^n |a_n| $. There seems to be some randomness in the number of terms to be positive and number of terms to be negative.

A: *

*$$|\frac{\sin(n^2+2n-5)}{n^2}|\leq\frac{1}{n^2}$$

*$\sum\frac{\cos n}{n}$ is convergent by using dirichlet test.


text:
Q: Javascript : do a second treatment when array filtering is complete I have to manipulate an array  by using two methods , one after the other :

*

*filter array

*then , sort it

my filter method is the following
  filterArray(list){
    return list.filter(item=> !this.myCondition(item));
  }

my sort method is the following :
sortArray(list) {
    return list.sort((a, b) =>
      new Date(b.beginDate).getTime() - new Date(a.beginDate).getTime()
    );
}

I want to control it, by the way, that its complete filtering and then do the sorting
I've tried this :
myData = myData.filterArray(myData).sortArray(myData);

But i'm not sure that it's the cleanest way
(Note : i want to keep sorting and filtering methods separated)
best ways to do it ?

A: Array.sort won't return a new sorted array. it will sort in-place which means that it will mutate the array. thus returning something from your sort function and storing it makes no sense. if you you want to prevent mutation of original array you should clone it on your sort function manually, then sorting it, then returning. to keep pure functions without side effects;
sortArray(list) {
    let listClone = list.slice(0); // some fast cloning method
    listClone.sort((a, b) =>
      new Date(b.beginDate).getTime() - new Date(a.beginDate).getTime()
    );
    return listClone
}

Since filter returns new array every time, your code works just fine; but if you use your sort function separately it will have side effects.

A:   myData = myData
  .filter(item => !this.myCondition(item))
  .sort((a, b) => new Date(b.beginDate).getTime() - new Date(a.beginDate).getTime());

Each line was assigned with different job.


text:
Q: Extract Numbers and Size Information (KB, MB, etc) from a String in Python I have a string like this
"44MB\n" (it can be anything ranging from 44mb, 44 MB, 44 kb, 44 B)

I want to separate 44 and MB from the above string. I have written this code to extract the number
import re
mystring = "44MB\n"
re.findall(r'\d+', mystring)

for extracting the size I want to avoid using if statements like
if "kb" mystring.lower():
    # Do stuffs
if .......

How can I extract the size info using regex

A: This script:
import re

test_string = '44.5MB\n12b\n6.5GB\n12pb'

regex = re.compile(r'(\d+(?:\.\d+)?)\s*([kmgtp]?b)', re.IGNORECASE)

order = ['b', 'kb', 'mb', 'gb', 'tb', 'pb']

for value, unit in regex.findall(test_string):
    print(int(float(value) * (1024**order.index(unit.lower()))))

Will print:
46661632
12
6979321856
13510798882111488

Which is the sizes it found in bytes.

A: The following regex should validate the size strings which you are trying to match:
my_string = "44MB\n"
match_Obj = re.match(r'^(\d*)\s?([kmKM][Bb])$', my_string)

print "size: ", match_Obj.group(1)
print "units: ", match_Obj.group(2)

Output:
size: 44
units: MB

Here is a link where you can test this regex:
Regex101

A: You could use a regex like the following to search for both size and unit (kb, mb)
re.compile(r"(?i)(?P<size>\d+)\s*(?P<unit>[km]?b)")

Trying it out:
>>> rgx = re.compile(r"(?i)(?P<size>\d+)\s*(?P<unit>[km]?b)")
>>> for x in ("44 mb", "44mb", "44kB"):
...     print(rgx.search(x).groups())
...
('44', 'mb')
('44', 'mb')
('44', 'kB')

For dealing with other prefixes, just alter the unit portion of the regex.
Its worth noting, since you say case doesn't matter, the "kb" is a valid symbol for kilobit, rather than kilobyte ...


text:
Q: Photos with pre-filled captions We recently got the follow message from FB:
It looks like your app, [Our App Name] may be posting photos with pre-filled captions. If that's the case, you'll want to remove any default photo captions within the next few days in order to avoid restrictions...
We are not using the "caption" field, but some of the photos shared do have embedded images in the image itself wich we have no control over.
We also post a url in the "message" field that link User to more info about that media.
It is confusing to us what FB is talking about.
Also, we are a mobile App, thus this kind of change will take some time to do and pass through Apple submission and release cycle.
Any help is appreciated.
here is a sample of our posts:
https://www.evernote.com/shard/s36/sh/9c5d091c-805e-4088-83b8-2d51f060a704/f06b36f9bddb1b200a4aaaa073eebc4c

A: We also post a url in the "message" field that link User to more info about that media.
This is what you need to stop doing, it's explicitly against policy


text:
Q: get blog page url in WordPress The blog page on my WordPress website is set to be a different page other than the home page. I want to get the link to this blog page from any other pages.
How can I get blog page url?

A: You can use get_option of page_for_posts to get the page ID to either assign it to a variable or to echo it.
<?php echo get_permalink( get_option( 'page_for_posts' ) ); ?>

For more information of the default get_option visit: Option Reference

A: $posts_page_url is the url to blog page and $posts_page_title is the page title
<?php
$posts_page_id = get_option( 'page_for_posts');
$posts_page = get_page( $posts_page_id);
$posts_page_title = $posts_page->post_title;
$posts_page_url = get_page_uri($posts_page_id  );
?>

More details refer the link - http://www.queness.com/code-snippet/7935/how-to-get-url-for-blog-page-when-using-static-homepage

A: Just call your url with this extention and all blog posts are displayed.
https://www.yourdomain.com/?post_type=post

A: If your blog url is https://www.yourdomain.com/blog, you can use:
echo site_url('/blog');

A: We can use get_post_type_archive_link since WordPress 4.5
get_post_type_archive_link( 'post' );

A: use this code:
<?php echo 'Our Blog'; ?>

A: To get the Blog URL you can use the below code.
get_permalink( get_option( 'page_for_posts' ) );

If you are using WordPress 4.5+ then you can use the below code which will work for any post type.
get_post_type_archive_link( 'post' );


text:
Q: When does weak* convergence characterize weak* closeness Consider a topological vector space $X$. Suppose $S$ is a subset of $X$. Under what condition, the following implication is true?
"If $\{s_n\}\subset S$ converges to $s\in X$, then $s\in S$. " $\Rightarrow$ "$S$ is closed."
I cannot find a rigorous reference for this.
In particular, consider the space of finite signed measure $\mathscr{M}(\Omega)$ equipped with weak* topology, where $\Omega$ is a compact subset of $\mathbb{R}^n$. Suppose $S\subset\mathscr{P}(\Omega)$ is a subset of probability measures. Suppose for every sequence $\{s_n\}\subset S$ that converges to some $s$, we have $s\in S$. Can we conclude $S$ is weak* closed?
Thank you!

A: The first part of the question has little to do with vector spaces:

A subset $A$ of a complete metric space $(X,d)$ is closed if and only if it is complete.

This is a standard exercise (solution in this question).
On (non-metrizable) topological spaces, say that $A$ is sequentially closed if it contains the limits of all its sequences.

Sequentially closed sets need not be closed

(see here for a standard counterexample)
Additionally,

The sequential closure of $A$, i.e. the set of all limit points of sequences in $A$, need not be sequentially closed

(see here).
Assuming that $X$ is additionally a topological vector space is not of any help:

there exist weakly sequentially closed subsets of a ($\infty$-dim) Hilbert space that are not weakly closed.

(see here).
Concerning the second part of the question, the answer is yes: we can conclude that $S$ is closed since $\mathscr P(\Omega)$ is metrizable.
This is a very particular case of the following fact. A topological space $(X,\tau)$ is Polish if there exists a distance $d$ metrizing $\tau$ and additionally such that $(X,d)$ is complete and separable. Endow $\mathscr P(X)$ with the weak topology (induced by the duality with the space $\mathcal C_b(X)$ of continuous bounded functions on $X$). Then

$(X,\tau)$ is Polish if and only if $\mathscr P(X)$ is Polish.

(see e.g. [A, Thm. 8.9.4])
In the case of $\Omega$ compact in $\mathbb R^n$, the weak topology on $\mathscr P(\Omega)$ coincides with the weak* topology since $\mathcal C_b(\Omega)=\mathcal C_c(\Omega)=\mathcal C(\Omega)$. As a consequence, since $\Omega$ is compact (hence complete and separable, thus Polish), $\mathscr{P}(\Omega)$ is Polish (in particular metrizable), and therefore the conclusion follows from the first part of the answer.
Trivia: if Analyst Alice writes "$\mathbb P(\Omega)$" Probabilist Peggy will read "1".
[A] Bogachev, V.I., Measure Theory, vol. II


text:
Q: lftp: where are bookmarks stored on debian jessie? Bookmarks are saved but I get an empty (new file) when I run bookmark edit inside lftp and I don't have any ~/.lftp/bookmarks file.
For information, I add bookmarks like this:
$ lftp sftp://username@mysitehost
$ password:
lftp> bookmark add mysite
lftp> exit

and then I can use the bookmark like this
$ lftp mysite
$ password:
lftp>

A: Despite running lftp as a regular user, I found that lftp actually stores the bookmarks in root's files (despite lftp> bookmark edit opening a blank file).
Check:
/root/.local/share/lftp/bookmarks

A: Nowadays the bookmarks are stored in the file ~/.local/share/lftp/bookmarks
You can still edit them with
lftp
bookmark edit


text:
Q: FacebookConnect returns AccessToken without an expiration date If I use native FB login on an iPhone, the returned AccessToken doesn't seem to have an expiration date, unlike the one I get using browser based (non-native) login. Is this by design? The reason I ask is that the Parse.com API requires a valid expiration date. For now, I just use today's date plus three years.

A: It does have that within the AccessToken class. See this example of usage in the Google login portion of the chat tutorial although it's applicable for Facebook too.


text:
Q: Collect data from multiple spreadsheets into one spreadsheet I have 184 audit sheets in one folder. I want to reference one cell in each of these sheets and bring them back in to one master spreadsheet.
I have a code that does the opposite that sends a value to each sheet in the folder and changes it to the value that I want. So in essence I want to do the opposite of the script below:
function getdata() {

 var files = DriveApp.getFolderById("1gbA2JI1DYNku7SQPaCq1Qk27hnbimPag").getFiles()
while (files.hasNext()) {
  var file = files.next();
  var shoot = SpreadsheetApp.openById(file.getId());

  var sourcesheet = SpreadsheetApp.getActive().getSheetByName("Jan");
  var sourcerange = sourcesheet.getRange('A3');
  var sourcevalues = sourcerange.getValues();

var destsheet = shoot.getSheetByName('Front Sheet');
var destrange = destsheet.getRange('B5');
destrange.setValues(sourcevalues);
 }

}

A: Your example code doesn't appear to match your explanation but I think I got the basic idea so I made up some of the needed details on my own. I included filenames, ids and 'A3' values.  You can choose to modify as needed.
function getdata(month) {
  var monthA=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
  var date=new Date();
  var mss=SpreadsheetApp.getActive();
  var ms=mss.getSheetByName("Master Sheet");
  var vObj={name:[],id:[],value:[]};
  var files = DriveApp.getFolderById("1gbA2JI1DYNku7SQPaCq1Qk27hnbimPag").getFilesByType(MimeType.GOOGLE_SHEETS);
  while (files.hasNext()) {
    var file = files.next();
    var fid=file.getId();
    var ss = SpreadsheetApp.openById(fid);
    var sh = ss.getSheetByName(monthA[date.getMonth()]);
    var rg = sh.getRange('A3');
    vObj.name.push(file.getName());
    vObj.id.push(fid);
    vObj.value.push(rg.getValue());
    vObj['month']=monthA[date.getMonth()];
  }
  vObj.id.splice(0,0,'ids');
  ms.appendRow(vObj.id);
  vObj.name.splice(0,0,vObj.month);
  ms.appendRow(vObj.name);
  vObj.value.splice(0,0,'values');
  ms.appendRow(vObj.value)
}


text:
Q: PLCrashReporter ios6 crash My iOS6 app is crashing when compiled and run in release mode, please see crash report below:
Incident Identifier: 0267EA79-BAAB-4559-90FB-9ED8C268EB19
CrashReporter Key:   7b2d29f7c42065db47d89a8b3ae1056cf45f7d95
Hardware Model:      iPhone5,2
Process:         Instant Santa [5814]
Path:            /var/mobile/Applications/B303BD19-177E-4DBB-A7C2-89BBF3331818/Instant Santa.app/Instant Santa
Identifier:      Instant Santa
Version:         ??? (???)
Code Type:       ARM (Native)
Parent Process:  launchd [1]

Date/Time:       2012-11-10 22:30:34.889 -0600
OS Version:      iOS 6.0.1 (10A525)
Report Version:  104

Exception Type:  EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Crashed Thread:  0

Last Exception Backtrace:
0   CoreFoundation                  0x3a6eb3e2 __exceptionPreprocess + 158
1   libobjc.A.dylib                 0x3974495e objc_exception_throw + 26
2   CoreFoundation                  0x3a6eb302 +[NSException raise:format:] + 102
3   Instant Santa                   0x001196aa -[PLCrashReporter enableCrashReporterAndReturnError:] + 82
4   Instant Santa                   0x000b1064 -[BWQuincyManager init] (BWQuincyManager.m:182)
5   Instant Santa                   0x000b0c00 __38+[BWQuincyManager sharedQuincyManager]_block_invoke_0 (BWQuincyManager.m:107)
6   libdispatch.dylib               0x334d35d6 _dispatch_client_callout + 18
7   libdispatch.dylib               0x334d4586 dispatch_once_f + 42
8   Instant Santa                   0x000b0bc0 +[BWQuincyManager sharedQuincyManager] (once.h:68)
9   Instant Santa                   0x0009f9a2 -[AppDelegate application:didFinishLaunchingWithOptions:] (AppDelegate.m:51)
10  UIKit                           0x33f5ba74 -[UIApplication _handleDelegateCallbacksWithOptions:isSuspended:restoreState:] + 248
11  UIKit                           0x33f5b5f8 -[UIApplication _callInitializationDelegatesForURL:payload:suspended:] + 1164
12  UIKit                           0x33f53806 -[UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:] + 694
13  UIKit                           0x33efbcea -[UIApplication handleEvent:withNewEvent:] + 1006
14  UIKit                           0x33efb778 -[UIApplication sendEvent:] + 68
15  UIKit                           0x33efb1ba _UIApplicationHandleEvent + 6194
16  GraphicsServices                0x3a78f5f2 _PurpleEventCallback + 586
17  GraphicsServices                0x3a78f222 PurpleEventCallback + 30
18  CoreFoundation                  0x3a6c03e2 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 30
19  CoreFoundation                  0x3a6c0386 __CFRunLoopDoSource1 + 134
20  CoreFoundation                  0x3a6bf20a __CFRunLoopRun + 1378
21  CoreFoundation                  0x3a632238 CFRunLoopRunSpecific + 352
22  CoreFoundation                  0x3a6320c4 CFRunLoopRunInMode + 100
23  UIKit                           0x33f52440 -[UIApplication _run] + 664
24  UIKit                           0x33f4f28c UIApplicationMain + 1116
25  Instant Santa                   0x0009f73e main (main.m:16)
26  Instant Santa                   0x0009f6f4 start + 36

Thread 0 name:  Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0   libsystem_kernel.dylib          0x3a455350 __pthread_kill + 8
1   libsystem_c.dylib               0x339edfb2 pthread_kill + 54
2   libsystem_c.dylib               0x33a2a366 abort + 90
3   Instant Santa                   0x00119912 uncaught_exception_handler + 22
4   CoreFoundation                  0x3a6eb6cc __handleUncaughtException + 624
5   libobjc.A.dylib                 0x39744a46 _objc_terminate() + 126
6   libc++abi.dylib                 0x33ae3118 safe_handler_caller(void (*)()) + 76
7   libc++abi.dylib                 0x33ae31b0 std::terminate() + 16
8   libc++abi.dylib                 0x33ae459a __cxa_throw + 118
9   libobjc.A.dylib                 0x3974499e objc_exception_throw + 90
10  CoreFoundation                  0x3a6eb302 +[NSException raise:format:] + 102
11  Instant Santa                   0x001196aa -[PLCrashReporter enableCrashReporterAndReturnError:] + 82
12  Instant Santa                   0x000b1064 -[BWQuincyManager init] (BWQuincyManager.m:182)
13  Instant Santa                   0x000b0c00 __38+[BWQuincyManager sharedQuincyManager]_block_invoke_0 (BWQuincyManager.m:107)
14  libdispatch.dylib               0x334d35d8 _dispatch_client_callout + 20
15  libdispatch.dylib               0x334d4586 dispatch_once_f + 42
16  Instant Santa                   0x000b0bc0 +[BWQuincyManager sharedQuincyManager] (once.h:68)
17  Instant Santa                   0x0009f9a2 -[AppDelegate application:didFinishLaunchingWithOptions:] (AppDelegate.m:51)
18  UIKit                           0x33f5ba74 -[UIApplication _handleDelegateCallbacksWithOptions:isSuspended:restoreState:] + 248
19  UIKit                           0x33f5b5f8 -[UIApplication _callInitializationDelegatesForURL:payload:suspended:] + 1164
20  UIKit                           0x33f53806 -[UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:] + 694
21  UIKit                           0x33efbcea -[UIApplication handleEvent:withNewEvent:] + 1006
22  UIKit                           0x33efb778 -[UIApplication sendEvent:] + 68
23  UIKit                           0x33efb1ba _UIApplicationHandleEvent + 6194
24  GraphicsServices                0x3a78f5f4 _PurpleEventCallback + 588
25  GraphicsServices                0x3a78f222 PurpleEventCallback + 30
26  CoreFoundation                  0x3a6c03e4 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 32
27  CoreFoundation                  0x3a6c0386 __CFRunLoopDoSource1 + 134
28  CoreFoundation                  0x3a6bf20a __CFRunLoopRun + 1378
29  CoreFoundation                  0x3a632238 CFRunLoopRunSpecific + 352
30  CoreFoundation                  0x3a6320c4 CFRunLoopRunInMode + 100
31  UIKit                           0x33f52440 -[UIApplication _run] + 664
32  UIKit                           0x33f4f28c UIApplicationMain + 1116
33  Instant Santa                   0x0009f73e main (main.m:16)
34  Instant Santa                   0x0009f6f4 start + 36

Any help would be appreciated!

A: This happens if PLCrashReporter is already initialized before QuincyKit initializes it. Are you initializing PLCrashReporter yourself or is there any other framework installed that uses PLCrashReporter?
This is the exception that is being raised and causes the crash: https://github.com/bitstadium/PLCrashReporter/blob/master/Source/PLCrashReporter.m#L296

A: Nevermind, you don't need CrashReporter.framework with the new HockeySDK, see here: http://support.hockeyapp.net/kb/client-integration/migrate-from-hockeykit-quincykit-to-hockeysdk-for-ios


text:
Q: How can you detect wether any music is playing in Phaser? In my game, I want to play music sometimes. But music that is already playing shouldn't be overridden.
So how can I

*

*Check if music is playing

*Manage that sound

Ideally in an global interface like this.sound
Thanks in advance

A: HTML5AudioSound has isPlaying member.
// inside scene method, create sound
const music = this.sound.add('music-name', {});
music.play();

// and later
if(music.isPlaying) {

}

See
https://newdocs.phaser.io/docs/3.54.0/Phaser.Sound.HTML5AudioSound#isPlaying
and
https://newdocs.phaser.io/docs/3.52.0/Phaser.Sound.HTML5AudioSoundManager
(this.sound is HTML5AudioSoundManager instance)


text:
Q: Interface implementation that needs initiliazation I would like to extract an interface of a class that needs initilization.
public class Example<T>
{
    public Example(SomeData data)
    {
        // initialize self with data
    }

    public IEnumerable<T> GetObjects(SomeData data)
    {
        // extract data
    }
}

The problem is that we can't write an interface that would enforce non-default type constructors. I could of course change my class to:
public interface IExample<T>
{
    void Initilize(SomeData data);
    IEnumerable<T> GetObjects(SomeData data);
}

public class Example<T> : IExample<T>
{
    public void Initilize(SomeData data)
    {
        // initialize self with data
    }

    public IEnumerable<T> GetObjects(SomeData data)
    {
        // extract data
    }
}

But this is not the same, because when one would instantiate this type could directly call into GetObjects which would then result in an exception that instance is not initilized.
What other options do I have?

A: As this is just an interface, you shouldn't care about the constructor.  The interface defines what the implementations can do but not specifically how they do it or what order methods are called in.
How can you realistically say that in the future there won't be some implementation of the interface that works differently and doesn't require the constructor?

A: You don't.  The constructor arguments are an implementation detail of the class- they are irrelevant to the interface unless you decide to make GetObjects a read/write property.
Somewhere you are constructing a concrete instance, and you already know about the class itself there, so you know that you need to pass certain constructor arguments.
If you really want to enforce this idea that "All IExamples must be constructed with some arguments" externally, use a Factory pattern:
public static class ExampleFactory {
    public static IExample<T> MakeAnExample(SomeData data) {
        // return some concrete implementation...
    }
}


text:
Q: Ada + Fixed Stringss + Stm32 Arm How to create a simple function returns a string on a arm platform?
procedure Main is
   function tst_func return String is
   begin
      return "string";
   end tst_func;
   str : String := tst_func;  --  <-- Doesnt work, runtime error.
                                -- Adacore gpl compiller, crossdev, arm elf hosted of win os.
                                -- Hardware is smt32f407 discovery board.
begin
...

A: The issue here seems to be that using Ada on small embedded CPUs like the STm32 (ARM Cortex)  or the Actel AVR or TI MSP430 often involves compromises, because the platform may not be capable of running a full Ada RTS (Runtime System) including things like tasking.
Instead, a minimal RTS may be supplied, with restrictions specified by pragmas, that doesn't support tasking, or in this case, features requiring the secondary stack. Funnily enough, the RTS for the AVR does include the files s-secsta.ads,.adb which implement package System.Secondary_Stack so the much more powerful STm32 ought to be capable of it. You could look at the RTS sources supplied with the Adacore GPL package to see if these files are present or not.
So - options.
1) Work around, either using fixed length strings, or a table of string constants, or returning an  access String (i.e. pointer) to a string allocated on the heap (don't forget to free it!) though heap use is not normally recommended for embedded programming.
2) Find a better RTS. You can compile and link against a different RTS by supplying -RTS=... arguments to the compiler. Here is a thread discussing alternative RTS strategies for this CPU.

A: The problem is a bug in the runtime system: if your program doesn't involve any tasking, the environment task's secondary stack isn't set up properly, so when your function tries to return a string it thinks the secondary stack has been exhausted and raises Storage_Error.
I have reported this to AdaCore: their recommendation was to include
delay until Ada.Real_Time.Clock;

in your main program.
The bug will likely be resolved in the next GNAT GPL release.


text:
Q: Django Filter by Multiple Foreign Key Properties So I have Django models which look like the following:
class Test(models.Model):
    cool_prop = models.CharField()

class Metadata(models.Model):
     key = models.CharField()
     value = models.CharField()
     test = models.ForeignKey(Test)

and I would like to be able to filter tests based on if they contain a key:value pair based on this metadata. Essentially, I would like to be able to do:
tests = Test.objects.all().filter(metadata__key=key and metadata__value=value)

But I'm unsure how to perform this in Django. I've looked into F and Q statements. It seems as though most Django operations would allow any tests that has ANY metadata with said key and ANY metadata with said value. But I need the tests where 1 metadata matches in both key and value.

A: If you are testing only 1 set, it is just a simple:
tests = Test.objects.filter(metadata__key=key, metadata__value=value)

If you want to match a bunch of key-value pairs,
#Assuming that the keyvalue pairs is in a dictionary,
import operator
from django.db.models import Q

k_v_pairs = (Q(metadata__key=key, metadata__value=value) for key, value in k_v_dictionary)
tests = Test.objects.filter(reduce(operator.or_, k_v_pairs)).distinct()

Basically, it is the equivalent of saying get me the queryset of Test which have any of the following key value pairs.

A: You can do a subquery for matching metadata objects:
metadata = Metadata.objects.filter(key=key, value=value)
tests = Test.objects.filter(metadata__in=metadata).distinct()


text:
Q: How would I make setInterval pause the for loop it is in? http://jsfiddle.net/xDWLQ/
JavaScript:
var quotes = new Array();
quotes[0] = "message 0";
quotes[1] = "message 1";

var qText = document.getElementById('qText');
for (i = 0; i < quotes.length; i++) {
    setInterval(function() { qText.innerHTML = quotes[i]; }, 2000);
}

HTML:

Predefined text

The innerHTML of qText changes to undefined, instead of changing into quotes[0], followed by quotes1. Now I tried debugging it by using alert() inside the setInterval function to give me the index of the for loop, and it said "2" both times. So, how would I have the for loop paused instead of setInterval creating new threads and incrementing the index?

A: You'll need a completely different approach:
var quotes = ["message 0", "message 1"];
var qText = document.getElementById('qText');
var i = 0;

var update = function() {
    qText.innerHTML = quotes[i++ % quotes.length];
};

update();
setInterval(update, 2000);

A: I think this is you want, not a loop.
var quotes = ["message 0", "message 1"];
var qText = document.getElementById('qText');
var i = 0;
var len = quotes.length;

setInterval(function() {
   qText.innerHTML = quotes[i++];
   if (i === len) i = 0;
}, 2000);

A: You can enforce correct variable to be passed to the function by calling setInterval with a list of parameters passable to the function (tested on your jsfiddle)
setInterval(function(q) { qText.innerHTML = q; }, 2000, quotes[i]);

A: setInterval is already creating a loop, all its iterations will run after each n milliseconds, in your case 2000. If you are calling setInterval in a loop then its content will run in every n milliseconds i times. You just have to call it once. Note that Javascript is not multithreaded in browsers.


text: Q: Any online step by step toolcalculator for verifing logical equivalence without truth table? Anyone to help me please, I really need to verify logical equivalence without truth table but I can not find any online free tool which I can see step by step the solutions that includes the laws of logical equivalences?


text:
Q: Live KML from PostGIS to Google Earth Is there a way to bring data from a PostGIS database into Google Earth to view live?
I know of the asKml function in PostGIS, but I'm interested to know if it's possible to dynamically load KML-formatted data from PostGIS into Google Earth.

A: This can be done by creating a Network Link KML, with the <refreshInterval> and <viewRefreshMode> (reference) settings set appropriately. As listed in the example, you'll need a script which returns the new response, in this case by sending the query down to PostGIS to respond with an updated asKml result.

A: The asKML function only returns the geometry in KML format - not the entire response. You will still need to write some sort of web service to create valid KML to return to the client.
It is not hard to do but you will need to write out all the XML required in the KML document. The nice part of the asKML function is you don't have to write all that tedious geometry xml tags.
Once you write the service then you can point google-earth at the URL for the service.

A: You can do it with GeoServer. Installing and "linking" Geoserver to Postgres/PostGIS database is quite easy.
KML KMZ Output

A: You can try FME Desktop or FME Server from Safe Software. If you are using FME Desktop you can schedule the translation from PostGIS to KML. The KML can be pushed to a FTP or a dropbox account directly by FME, so that everytime you have new data in PostGIS, the KML also gets re-written.Read more about dropbox and FME at evangelism.safe.com/fmeevangelist52/
For some idea on FME Server and realtime KML look at this link:
http://www.fmepedia.com/index.php/Real-time_Taxi_Cabs_(KML_Network_Link_Example)


text:
Q: Change elfinder root by user My problem is almost like that of http://elrte.org/redmine/boards/2/topics/734?r=3250 which didn't get any solution.
I am using elfinder on my wordpress site in which on every user register I create a folder under the files directory on username and when that user comes to the interface where elfinder shows I want elfinder to show that user his user's folder as the root directory instead of the actual root set.
I found out through code that the root directory is set in connectors/php/connector.php file that passes it to elFinder.class.php file
I even found out a way to do that hardcoded... which is if you go into elFinder.class.php file and append the username with root in __contruct function everything works fine
public function __construct($options=array()) {
        foreach ($this->_options as $k=>$v) {
            if (isset($options[$k])) {
                $this->_options[$k] = is_array($this->_options[$k])
                    ? array_merge($this->_options[$k], $options[$k])
                    : $options[$k];
            }
        }
if (substr($this->_options['root'], 1) == DIRECTORY_SEPARATOR) {
            $this>_options['root'] = substr($this->_options['root'], 0, 1);
        } $this>_options['root'] .= 'username';

But the problem is that I am unable to find a way through which I can access username in elFinder way... It feels like there will be some simple way that my mind just ain't clicking to.. any help in this regard will be greatly appreciate.
Even if I can't access username in this function and somehow pass the username to this function or connector.php which calls its construct???

A: Modifying elFinder.class.php is a wrong way, what you need is to get your WordPress instance inside connector.php and generate correct root option for current user, the username/path you should get from WordPress.


text:
Q: VueJS Store pattern with get & set I have a small store (following the state pattern on VueJS (not VUEX)).
It essentially looks like this
export default {
    get selectedPartner() {
        return localStorage.getItem('selectedPartner');
    },

    set selectedPartner(item) {

        localStorage.setItem('selectedPartner', item);
    },

    clearFilters() {
        localStorage.removeItem('selectedPartner');
    }
}

In my .vue component I am now trying to bind to it like so
    data: function() {
      return {
        // Other stuff here...
        selectedPartner: filterStore.selectedPartner,
      }
    },

Now, when it draws the component, the getter is actually properly called.
When i change the value in the component, it does not update the store...
I do realise that doing it like this (in localStorage) is awfully close to VUEX.
But chose for this approach to grasp state in its most simple form first, before getting into VUEX.
Many thanks

A: Use computed instead of data:
computed: {
  selectedPartner: {
    get() { return filterStore.selectedPartner; },
    set(item) { filterStore.selectedPartner = item; }
  }
}


text:
Q: delete node in binary search tree python The code below is my implement for my binary search tree, and I want to implement delete method to remove the node. Below is my implementation, but when I perform
bst = BSTRee()
bst.insert(5)
bst.insert(11)
bst.insert(3)
bst.insert(4)
bst.insert(12)
bst.insert(2)
bst.delete(3)

when I call delete method, it did nothing. Can someone help me to fix it. The link below is my code on github. Thank you so much for your help.
https://github.com/hly189/sort/blob/master/tree/BST.py
class BSTreeNode
    def ____init__(self, value):
        self.value = value
        self.left = None
        self.right = None

   def insert(self,key):
        if self.value == key:
            print ("the node already exists")
            return False
        elif self.value > key:
            if self.left is not None:
               return self.left.insert(key)
            else:
               self.left = BSTreeNode(key)
               return True
        else:
             if self.right is not None:
               return self.right.insert(key)
            else:
               self.right = BSTreeNode(key)
               return False

    def delete(self, node, k):
            if node == None:
               return None
            elif node.value == k:
               if node.left is None and node.right is None:
               return None
            elif node.left is None:
                return node.right
            elif node.right is None:
                return node.left
            else:
                node.value = get_min(node.right)
                node.right.delete(node.right,node.value)
            elif k < node.value:
                node.left.delete(node.left,k)
            else:
                node.right.delete(node.right,k)
            return node

class BSTree:
    def __init__(self):
           self.root = None

    def delete(self,key):
           self.root.delete(self.root,key)

    def insert(self,data):
           if self.root:
               self.root.insert(data)
           else:
               self.root = BSTreeNode(data)
               return True
    def find_min(self,node):
           current_node = node
           while current_node.left:
               current_node = current_node.left
           return current_node

def get_min(node):
    current_node = node
    while current_node.left:
        current_node = current_node.left
    return str(current_node.value)

def print_helper(root, indent):
    if root is not None:
        print_helper(root.right, indent + "   ")
        print (indent + str(root.value))
        print_helper(root.left, indent + "   ")

def print_tree(root):
     print_helper(root, "")

A: def delete(self, key):
    """ delete the node with the given key and return the
    root node of the tree """

    if self.key == key:
        # found the node we need to delete

        if self.right and self.left:

            # get the successor node and its parent
            [psucc, succ] = self.right._findMin(self)

            # splice out the successor
            # (we need the parent to do this)

            if psucc.left == succ:
                psucc.left = succ.right
            else:
                psucc.right = succ.right

            # reset the left and right children of the successor

            succ.left = self.left
            succ.right = self.right

            return succ

        else:
            # "easier" case
            if self.left:
                return self.left    # promote the left subtree
            else:
                return self.right   # promote the right subtree
    else:
        if self.key > key:          # key should be in the left subtree
            if self.left:
                self.left = self.left.delete(key)
            # else the key is not in the tree

        else:                       # key should be in the right subtree
            if self.right:
                self.right = self.right.delete(key)

    return self

def _findMin(self, parent):
    """ return the minimum node in the current tree and its parent """

    # we use an ugly trick: the parent node is passed in as an argument
    # so that eventually when the leftmost child is reached, the
    # call can return both the parent to the successor and the successor

    if self.left:
        return self.left._findMin(self)
    else:
        return [parent, self]

This might help. For complete code and better understanding go to
For code
Binary search Tree in Python
For explanation
Notes on BST in Python
As per my knowledge its working fine.


text:
Q: How to include JavaScript file in Liferay Portlet? I am not able to include http://maps.googleapis.com/maps/api/js?sensor=false. Whenever I load my portlet for the first time it doesn't work but if I refresh the same page then it starts working fine. I don't know what the issue is. Please Help.

A: One of the clean ways to include js file in a portlet, independent of the portal server is to configure in portlet deployment descriptor file as below. For liferay, it would be liferay-portlet.xml.
<portlet>
    <portlet-name>MySamplePortlet</portlet-name>
    <header-portlet-javascript>http://maps.googleapis.com/maps/api/js?sensor=false</header-portlet-javascript>
</portlet>