text:
Q: event.bytesTotal returning 0 in ProgressEvent.PROGRESS I am getting the result for event.bytesTotal = 0 in some of the mp3 file when i am loading it from ftp server.But
when loading the same file from local server, the call to event.bytesTotal is working well - giving the expected result.
Here is my code :
 public function LoadedBytes()
        {
            var byteLoader:URLLoader = new URLLoader();
            byteLoader.dataFormat = URLLoaderDataFormat.BINARY;

            var fileRequest:URLRequest = new URLRequest();

            myFile =new File();
            myFile=File.desktopDirectory;
            myFileStream = new FileStream();

            fileRequest.url="http://minhajproductions.in/irfanulquran/Al-Fatihah/4.mp3";

            myFile=File.desktopDirectory;
            myFile=myFile.resolvePath("sound/4.mp3");

            try{
                byteLoader.addEventListener(ProgressEvent.PROGRESS,onProgress);
                byteLoader.load(fileRequest);
            }catch(e:IOError){
                trace("unable to load requested sound")
            }

        }

        protected function onProgress(event:ProgressEvent):void
        {
            trace(event.bytesLoaded,event.bytesTotal," length");
            //progressCB((event.bytesLoaded/event.bytesTotal));

        }

why this weird thing is happening?
        Thanks in advance.

A: My problem was the missing Content-Length header on my server side. Flash use it to be able to find the download progression.

A: I think there is problem at your end. Try running the same program from some other place.
I found one post event-bytestotal-returns-0
Check the first answer in which Chunked_transfer_encoding link is given for more info.


text:
Q: Composer requirements could not be resolved I'm trying to update my composer dependencies and composer can't resolve my requirements. I've tried updating rezzza/formulate and hoa/math, but I always get this error:
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

Problem 1
- rezzza/formulate v1.0.2 requires hoa/math dev-master -> satisfiable by hoa/math[dev-master].
- rezzza/formulate v1.0.2 requires hoa/math dev-master -> satisfiable by hoa/math[dev-master].
- Removal request for hoa/math == 9999999-dev
- Installation request for rezzza/formulate == 1.0.2.0 -> satisfiable by rezzza/formulate[v1.0.2].

Here is my Composer config:
"require": {
    "bernard/bernard": "~0.11",
    "bshaffer/oauth2-server-php": "v1.5",
    "doctrine/annotations": "~1.1",
    "doctrine/cache": "~1.3",
    "doctrine/collections": "v1.1",
    "goodby/csv": "dev-master",
    "guzzle/guzzle": "~3.7",
    "herrera-io/date-interval": "~1.0",
    "jms/serializer": "~0.13",
    "kriswallsmith/buzz": "0.12",
    "lexpress/doctrine1": "1.3.0",
    "lexpress/symfony1": "1.5.3",
    "merk/dough": "~1.1.4",
    "misd/guzzle-bundle": "~1.0",
    "monolog/monolog": "~1.7.0",
    "namshi/notificator": "~1.0",
    "parse/php-sdk": "~1.0.4",
    "predis/predis": "dev-master",
    "raven/raven": "~0.7.0",
    "rezzza/formulate": "~1.0",
    "symfony/console": "~2.4",
    "symfony/security": "~2.5",
    "symfony/templating": "~2.4",
    "symfony/twig-bridge": "~2.4",
    "symfony/validator": "~2.4",
    "twig/twig": "1.*",
    "willdurand/hateoas": "~2.1",
    "willdurand/negotiation": "~1.2",
    "yohang/finite": "~1.0",
    "yzalis/ua-parser": "dev-browserscope-yml-support"
},
"require-dev": {
    "phpunit/phpunit": "4.1.*"
},
"prefer-stable": true,
"autoload": {
    "psr-4": {
        "": "src/"
    }
}

It seems that the removal request is what's tripping me up, but I'm not even sure what that means. I also see two different version formats for the rezzza/formulate library: 1.0.2 and 1.0.2.0 -- maybe that's also an issue?

A: I ran composer update rezzza/formulate, which solved my installation requirements problem.

redpajama_set_name: RedPajamaStackExchange


text:
Q: that running boy a. Stop that running boy!
b. Stop that boy running!
You see a young boy running towards a street and you think he is going to try and cross it and put his life in danger. You shout to other people to stop the kid before it is too late.
Which of the sentences is grammatically correct?
Which is natural?

A: Both are grammatically correct. In (a), running identifies the boy, in (b) it identifies the action you want to put a stop to.
In real life, with a busy road nearby I think the situation would be obvious to bystanders and you would only need to shout "Stop that boy!" If you must include running, possibly (b) is more likely (but that's opinion-based.)


text:
Q: "mount: RPC: Timed out" when attempting to mount NFS filesystem Following a reboot of an NFS server, client machines are unable to mount it, returning the message"mount: RPC: Timed out"

*

*I've ruled out iptables rules by clearing them

*/etc/exports on the server is unchanged

*rpcinfo -p from the client to the server looks OK:

    program vers proto   port
    100000    2   tcp    111  portmapper
    100000    2   udp    111  portmapper
    100003    2   udp   2049  nfs
    100003    3   udp   2049  nfs
    100003    2   tcp   2049  nfs
    100003    3   tcp   2049  nfs
    100021    1   udp  32791  nlockmgr
    100021    3   udp  32791  nlockmgr
    100021    4   udp  32791  nlockmgr
    100021    1   tcp  32768  nlockmgr
    100021    3   tcp  32768  nlockmgr
    100021    4   tcp  32768  nlockmgr
    100005    1   udp    618  mountd
    100005    1   tcp    621  mountd
    100005    2   udp    618  mountd
    100005    2   tcp    621  mountd
    100005    3   udp    618  mountd
    100005    3   tcp    621  mountd
    100024    1   udp  32765  status
    100024    1   tcp  32765  status

Advice for further diagnostics much appreciated!

A: I resolved this by restarting some of the client side components with
/etc/init.d/nfs-common restart

I was then able to mount the filesystem just fine. Phew ;)

A: You need to make sure that both the client and the server have a working portmap service, visible from the client. It's possible that you don't have a working portmap on the client.


text:
Q: stopping weblogic server 8.1 from console I am using weblogic server 8.1 with MyEclipse and started the command propmt with "startweblogic" command.
I can't post image due to less reputation so I'm just writing the command like I wrote on my console:
E:\JLC\bea8\user_projects\domains\MyDomain>startweblogic
and my server is started after this.
now instead of just closing the window, I want to stop the server properly, but I don't know how to do it. It seems that I can't type anything in the console. So please someone tell me how to stop the server properly??

A: Maybe pressing Ctrl+C in the console...but closing windows console is well too.
If you want to keep opened your cmd, first open a new cmd, navigate to the weblogic bat file, start server and then press Ctrl+C to stop server. Doing that, you could start server again pressing key up and enter.
(sorry for my bad english)


text:
Q: Can you manually push notifications with appMobi's framework without having to use the admin panel? I am developing a hybrid mobile application with appMobi. So far everything is very promising. From my understanding though it appears that you have to use the admin panel to send push notifications. Is there anyway to manually do this where I can create the mobile applications for clients, and not have to worry about having them signed up with appMobi for the application to function? Essentially I want to pull data from a website, and upon the date of the event execute a push notification that lets the user know an event is going on that day.
Any thoughts or suggestions? I am very new to appMobi's framework, and chose it over Phonegap since I don't have an apple based computer.

A: You certainly can!  Please check out the web service documentation for push messages http://www.appmobi.com/documentation/pushMobi.html


text:
Q: How to store data in a matrix I have a simple question: I created a function called se.bootstrap that receives elements from two vectors:
bs <- c(10, 25, 200, 500, 5000)
sample.size <- c(5, 10, 200, 2000)

I am trying to pass all the possible combinations of the elements of these two vectors to this function and store the results in a matrix, such as:
      10                 25        200         500          5000
5     sd.boostrap(5, 10)
10
200
2000                                                       sd.boostrap(2000, 5000)

Could anyone help with that?
Thank you very much

A: se.bootstrap  <- function(a,b) ( a*b)  # use whatever function on 2 variables
bs <- c(10, 25, 200, 500, 5000)    # your vectors
sample.size <- c(5, 10, 200, 2000) # your vectors
res  <- matrix(se.bootstrap(expand.grid(bs,sample.size)$Var1,expand.grid(bs,sample.size)$Var2),nrow = length(bs),ncol = length(sample.size))

expand.grid does what you want and returns Var1 and Var2 which goes to the function defined.
the matrix() makes the vector a matrix having the dimensions of the vectors (you can switch cols=>rows)
res
      [,1]  [,2]  [,3]  [,4]
[1,]    50   100 2e+03 2e+04
[2,]   125   250 5e+03 5e+04
[3,]  1000  2000 4e+04 4e+05
[4,]  2500  5000 1e+05 1e+06
[5,] 25000 50000 1e+06 1e+07

A: Assuming se.bootstrap returns a scalar, you can:
# function that returns a scalar
sd.fake <- function(bs, ss) bs*ss

# we prepare the matrix
res <- matrix(nr=length(sample.size), nc=length(bs), dimnames=list(sample.size, bs))

# we loop and fill the matrix
for (i in seq_along(sample.size))
  for (j in seq_along(bs))
    res[i, j] <- sd.fake(sample.size[i], bs[j])

> res
10    25   200     500    5000
5       50   125 1e+03    2500 2.5e+04
10     100   250 2e+03    5000 5.0e+04
200   2000  5000 4e+04  100000 1.0e+06
2000 20000 50000 4e+05 1000000 1.0e+07

Is this what you want? expand.grid may help as well.


text:
Q: Не отображается элемент :before при загрузке на хостинг         При локальной работе с файлами все отображается корректно, но стоит только загрузить на хостинг, и все ломается, а именно, пропадает элемент :before

Локально
а вот при уже непосредственно на сайте

далее код в html

Партнеры

YTONG

Газобетонный блок YTONG производится из натуральных компонентов и во всем мире признаны экологическим чистым, нетоксичным строительным материалом.

Bonolit

Bonolit крупнейший завод по выпуску современного, экологичного и качественного стенового материала для строительства малоэтажного и многоэтажного жилья.

Пластблок

Лучший производитель строительных материалов из полистиролбетона в России. Изделия, производимые заводом Пластблок, обладают уникальными характеристиками: энергоэффективность, прочность и долговечность.

Wienerberger

Крупноформатные керамические блоки Porotherm производятся австрийским концерном Wienerberger. Это теплые и очень прочные изделия с повышенным сопротивлением к сжатию и устойчивостью к воздействию высоких температур. Они не боятся морозов и перепадов температур, не содержат вредных веществ и токсичных добавок.

Гжельский кирпичный завод

Гжель предлагает широкий ассортимент кирпичей разных размеров и цветов. Вы можете использовать этот строительный материал как для возведения стен, так и для облицовки. В качестве используется экологически чистая глина из Гжельского месторождения, которая обла-дает уникальными физическими свойствами.

И css
  .partners__img {
position: relative;}
.partners__promt-1 {
  position: absolute;
  bottom: -90px;
  left: -50px;
  width: 300px;
  min-height: 210px;
  background: #fff;
  padding: 22px;
  -webkit-box-shadow: 0px 24px 64px rgba(0, 0, 0, 0.12);
  box-shadow: 0px 24px 64px rgba(0, 0, 0, 0.12);
  border-radius: 24px;
  opacity: 0;
  transition: all 0.6s ease;
  text-align:initial;
  z-index: 2; }
.partners__promt-1:before {
  content: "";
  width: 100%;
  height: 100%;
  position: absolute;
  bottom: 0;
  left: 0; }
.partners__promt-1 h4 {
  font-size: 22px;
  margin-bottom: 8px; }
.partners__promt-1 p {
  font-size: 16px;
  line-height: 22px; }
.partners__promt-1:hover {
  opacity: 1; }
.partners__flex2 .partners__img .partners__promt-1 {
  bottom: -190px;
}


text:
Q: How to `du` only the space used up by files that are not hardlinked elsewhere? Using rsync --link-dest for space-saving snapshots, how can I figure out how much space I actually saved? Or more general:

How to figure out how much space a directory uses considering only files that are not hardlinked elsewhere outside the directory structure? Asked differently: How much space would actually be freed after a deletion of that directory? (du -hs would lie. The space required for the hardlinks themselves may be included)

A: Basically, you need to get the inode numbers and number of links for all the files (non-directories), compare that number of link with the number of occurrence of each inode, and if they differ, exclude the file.
Assuming, they're all on the same filesystem, something like this should work (with GNU find):
find . -type d -printf '%k\n' -o -printf '%i %n %k\n' |
   awk '
     NF==1{t+=$0; next}
     {n1[$1]=$2; n2[$1]++; s[$1]=$3}
     END {
       for (i in n1)
         if (n1[i] == n2[i])
           t+=s[i]
       print t
     }'

A: du actualy won't lie ;) It parses the dir(s) one gives it, counting only the first of all hardlinks pointing to the same inode it encounters.
If you ask du what it sees in one directory only, it does not care that there are other hard links pointing to the same contents:
$ du -h daily.0 && du -hc daily.1
29G /daily.0
29G /daily.1

Now give it dirs on the same row (starting with the most recent one for rsync incremental backups with --link-dest):
$ du -hc daily.0 daily.1
29G /daily.0
364M /daily.1
29G total

Or the whole backup dir:
$ du -hc --max-depth=1 /snapshots
29G /daily.0
364M /daily.1
537M /daily.2
333M /daily.3
30G total

Any file in 'daily.1' referencing an inode (aka "real" file) already referenced in 'daily.0' will not be counted.
Therefore deleting daily.1 will save 364MB on your device.
REMOVE

A: Assuming there aren't internal hardlinks (that is, every file with more than 1 hardlink is linked from outside the tree), you can do:
find . -links -2 -print0 | du -c --files0-from=-

EDIT And here is what I sketched in the comment, applied. Only without du; kudos to @StephaneChazelas for noticing du is not necessary. Explanation at the end.
( find . -type d -printf '%k + ' ; \
  find . \! -type d -printf '%n\t%i\t%k\n' | \
    sort | uniq -c                         | \
    awk '$1 >= $2 { print $4 " +\\" }' ; \
  echo 0 ) | bc

What we do is to create a string with the disk usage (in KB) of every relevant file, separated by plus signs. Then we feed that big addition to bc.
The first find invocation does that for directories.
The second find prints link count, inode, and disk usage. We pass that list through sort | uniq -c to get a list of (number of appearances in the tree, link count, inode, disk usage).
We pass that list through awk, and, if the first field (# of appearances) is greater than or equal the second (# of hardlinks), meaning there aren't links to this file from outside the tree, then print the fourth field (disk usage) with a plus sign and a backslash attached.
Finally we output a 0, so the formula is syntactically correct (it would en in + otherwise) and pass it to bc. Phew.
(But I would use the simpler first method, if it gives a good enough answer.)


text:
Q: Разграничение доступа к записям в одной БД (таблице) Есть БД с набором таблиц, записи в которые создаются разными пользователями. Возможно ли реализовать доступ к данным так, чтобы каждый пользователь имел доступ (в том числе на чтение), только к тем записям, которые он сам создал. Если да, то как это лучше реализовать?  Можно ли это сделать средствами JAVA?
Речь идет о СУБД H2 и MySQL.

A: создать отдельную таблицу только с users ,  если у каждого будет что то уникальное и если у таблицы будет что то уникальное , что соответствует этим двум уникальностям ...  далее > каждый юзер может создавать таблицы как вам надо, но при создании будет стоять дэфолтное значение какой - то уникальности .. например создает первый юзер таблицу1 - дэфолтная уникальность 1 и заносится в таблицу1 .. если происходит редактирование какой то из таблиц , если соответствует тот уникальный ключ (который был задан для каждого пользователя) уникальному ключу этой таблице, если да - то редактируй , если нет то нет ..


text:
Q: How to Format Pivot Table Months in Mon-Yr format I would like to change the format of my dates to Mon-Yr.
My Graph

My Table has the format I want:

Thank you.

A: Right click on the axis, select format axis and scroll to number. Enter the Format Code mmm-yy and click add.

A: I used DATE(M2,L2,1) M2= month column L2 = year column


text: Q: First Betti number of finitely non-co-hopfian groups Let $G$ be a finitely generated group.  Assume that $G$ is a finitely non-co-hopfian group in the sense that there is a group embedding $i: G\hookrightarrow G$ such that $1<[G\colon i(G)]<\infty$, is the first Betti number $b_1(G)$ always positive, i.e., the free part of the abelianization of $G$ has positive rank?


text:
Q: Search: Primary and Replica Index not the same size? I have a question regarding size of index partition. My Search Application Topology looks like that:

Checking the status of my SSA shows everything in Active State, nothing degraded.

But the Size of the index is different. Does anybody know, why? Here's a screenshot of Primary and Replica Index Content/Size of both WFE Servers. Each Folder "SPSearchService" contain the subfolders "PrimaryIndex" and "ReplicaIndex".

I thought the index on both servers have to be the same size?
Edit: I generated a report for a full overview:

A: I do not know what caused this issue (once I was out of disk space, maybe this caused the fail in merging the index), but I could fix it.
First I did an Index Reset (in Search Administration) and checked, if the index files on my servers are deleted. Then I started full crawling on every content source I have.
Now the ratio of my index components looks much healthier:
-----------------------------------------
[ SharePoint Search Service Application ]
-----------------------------------------

Host     State  Name            CellName Partition Primary Generation ActiveDocs Merging CheckpointSize
----     -----  ----            -------- --------- ------- ---------- ---------- ------- --------------
xxxxx059 Active IndexComponent5 [I.0.0]          0    True       5264    1516121   False 34423 (MB)
xxxxx154 Active IndexComponent7 [I.1.0]          0   False       5264    1516121   False 34458.7 (MB)
xxxxx059 Active IndexComponent6 [I.0.1]          1    True       5264    1515190   False 34297.3 (MB)
xxxxx154 Active IndexComponent8 [I.1.1]          1   False       5264    1515190   False 34297.5 (MB)

ServerName Name            Drive Capacity Available Space Size on Disk Path
---------- ----            -------------- --------------- ------------ ----
xxxxx059   IndexComponent5 153469 MB      80739.6 MB      35056.8 MB   D:\SPSearchService\PrimaryIndex\SPf90231c0687...
xxxxx059   IndexComponent6 153469 MB      80739.7 MB      35154.4 MB   D:\SPSearchService\ReplicaIndex\SPf90231c0687...
xxxxx154   IndexComponent7 153469 MB      80255.5 MB      35145.9 MB   D:\SPSearchService\ReplicaIndex\SPf90231c0687...
xxxxx154   IndexComponent8 153469 MB      80255.5 MB      35154.8 MB   D:\SPSearchService\PrimaryIndex\SPf90231c0687...

Component       UpdateGroup TargetRatio   Total  Master Time                Ratio
---------       ----------- -----------   -----  ------ ----                -----
IndexComponent5 %default    10%         1521141 1502373 05.11.2015 09:03:03 1.23%
IndexComponent5 link        10%         1515464 1401709 05.11.2015 09:03:03 7.51%
IndexComponent5 people      10%             661     661 05.11.2015 09:03:03 0.00%
IndexComponent5 security    10%         1521365 1400995 05.11.2015 09:03:03 7.91%
IndexComponent5 usage       10%            6202    6202 05.11.2015 09:03:03 0.00%
IndexComponent6 %default    10%         1520228 1481600 05.11.2015 09:03:03 2.54%
IndexComponent6 link        10%         1514542 1400506 05.11.2015 09:03:03 7.53%
IndexComponent6 people      10%             652     652 05.11.2015 09:03:03 0.00%
IndexComponent6 security    10%         1520465 1399616 05.11.2015 09:03:03 7.95%
IndexComponent6 usage       10%            6215    6215 05.11.2015 09:03:03 0.00%
IndexComponent7 %default    10%         1521140 1510511 05.11.2015 09:03:03 0.70%
IndexComponent7 link        10%         1515464 1401709 05.11.2015 09:03:03 7.51%
IndexComponent7 people      10%             661     661 05.11.2015 09:03:03 0.00%
IndexComponent7 security    10%         1521361 1415827 05.11.2015 09:03:03 6.94%
IndexComponent7 usage       10%            6202    6202 05.11.2015 09:03:03 0.00%
IndexComponent8 %default    10%         1520228 1481600 05.11.2015 09:03:03 2.54%
IndexComponent8 link        10%         1514542 1400506 05.11.2015 09:03:03 7.53%
IndexComponent8 people      10%             652     652 05.11.2015 09:03:03 0.00%
IndexComponent8 security    10%         1520456 1413821 05.11.2015 09:03:03 7.01%
IndexComponent8 usage       10%            6215    6215 05.11.2015 09:03:03 0.00%

Health Reports for Index System SPf90231c06878 of Constellation 3CCEF9:

Name                                Message        Level
----                                -------        -----
active_indexrouters[SPf90231c06878] [I.0.0, I.0.1] Info
in_sync[SPf90231c06878.0]           [I.0.0, I.1.0] Info
in_sync[SPf90231c06878.1]           [I.0.1, I.1.1] Info
left_behind[SPf90231c06878.0]       []             Info
left_behind[SPf90231c06878.1]       []             Info
members[SPf90231c06878.0]           [I.1.0, I.0.0] Info
members[SPf90231c06878.1]           [I.1.1, I.0.1] Info
primary[SPf90231c06878.0]           I.0.0          Info
primary[SPf90231c06878.1]           I.0.1          Info

Primary Search Admin for Constellation 3CCEF9: NodeRunnerAdmin1 on prds0058

Home directory for SharePoint Search Service Application's Constellation:
C:\Program Files\Microsoft Office Servers\15.0\Data\Office Server\Applications\Search\Nodes\3CCEF9

So, something messed up my index and I could repair it by resetting the index.


text:
Q: Using \item in the first column of a table I have a list and a sublist both created with \enumerate, and each item in the sublist consists of two halves (both math). How could I separate the halves so that the first half of each row is left-aligned with all the other first-halves and the second half of each row is left-aligned with the second-halves?
My first thought was using \item within \tabular, but I couldn't quite get it to work. The simplest example to offer comes from page 6 of Enderton's Elements of Set Theory:
\documentclass{article}
\usepackage{amsmath,amssymb}
\begin{document}
\begin{enumerate}
\item
\begin{enumerate}
    \item \begin{tabular}{ll}$\{\emptyset\} \in \{\emptyset, \{\emptyset\}\}$ & $\{\emptyset\} \subseteq \{\emptyset, \{\emptyset\}\}$\end{tabular}

    \item \begin{tabular}{ll}$\{\emptyset\} \not \in \{\emptyset, \{\{\emptyset\}\}\}$ & $\{\emptyset\} \subseteq \{\emptyset, \{\{\emptyset\}\}\}$\end{tabular}

    \item \begin{tabular}{ll}$\{\{\emptyset\}\} \not \in \{\emptyset, \{\{\emptyset\}\}\}$ & $\{\{\emptyset\}\} \subseteq \{\emptyset, \{\{\emptyset\}\}\}$\end{tabular}

    \item \begin{tabular}{ll}$\{\{\emptyset\}\} \in \{\emptyset, \{\emptyset\}\}$ & $\{\{\emptyset\}\} \not \subseteq \{\emptyset, \{\emptyset\}\}$\end{tabular}

    \item \begin{tabular}{ll}$\{\{\emptyset\}\} \not \in \{\emptyset, \{\emptyset, \{\emptyset\}\}\}$ & $\{\{\emptyset\}\} \not \subseteq \{\emptyset, \{\emptyset, \{\emptyset\}\}\}$\end{tabular}
\end{enumerate}
\end{enumerate}
\end{document}

The result is below. As you can see, the second halves of each subitem are not aligned.

I did find other questions related to enumerated lists within tables, but I'm relatively new to LaTeX (and StackExchange) so I wasn't sure which solution was right for me. I'm looking for the simplest solution, but if it has already been supplied in another question, please point me there. Thanks in advance.

A: Here are two possible ways, without align etc. if it must be an enumerate version.
The reason, why the columns are not aligned from one item to the next is, that each \begin{tabular}{ll}...\end{tabular} has different column widths. If all would columns would have the same width, then the columns would be aligned. I've done this in the second version below, the *{2}{p{\mycolumnwidth}} sets two (2) left aligned parbox columns of width \mycolumnwidth, set here to 3.5cm. Change to appropiate values...
The first version fakes the inner enumerate by usage of an automatic row counting, using one common tabular environment.
\documentclass{article}
\usepackage{amsmath,amssymb}

\usepackage{array}

\newcounter{rowcounter}
\renewcommand{\therowcounter}{(\alph{rowcounter})}
\newcolumntype{R}{>{\stepcounter{rowcounter}\therowcounter\arraybackslash}r}

\newlength{\mycolumnwidth}

\setlength{\mycolumnwidth}{3.5cm}
\begin{document}

%%%%

\begin{enumerate}
\item
  \begin{tabular}[t]{Rll}
   & $\{\emptyset\} \in \{\emptyset, \{\emptyset\}\}$ & $\{\emptyset\} \subseteq \{\emptyset, \{\emptyset\}\}$ \tabularnewline
   & $\{\emptyset\} \not \in \{\emptyset, \{\{\emptyset\}\}\}$ & $\{\emptyset\} \subseteq \{\emptyset, \{\{\emptyset\}\}\}$ \tabularnewline
   & $\{\{\emptyset\}\} \not \in \{\emptyset, \{\{\emptyset\}\}\}$ & $\{\{\emptyset\}\} \subseteq \{\emptyset, \{\{\emptyset\}\}\}$ \tabularnewline
   & $\{\{\emptyset\}\} \in \{\emptyset, \{\emptyset\}\}$ & $\{\{\emptyset\}\} \not \subseteq \{\emptyset, \{\emptyset\}\}$ \tabularnewline
   & $\{\{\emptyset\}\} \not \in \{\emptyset, \{\emptyset, \{\emptyset\}\}\}$ & $\{\{\emptyset\}\} \not \subseteq \{\emptyset, \{\emptyset, \{\emptyset\}\}\}$
\end{tabular}
\end{enumerate}

\begin{enumerate}
\item
\begin{enumerate}
    \item \begin{tabular}{*{2}{p{\mycolumnwidth}}}$\{\emptyset\} \in \{\emptyset, \{\emptyset\}\}$ & $\{\emptyset\} \subseteq \{\emptyset, \{\emptyset\}\}$\end{tabular}
    \item \begin{tabular}{*{2}{p{\mycolumnwidth}}}$\{\emptyset\} \not \in \{\emptyset, \{\{\emptyset\}\}\}$ & $\{\emptyset\} \subseteq \{\emptyset, \{\{\emptyset\}\}\}$\end{tabular}
    \item \begin{tabular}{*{2}{p{\mycolumnwidth}}}$\{\{\emptyset\}\} \not \in \{\emptyset, \{\{\emptyset\}\}\}$ & $\{\{\emptyset\}\} \subseteq \{\emptyset, \{\{\emptyset\}\}\}$\end{tabular}
    \item \begin{tabular}{*{2}{p{\mycolumnwidth}}}$\{\{\emptyset\}\} \in \{\emptyset, \{\emptyset\}\}$ & $\{\{\emptyset\}\} \not \subseteq \{\emptyset, \{\emptyset\}\}$\end{tabular}
    \item \begin{tabular}{*{2}{p{\mycolumnwidth}}}$\{\{\emptyset\}\} \not \in \{\emptyset, \{\emptyset, \{\emptyset\}\}\}$ & $\{\{\emptyset\}\} \not \subseteq \{\emptyset, \{\emptyset, \{\emptyset\}\}\}$\end{tabular}
\end{enumerate}
\end{enumerate}

\end{document}

A: In the following code, I define a tabenumerate environment and a \tabitem command, which mimick a 2nd level enumerate environment within a tabular environment:
\documentclass{article}
\usepackage{amsmath,amssymb}
\usepackage{eqparbox}
\newcounter{tabenum}
\newenvironment{tabenumerate}{%
\setcounter{tabenum}{0}\setlength\extrarowheight{\itemsep}
\newcommand{\tabitem}{\refstepcounter{tabenum}\eqmakebox[A][r]{(\alph{tabenum})}\hskip\labelsep}
\begin{tabular}[t]{@{}l@{\qquad}l}
}
{\end{tabular}}

\begin{document}

\begin{enumerate}
  \item
        \begin{tabenumerate}
          \tabitem $\{\emptyset\} \in \{\emptyset, \{\emptyset\}\}$ & $\{\emptyset\} \subseteq \{\emptyset, \{\emptyset\}\}$\\
          \tabitem $\{\emptyset\} \not \in \{\emptyset, \{\{\emptyset\}\}\}$ & $\{\emptyset\} \subseteq \{\emptyset, \{\{\emptyset\}\}\}$\\
          \tabitem $\{\{\emptyset\}\} \not \in \{\emptyset, \{\{\emptyset\}\}\}$ & $\{\{\emptyset\}\} \subseteq \{\emptyset, \{\{\emptyset\}\}\}$\\
          \tabitem $\{\{\emptyset\}\} \in \{\emptyset, \{\emptyset\}\}$ & $\{\{\emptyset\}\} \not \subseteq \{\emptyset, \{\emptyset\}\}$\\
          \tabitem $\{\{\emptyset\}\} \not \in \{\emptyset, \{\emptyset, \{\emptyset\}\}\}$ & $\{\{\emptyset\}\} \not \subseteq \{\emptyset, \{\emptyset, \{\emptyset\}\}\}$
        \end{tabenumerate}
        %
  \item
        \begin{tabenumerate}
          \tabitem $\{\emptyset\} \in \{\emptyset, \{\emptyset\}\}$ & $\{\emptyset\} \subseteq \{\emptyset, \{\emptyset\}\}$\\
          \tabitem $\{\emptyset\} \not \in \{\emptyset, \{\{\emptyset\}\}\}$ & $\{\emptyset\} \subseteq \{\emptyset, \{\{\emptyset\}\}\}$\\
          \tabitem $\{\{\emptyset\}\} \not \in \{\emptyset, \{\{\emptyset\}\}\}$ & $\{\{\emptyset\}\} \subseteq \{\emptyset, \{\{\emptyset\}\}\}$\\
          \tabitem $\{\{\emptyset\}\} \in \{\emptyset, \{\emptyset\}\}$ & $\{\{\emptyset\}\} \not \subseteq \{\emptyset, \{\emptyset\}\}$\\
          \tabitem $\{\{\emptyset\}\} \not \in \{\emptyset, \{\emptyset, \{\emptyset\}\}\}$ & $\{\{\emptyset\}\} \not \subseteq \{\emptyset, \{\emptyset, \{\emptyset\}\}\}$
        \end{tabenumerate}
\end{enumerate}

\end{document}


text:
Q: Print Column Name of Smallest Element of Each Row in R I want R to print the column-name holding the minimum element in every row of a matrix.
Minimum Reproducible Example
################# Simulate 99 integers between 1 to 20 with replacement. ################
set.seed(1)
a <- sample.int(20, 99, replace = TRUE)
################## For a 9 by 11 matrix #####################
b <- matrix(a, ncol = 11)
colnames(b) <- 2:12
b
 ##       2  3  4  5  6  7  8  9 10 11 12
 ## [1,]  4 10  5  6  8 13 12 16  6  7 12
 ## [2,]  7 14  5 10 12 18  6 14 17 19  7
 ## [3,]  1 10  2 10  6 14  8 20  9  2  8
 ## [4,]  2  7 10  6  7  6  7  7  7 10  1
 ## [5,] 11  9 12 15 19  1 11 13 19  1 19
 ## [6,] 14 15 15 20 10 19 17 12 18 11  3
 ## [7,] 18  5  1 20  6 19  4 16 16 15 11
 ## [8,] 19  9 20 12 14  8 13  1 11 10  1
 ## [9,]  1 14  3  6  2  6  8 13 10 16 14

 ############# Instead of ##################
future.apply::future_apply(b, 1, min)
 ## [1] 4 5 1 1 1 3 1 1 1 ## is the smallest element in each row (row1 to row9), I want to print the `colname` of smallest element in each row of the matrix `b`. like this:
## [1] 2 4 2 12 11 12 4 12 1

A: You can use max.col negating the matrix b to get index of smallest value in each row. We can use this index to get corresponding column names.
colnames(b)[max.col(-b)]
#[1] "2"  "4"  "2"  "12" "11" "12" "4"  "12" "2"

A: A base R option with apply
apply(b, 1, FUN = function(x) names(x)[which.min(x)])
#[1] "2"  "4"  "2"  "12" "7"  "12" "4"  "9"  "2"


text:
Q: "init: Failed to spawn google main process: unable to execute: No such file or directory" in /var/log/syslog When booting up or restarting one of my instances in Google Compute Engine, I'm getting this error in /var/log/syslog.
Without the "google" service/process, I'm unable (among other things) to update my SSH keys from GCE's Metadata.
Running
  sudo service google start

gives me the error
  start: Job failed to start

with the same error line in /var/log/syslog.
Any ideas on how to resolve this issue?

A: Fixed myself by following the "From Source Repository" installation instructions in this git repo: https://github.com/GoogleCloudPlatform/compute-image-packages
It appears that all the /usr/... and /etc/... files were missing.


text:
Q: InterpolatingFunction gives different result when plot I solve a series of ODE equations by NDSolve({t,0,200} is the region), it gives results in the form of InterpolatingFunction[sth][t]. When I try to plot the function in follow way, it gives different picture.
Plot[InterpolatingFunction[sth][t], {t, 0, 200}, PlotRange -> {{0, 0.0001}, {10^-7, -10^-7}}, PlotLabel -> "{t, 0, 200}"]
Plot[InterpolatingFunction[sth][t], {t, 0, 1}, PlotRange -> {{0, 0.0001}, {10^-7, -10^-7}}, PlotLabel -> "{t, 0, 1}"]

there is not any error when I plot.

I wonder why this happened. I don't know how to add my InterpolatingFunction[sth][t] to the question, and my NDSolve is very complex, so I don't show.

A: I believe that the reason behind the discrepancy is that when Plot decides at which points the target expression is to be evaluated, it assumes that the "typical scale" of the independent variable is of the same order as the range specified as the second argument of Plot. PlotRange doesn't matter here, it simply determines what area to include in the picture. So, when you ask to plot an expression in the range {t, 0, 200}, Plot doesn't try to be precise at a scale of 0.0001. Neither does it try to be precise at such scale, when you ask it to plot the expression at the {t, 0, 1} range. So, basically, I would suggest that both pictures are nothing but numerical rubbish.
Consider the following to examples:
Last[Reap[
   Plot[Sin[t], {t, 0., 200.}, EvaluationMonitor :> Sow[{t, Sin[t]}],
   PlotRange -> {{0., 0.0001}, {-1., 1.}}
]]][[1, 1 ;; 10]]
({{4.08163*10^-6,4.08163*10^-6},{3.92573,-0.706216},{8.18167,0.946788},{12.1556,-0.399337},{16.0515,-0.336847},{20.2777,0.989842},{24.2218,-0.790066},{28.4962,-0.220016},{32.6926,0.957044},{36.6069,-0.887643}}*)

Last[Reap[
   Plot[Sin[t], {t, 0., 1.}, EvaluationMonitor :> Sow[{t, Sin[t]}],
   PlotRange -> {{0., 0.0001}, {-1., 1.}}
]]][[1, 1 ;; 10]]
(*{{2.04082*10^-8,2.04082*10^-8},{0.0196287,0.0196274},{0.0409084,0.0408969},{0.0607779,0.0607405},{0.0802576,0.0801715},{0.101388,0.101215},{0.121109,0.120813},{0.142481,0.141999},{0.163463,0.162736},{0.183035,0.182014}}*)

They show that when Plot is asked to plot an expression at a smaller scale, it uses a different grid to plot the expression than when it was asked to plot this expression at a larger scale, but still this grid is too dense for your PlotRange.
P.S.
If you want to examine your solution at such a small time scale relative to overall time of evolution, you should ensure that the time step that was used by NDSolve is appropriately small.
EDIT
Regarding your comment about making the pictures normal. That is how Plot builds the pictures:

*

*First, it chooses the initial grid for the plot. The number of nodes in this grid is determined by internal Plot algorithms but will not be less that PlotPoints option value. Plot will add extra nodes if its internal algorithms return less nodes than specified in PlotPoints option value. What is important here is that Plot algorithms determine the number of grid nodes using your target expression and the second argument of Plot. PlotRange doesn't matter, in fact, this options is inherited form Graphics.

*Then Plot examines how fast the target expression changes from node to node. If this change is sufficiently large, Plot will add extra nodes where necessary, but only if MaxRecursion is greater than zero and it will do extra sampling not more times than MaxRecursion. What is important here is that Plot decides whether it needs extra grid points using your target expression and the previous grid.
So, conclusions:

*

*If you set PlotRange much smaller then the range specified as the second argument, then MaxRecursion is unlikely to help because internal Plot algorithms might just decide that you don't need to see details at such scale. MaxRecusrion -> n says to Plot: "You can do extra sampling up to n times if you want". But maybe in combination with PlotPoints, when the initial grid is already very detailed, it will work.

An example:
 Last[Reap[
   Plot[Sin[t], {t, 0., 1.}, EvaluationMonitor :> Sow[{t, Sin[t]}],
   PlotRange -> {{0., 0.0001}, {-1., 1.}}, MaxRecursion -> 1]]][[1, 1 ;; 10]] ===
 Last[Reap[
   Plot[Sin[t], {t, 0., 1.}, EvaluationMonitor :> Sow[{t, Sin[t]}],
   PlotRange -> {{0., 0.0001}, {-1., 1.}}, MaxRecursion -> 15]]][[1,
 1 ;; 10]]
 (*True*)

*Setting PlotPoints to some appropriately large number will force Plot to use a very detailed grid, but note that Plot will use this detailed grid everywhere, not only inside the PlotRange.

An example:
Last[Reap[
  Plot[Sin[t], {t, 0., 1.}, EvaluationMonitor :> Sow[{t, Sin[t]}],
  PlotRange -> {{0., 0.0001}, {-1., 1.}}, PlotPoints -> 10^5]]][[1,
1 ;; 10]]
(*{{1.00001*10^-11,1.00001*10^-11},{9.61814*10^-6,9.61814*10^-6},{0.0000200453,0.0000200453},{0.0000297815,0.0000297815},{0.0000393266,0.0000393266},{0.0000496808,0.0000496808},{0.0000593441,0.0000593441},{0.0000698163,0.0000698163},{0.0000800976,0.0000800976},{0.0000896878,0.0000896878}}}*)

Honestly, why not to just specify the second argument to Plot appropriately? :)


text:
Q: How to create a customized repository for websphere (Application server)? I want to create a customized repository for websphere and publish that URL using IHS server.(preferably i want to do it in Windows server ) so that i can use that link to access binaries for installations/upgrades/patchings from other servers(Linux/Solaris) in my environment. Can anyone please provide the process ?

A: WebSphere Application Server install and maintenance is managed with a tool called IBM Installation Manager (IIM).  There is an optional tool called PUCL (Packaging Utility Commnad Line) that allows you to mirror existing repositories into directories that are directly usable over ftp:// and http://
A good summary of PUCL relative to WebSphere is available here:
http://www.ibm.com/developerworks/websphere/library/techarticles/1201_seelemann/1201_seelemann.html

You can use the IBM Packaging Utility to create custom or "enterprise"
  IBM Installation Manager repositories that contain multiple products
  and maintenance levels that fit the needs of your business. As an
  administrator, you can control the content of your enterprise
  repository, which then can serve as the central repository to which
  your organization connects to perform product installations and
  updates. IBM Packaging Utility essentially copies from a set of source
  IBM Installation Manager repositories to a target repository and
  eliminates duplicate artifacts, helping to keep the repository size as
  small as possible. You can also delete (or "prune") a repository,
  removing maintenance levels or products that are no longer needed. IBM
  Packaging Utility 1.5.0.1 can be downloaded at no cost from the IBM
  Support Portal.

   $ PUCL copy com.ibm.websphere.BASE.v80 –repositories
 http://www.ibm.com/software/repositorymanager/com.ibm.websphere.BASE.v80 -target D:\WASBase8001


text:
Q: SQL Server: combine maximum result and second largest results in single query I think this should be easy but I can't figure it out.
Here is some background information:
I have two tables, called Leases and UtilityBills.  They are connected via a foreign key called   LeaseID in the UtilityBills table, which references the primary key (also called LeaseID) in the Leases table.
So that's pretty straightforward--I am recording a monthly electricity meter reading for each of the many leases.
In the UtilityBills table I have a field called MeterReadingDate which is where I store the date when each meter reading was taken.
Here is my question:
How can I create a query which will give me, for each lease, both the date of the most recent meter reading, and the date of the prior meter reading?
I am able to get the most recent meter reading for each lease easily enough, using this sql statement:
SELECT LeaseID, MAX(MeterReadingDate) AS MostRecentMeterReadingDate
FROM   dbo.UtilityBills
GROUP BY LeaseID

I am also able to get the prior meter reading for any given lease, using this sql statement (for instance, this gives me the prior meter reading for lease with LeaseID=228):
SELECT TOP 1 MeterReadingDate, LeaseID
FROM   (SELECT TOP 2 MeterReadingDate, LeaseID
                FROM    dbo.UtilityBills
                WHERE (LeaseID = 228)
                ORDER BY MeterReadingDate DESC) DERIVEDTBL
ORDER BY MeterReadingDate

What I can't figure out, is how to combine these two statements to generate a query that lists the second-most recent and the most recent meter reading dates, for all leases.  As far as I can tell, I need to use CROSS APPLY in this situation, but can't get it to work.  Thanks!

A: If you want both dates in the same row, you can use the ROW_NUMBER() function. You do not need to join the table to itself, just use a group by like this:
IF OBJECT_ID('dbo.UtilityBills') IS NOT NULL DROP TABLE dbo.UtilityBills;

CREATE TABLE dbo.UtilityBills(
Id INT IDENTITY(1,1) PRIMARY KEY CLUSTERED,
LeaseId INT,
MeterReadingDate DATE
);

INSERT INTO dbo.UtilityBills(LeaseId,MeterReadingDate)VALUES
  (1,'2012-01-01'),
  (1,'2012-02-01'),
  (1,'2012-03-01'),
  (1,'2012-04-01'),
  (2,'2012-01-02'),
  (2,'2012-03-02'),
  (2,'2012-05-02'),
  (3,'2012-08-03'),
  (3,'2012-10-03'),
  (4,'2012-05-04');

SELECT LeaseId,
MAX(CASE WHEN rn = 1 THEN MeterReadingDate END) MostRecentReadingDate,
MAX(CASE WHEN rn = 2 THEN MeterReadingDate END) PreviousReadingDate
FROM(
SELECT  LeaseID,
        MeterReadingDate,
        ROW_NUMBER() OVER ( PARTITION BY LeaseId ORDER BY MeterReadingDate DESC ) rn
FROM    dbo.UtilityBills
)AS U
WHERE rn <=2
GROUP BY LeaseId;

There are a few other answers here suggesting the RANK() function instead of ROW_NUMBER(). However, if the last two readings happened on the same day RANK() will produce unexpected results.

A: If I understood correctly, I think you need to get the most recent 2 readings fro each LeaseID. For that this;
SELECT LeaseID, MeterReadingDate
FROM (
    SELECT LeaseID, MeterReadingDate,
           Rank() Over (Partition by LeaseID Order by MeterReadingDate desc) rk
    FROM   dbo.UtilityBills
) A
WHERE rk <3
ORDER BY MeterReadingDate desc

A: Try this
;WITh CTE AS
(
   SELECT LEASEID, MeterReadingDate, ROW_NUMBER() OVER
                       (PARTITION BY LEASEID
                        ORDER BY MeterReadingDate DESC) RN
   FROM   dbo.UtilityBills
)
SELECT x1.LEASEID, x1.MeterReadingDate CurrentDate,
x2.MeterReadingDate PreviousDate
FROM CTE x1
LEFT OUTER JOIN CTE X2 ON x1.leaseid = x2.leaseid AND x1.rn + 1 = x2.rn
WHERE X1.rn = 1

A: For your particular problem, you can combine the queries by including the group by.  Here is an example:
SELECT LeaseID, MIN(MeterReadingDate) as PriorReading, MAX(MeterReadingDate) as LatestReading
FROM   (SELECT TOP 2 MeterReadingDate, LeaseID
        FROM    dbo.UtilityBills
        WHERE (LeaseID = 228)
        ORDER BY MeterReadingDate DESC
       ) DERIVEDTBL
group by leaseid
ORDER BY MeterReadingDate

This works for the prior.  For going back longer, you need a more complex solution . . . but that is not your question.

A: try this:
SELECT
   ls.Id  as 'leaseId',
   ub.MeterReadingDate as 'MeterDate'
FROM Leases ls
    left outer join UtilityBills ub  on   ls.Id = ub.LeaseID
    left outer join UtilityBills ub2 on   ub2.LeaseID=ls.Id
                                     and  ub2.MeterReadingDate > ub.MeterReadingDate
    left outer join UtilityBills ub3 on   ub3.LeaseID=ls.Id
                                     and  ub3.MeterReadingDate > ub.MeterReadingDate
                                     and  ub3.MeterReadingDate < ub2.MeterReadingDate
    left outer join UtilityBills ub4 on   ub4.LeaseID=ls.Id
                                     and  ub3.Id is null
                                     and  ub4.MeterReadingDate > ub2.MeterReadingDate
WHERE ub2.Id is null
   or (ub3.Id is null and ub4.Id is null)


text:
Q: Webpage doesn't render despite viewport The tag "main" has a dimension of 532x897px; Despite the viewport tag, when I emulate the page onto an iphone4, it doesn't resize accordingly and overflows. Please advise.
https://github.com/elegant13/FEWD/tree/master/P0-Intro_HTML_CSS
Thank you,
Abhilash

A: Try changing width:532px to max-width:532px for the 'main' container. That should fix it.


text:
Q: How to Integrate Rest Api with GraphQL Gateway and send Context I use GraphQL Gateway to integrate with GraphQL Federation Microservices .
but I use some Rest API code for some reason. like(refresh token , Upload Images with rest)
The Question is : how to communicate with Rest API for the other services from graphql gateway and how to send context to the controller(rest api) server.
import { IntrospectAndCompose, RemoteGraphQLDataSource } from '@apollo/gateway';
import { ApolloGatewayDriver, ApolloGatewayDriverConfig } from '@nestjs/apollo';
import { Module } from '@nestjs/common';
import { GraphQLModule } from '@nestjs/graphql';
import { AppController } from './app.controller';

@Module({
  imports: [
    GraphQLModule.forRoot<ApolloGatewayDriverConfig>({
      driver: ApolloGatewayDriver,
      server: {
        // ... Apollo server options
        context: ({ req, res }) => ({
          authorization:req.headers.authorization,
          req,
          res,
          url: req.protocol + '://' + req.headers.host,
        }),
        cors: true,
      },
      gateway: {
        buildService({ name, url }) {

          return new RemoteGraphQLDataSource({
            url,
            willSendRequest({ request, context }) {
              request.http.headers.set('authorization',context['authorization'] );
            }
          });
        },
        supergraphSdl: new IntrospectAndCompose({
          subgraphs: [
            { name: 'Service1', url: 'http://localhost:3001/graphql' },
            { name: 'Service2', url: 'http://localhost:3002/graphql' },
            { name:  'Service3' , url: 'http://localhost:3003/graphql' }
          ],
        }),
      },
    }),
  ],controllers:[AppController]
})
export class AppModule { }

Note: if I removed '/graphql' from Url to access origin url , it gives me error[Couldn't load service definitions for service1] .
This code works fine with GraphQL but didn't work with Rest.
Server : NestJS.
Thanks..

A: Your question is not super clear but let me take a stab at it.
You can use a service like WunderGraph on top of your existing gateway or you can create a new gateway and ingest the GraphQL Federated Microservices. You can then introspect the REST API and ingest it into your gateway. .


text:
Q: Check particular identifier is present in the other data frame or not val df1 = Seq(("[1,10,20]", "bat","43243"),("[20,4,10]","mouse","4324432"),("[30,20,3]", "horse","4324234")).toDF("id", "word","userid")

val df2 = Seq((1, "raj", "name"),(2, "kiran","name"),(3,"karnataka","state"),(4, "Andrapradesh","state")).toDF("id", "name", "code")

Explanation:
I have two dataframes  df1 & df2. df1 is having id column which is having a list of ids.
I need to check any one of the ids is present in the df2 dataframe.
Conditions
if id is present in the df2 id column and if the code is state then get the name of the particular id from the df2 and create a new data frame with name column
Expected Output
id        |     word    |  userid   | name

-------------------------+-----------------------

[30,20,3] |  "horse"    | "4324234" | "karnataka"
[20,4,10] |  "mouse"    | "4324432" | "Andrapradesh"

A: You can flatten the id column first by converting it to an array and applying explode. Then you can apply a normal join operation between the DataFrames.
For example:
val df1 = Seq(("[1,10,20]", "bat","43243"),("[20,4,10]","mouse","4324432"),("[30,20,3]", "horse","4324234")).toDF("id", "word","userid")
val df2 = Seq((1, "raj", "name"),(2, "kiran","name"),(3,"karnataka","state"),(4, "Andrapradesh","state")).toDF("id", "name", "code")

val flattenDf1 = df1.
  select(
    col("id"),
    expr("""split(regexp_replace(id, "\\[|\\]",""), ",")""").as("idArray"), col("word"),
    col("userid")).
  withColumn("id_", explode(col("idArray"))).
  drop("idArray")

df2.as("df2").
  join(
    flattenDf1.as("df1"),
    col("df2.id") === col("df1.id_")).
  filter("code = 'state'").
  select("df1.id", "word", "userid", "name").
  show
// Result:
// +---------+-----+-------+------------+
// |       id| word| userid|        name|
// +---------+-----+-------+------------+
// |[30,20,3]|horse|4324234|   karnataka|
// |[20,4,10]|mouse|4324432|Andrapradesh|
// +---------+-----+-------+------------+

I hope it helps.

A: You could just use UDF as a condition in the join:
val arrayJoin = udf {
   (a: WrappedArray[Int], v: Int) => a.contains(v)
}

val result = df1
      .join(df2.as("df2"), arrayJoin(df2("id"), df1("id"))) //join using udf
      .drop("df2.id", "df2.code") //drop unnecessary columns


text:
Q: Even if the sun were to rise in the west, I love you I came across a sentence in my textbook:

If the sun were to rise in the west, I would never tell a lie.

And I also found a  Japanese webpage that says

*

*Even if the sun were to rise in the west, I love you.

*If the sun were to rise in the west, I will not/never change my mind.
In the above two sentences, it is inappropriate to use I would instead of I will

So then, the first sentence in my textbook also has to be rewritten into  I never tell a lie.

A: Are you asking about conversational language or poetic language? There are English idioms that express when something is unconditional, or unlikely. But there's no English expression equivalent to "if the Sun were to rise in the West..." I'm going to trust the comments that this is a word-for-word translation of a Japanese idiom.
The way you translate idioms/poetry depends on what you want to achieve. If you just want a translation that sounds natural in a normal conversation, then avoid the expression entirely. You could replace it with an English idiom (only use idioms you're familiar with). Or in a lot of cases it's sufficient to say "I love you unconditionally," or "I would never tell a lie."
If you're writing a prose translation (borrowing a term from poetry), then the goal would be to translate the original Japanese as accurately and literally as possible. In those cases you would translate it as "if the Sun were to rise in the West..." Prose translations are normally made to help people understand the original Japanese text. You could translate everything like this, but it relies a bit on your audience already having a cultural understanding of Japanese. I'm not sure about the answer to your would/will question, because the Sun rising in the West is already such an unfamiliar metaphor.
However, if you're translating into poetic language, then you have more freedom to decide what features of the Japanese expression you're trying to translate into English. You could keep the comparison about the Earth's rotation, or you could use an English expression that feels similar, or reword the expression to sound more natural, understandable etc. You have to decide what's most important. No matter how you translate it, you're going to lose some of the original meaning. Some example poetic translations that try to keep the metaphor:

The Sun will rise in the West before I'll tell a lie.

The Sun may rise in the West; I will never tell a lie.

Even if the Sun rose in the West, I would still love you.

You asked about Shakespeare. Shakespeare quotes are instantly recognizable as poetic language, not conversational speech. There have been poetic translations of his work which update it to modern English. Although the most popular format of Shakespeare's work tends to be the original.


text:
Q: Cannot find scale bar tool I am new to QGIS and I am working with version 3.22.5. I am trying to add a scale bar to a map. According to web tutorials, there should be a scale bar tool available. However, I cannot find it anywhere.
Is it possible that I am not displaying the whole toolbox?

A: The scale bar is located, on the layout view (main view) here on the top menu:

However, if you are looking for the scale bar in the Print Composer view, it is located on the left-hand side menu, here:


text:
Q: Avoiding empty spaces on the sides of the panels in wxPython I am working with wxPython v3.0 and python v2.7 on Windows 8 OS.
The code is provided below.
Problem: If you scroll the vertical scroll bar completely to the bottom and scroll the horizontal scroll bar completely to the right side, then you shall notice empty spaces at the bottom of the panels and at the right side of the panels as shown in the image below. How to avoid this? Is this the default behavior or am I doing something wrong? It would be great if someone can test this on his/her system and confirm if this is a normal behavior?

Code:
import wx
import wx.lib.scrolledpanel

class GUI(wx.Frame):
    def __init__(self, parent, id, title):
        screenWidth = 700
        screenHeight = 400
        screenSize = (screenWidth, screenHeight)
        wx.Frame.__init__(self, None, id, title, size=screenSize)
        myFont = wx.Font(15, wx.MODERN, wx.NORMAL, wx.BOLD)
        mainSizer = wx.BoxSizer(wx.VERTICAL)
        panelsSizer = wx.BoxSizer(wx.HORIZONTAL)
        sizer1 = wx.BoxSizer(wx.VERTICAL)
        sizer2 = wx.BoxSizer(wx.VERTICAL)
        mainPanel = wx.lib.scrolledpanel.ScrolledPanel(self, -1,style=wx.SIMPLE_BORDER)
        mainPanel.SetupScrolling()
        panel1 = wx.lib.scrolledpanel.ScrolledPanel(mainPanel, -1, style=wx.SIMPLE_BORDER)
        panel1.SetupScrolling(scroll_y=False)
        panel2 = wx.lib.scrolledpanel.ScrolledPanel(mainPanel, -1, style=wx.SIMPLE_BORDER)
        panel1.SetBackgroundColour('#cccFFF')
        panel2.SetBackgroundColour('#FFFaaa')
        panelsSizer.Add(panel1, 1, wx.ALL|wx.EXPAND)
        panelsSizer.Add(panel2, 2, wx.ALL|wx.EXPAND)
        mainPanel.SetSizer(panelsSizer)

        k = 0
        #Populating the panel-1 with panels to show scroll bars
        for i in range(1,20):
            lPanels = 'lPanel'+str(k)
            lPanels = wx.Panel(panel1)
            label0 = str(k+1)+ '. '+'Panel-1   #############################'
            text0 = wx.StaticText(lPanels, -1, label0)
            text0.SetFont(myFont)
            sizer1.Add(lPanels, 0, wx.ALL|wx.EXPAND, 5)
            sizer1.Add(wx.StaticLine(panel1), 0, wx.ALL|wx.EXPAND, 0)
            k += 1

        k = 0
        #Populating the panel-2 with panels to show the scroll bars
        for i in range(1,20):
            sPanel ='sPanel' +str(k)
            sPanel = wx.Panel(panel2)
            label = str(k)+ '. Panel-2#############################'
            text = wx.StaticText(sPanel, -1, label)
            text.SetFont(myFont)
            sizer2.Add(sPanel, 0, wx.ALL|wx.EXPAND, 5)
            sizer2.Add(wx.StaticLine(panel2), 0, wx.ALL|wx.EXPAND, 0)
            k += 1

        panel1.SetSizer(sizer1)
        panel2.SetSizer(sizer2)
        mainSizer.Add(mainPanel, 15, wx.EXPAND|wx.ALL)
        self.SetSizer(mainSizer)

if __name__=='__main__':
    app = wx.App()
    frame = GUI(parent=None, id=-1, title="Test")
    frame.Show()
    app.MainLoop()

Thank you for your time!

A: It is normal.  wx.ScrolledWindow rounds the virtual size up to the next multiple of the scroll rate, so you end up with between 0 and scroll rate extra pixels.


text:
Q: How to access list from a child within a child? I'm working on a program where I let the user add items to a list view. These items are then stored in a list that makes it really easy for me to load the list view on startup using a StreamReader. Now, here's my problem. The user can select an item in the list view and then click a button to show a window that basically shows more information about the item that the user has selected. In order to change, lets say, the name, I want to open yet ANOTHER window where the user can enter the new name which is then changed and saved into the list when pressing a button.
I can easily access the list from the first child by sending an instance of Form1 to Form2 using a constructor. But how do I go about accessing Form1 from Form3 when Form3 is opened from Form2?
I use the following code to access Form1 in Form2:
Form1:
private void button1_Click(object sender, System.EventArgs e)
{
    Form2 form2 = new Form2(this);
    form2.StartPosition = FormStartPosition.CenterParent;
    form2.ShowDialog(this);
}

Form2:
private Form1 _Form1;

public Form2(Form1 _Form1)
{
    this._Form1 = _Form1;
}

A:
"how do I go about accessing Form1 from Form3 when Form3 is opened from Form2"

Well, since Form2 has access to the instance of Form1, if Form3 needs it then Form2 can give it.
One way is to pass it through the constructor, as you did previously:
public class Form2
{
    private Form1 _Form1;

    public Form2(Form1 form1)
    {
        this._Form1 = form1;
    }

    // Imaginary method that needs to pass Form1 to Form3
    public string GetName()
    {
        // Pass our reference to Form1 to the constructor of Form3
        Form3 form3 = new Form3(this._Form1);
        form3.StartPosition = FormStartPosition.CenterParent;
        form3.ShowDialog(this);

        return form3.txtName.Text;
    }
}


text:
Q: Get records with more than one value and at least one of them is zero Create table #Tbl
(
ID int not null,
Keyword nvarchar(max)
)
Insert into #Tbl Values ('0','Cryptography')
Insert into #Tbl Values ('1','Cryptography')
Insert into #Tbl Values ('4','Cryptography')
Insert into #Tbl Values ('0','SQL')
Insert into #Tbl Values ('0','SQL')
Insert into #Tbl Values ('3','Cloud Computing')
Insert into #Tbl Values ('6','Recursion')
Insert into #Tbl Values ('8','Recursion')
Insert into #Tbl Values ('0','Universe')
Insert into #Tbl Values ('0','Universe')
Insert into #Tbl Values ('7','Universe')

I need to get the titles which has more than one ID and at least one of the ID is zero.
So the expected result will be:
Cryptography
Universe

I tried below query but not able to add "at least one id is zero" condition
select Keyword,COUNT(distinct id) from #Tbl
group by Keyword
having COUNT(distinct id)>1

How can I proceed here ? Thanks for your help.

A: Assuming your IDs start from 0, the below should work
select Keyword,COUNT(distinct id) from #Tbl
group by Keyword
having COUNT(distinct id)>1 and MIN(id) = 0

A: There are many ways to do this, one example:
SELECT DISTINCT Keyword
FROM #Tbl T
WHERE EXISTS (SELECT 1 FROM #Tbl WHERE Keyword = T.Keyword
              AND ID = 0)
AND EXISTS (SELECT 1 FROM #Tbl WHERE Keyword = T.Keyword
              AND ID != 0)

Here is a sqlfiddle with a demo.

A: This should do it:
SELECT Keyword
FROM  #Tbl
WHERE Keyword IN (SELECT DISTINCT Keyword FROM #Tbl WHERE ID = 0)
GROUP BY Keyword
HAVING COUNT(DISTINCT id) > 1

A: Here's yet another approach:
SELECT Keyword, COUNT(DISTINCT ID)
FROM #Tbl
GROUP BY Keyword
HAVING COUNT(DISTINCT ID) > ALL (SELECT COUNT(DISTINCT NULLIF(ID, 0)) UNION ALL SELECT 1)
;


text:
Q: Integrate zxing code with the application and install in on Android os higher than 1.5 i am working on an application that needs to scan bar codes as a functionality..I have integrated all the code of zxing with my app code and now when i try to install it on my device(OS 1.6) it gives me an "INSTALL_FAILED_CPU_ABI_INCOMPATIBLE" error...
i cant use intents to use the barcode application because that will create a necessity to have zxing installed on the device..i want my application to be standalone..
Please suggest what do i do???

A: I did the same thing you tried to do. I did not have any such error.
Yet, the error mentions ABI, which makes me believe the problem is NDK related. (AFAIK) ZXing doesn't use native code, so you should look at the native code in you application.


text:
Q: Change HTTP status code in Jekyll I'm using Jekyll to generate my website. When you add a file called 404.html to your web root and a page isn't found in a Jekyll website, then Jekyll will automatically display the contents of the 404.html file to the user. However, it does so with an unchanged URL (but, with a correct HTTP status return code of 404).
In order to be able to log errors in Google Analytics (and set a Custom Alert to alert me of any 404's), I want to forward the error page to /404/?broken=url-goes-here. This page unfortunately, returns a HTTP status code of 200. This leads to the main question:
How do I get a page to return a different status code than 200 in Jekyll? The original page that is fetched upon an error correctly returns 404, but my /404/ page returns 200, and I want it to return 404 (preferably without using any Jekyll Plugins, AJAX or Javascript).
Anyone?

A: In Github pages, you can set a custom 404.html page.
The name must be 404.html.
The http returned code is 404.
You can then catch this in analytics.


text:
Q: Error: The 'pycuda' distribution was not found and is required by the application What is causing this error?
raise DistributionNotFound(req, requirers)
pkg_resources.DistributionNotFound: The 'pycuda' distribution was not found and is required by the application
-------------------------------------------------------------------
PyCUDA ERROR: The context stack was not empty upon module cleanup.
-------------------------------------------------------------------
A context was still active when the context stack was being
cleaned up. At this point in our execution, CUDA may already
have been deinitialized, so there is no way we can finish
cleanly. The program will be aborted now.
Use Context.pop() to avoid this problem.

A: The error is pretty self-explanatory. The code you're trying to run wants to use the pycuda package, but the package is not installed.
You can try running pip install pycuda, preferably inside a virtuaenv.


text:
Q: Will the ajax callback always be executed after the loop? I have this Javascript/JQuery code:
$.ajax({...}).done(function() {
    console.log('done');
});
for(var i = 0; i < 10; i++)
    console.log(i);

Let's say the ajax request completes when the loop has reached the 5th iteration, will the browser suspend the loop execution and run the callback or will it wait for the loop to finish?
To make it more clear, is an output like this possible?

0

1

2

3

4

done

5

6

7

8

9
or will the output always be:

0

1

2

3

4

5

6

7

8

9

done
More in general I was wondering if the browser always pushes the callback, when triggered, at the bottom of the execution queue.

A: You could get both output example you describe, depending on the time the ajax request takes to complete.
EDIT: Note that this might lock your browser for a while, but it should not crash, and then prints something like ***** DONE! ***** 2828725

var promise = new $.Deferred(),
    i = 1, j = 0, to = 5000000;

promise.done(function() {
    document.write("***** DONE! *****\n" + i);
    i = to;
});

setTimeout(function() {
    promise.resolve();
}, 1000);

for(i = 1; i < to; ++i) {
    console.log(++j);
    //alert(++j);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

A: The test I did seems to show the loop must complete first
fiddle
time = new Date()
new Request.JSONP({
    url: 'http://jsfiddle.net/echo/jsonp/',
    onSuccess: function (response) {

        console.log('done ' + (new Date()-time))
    }
}).send();

for (var i = 0; i <= 65535; i++) {
    for (var j = 0; j <= 10000; j++) {
            if (i===65535 && j == 10000)
            {
        console.log('loop complete ' + (new Date()-time))
            }
    }
}


text:
Q: How to loop in Java and Android Studio I have made an alarm clock app however, I am trying to make a homepage where the user can see all the alarms they have set. I want to infinitely run a block of code that updates the homepage of my app, but the methods I have found have not worked (i.e using a timer loop, while, and for loop). Any suggestion would help me a lot, also any critique to the code would help to, Thanks everyone!
I have tried
Timers, Do-While, While, and For Loops
The While loop that is in there currently cause an error and the app does not even run.
All the code I need help with is in the While Loop.
I think this is the error

(I/zygote64: Rejecting re-init on previously-failed classjava.lang.Class: java.lang.NoClassDefFoundError: Failed resolution of: Landroid/view/View$OnUnhandledKeyEventListener;)

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_alarms);

    final Button selectAlarm1 = (Button) findViewById(R.id.selectAlarm1);
    final Button selectAlarm2 = (Button) findViewById(R.id.selectAlarm2);
    final Button selectAlarm3 = (Button) findViewById(R.id.selectAlarm2);

    selectAlarm1.setVisibility(View.INVISIBLE);
    selectAlarm2.setVisibility(View.INVISIBLE);
    selectAlarm3.setVisibility(View.INVISIBLE);

    final TextView textView = (TextView) findViewById(R.id.textView);

    final Button createAlarm = (Button) findViewById(R.id.createAlarm);
    final Button createAlarm2 = (Button) findViewById(R.id.createAlarm2);
    final Button createAlarm3 = (Button) findViewById(R.id.createAlarm3);

    createAlarm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openMainActivity();
                createAlarm2.bringToFront();
            }
        });
    createAlarm2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openMainActivity2();
                createAlarm3.bringToFront();
            }
        });
    createAlarm3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openMain3Activity();
            }
        });

    selectAlarm1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openMainActivity();
            }
        });
        selectAlarm2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openMainActivity2();
            }
        });
        selectAlarm3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openMain3Activity();
            }
        });

    while(true){
            if (Global.intHour1 != 0 && Global.intMinute1 != 0) {
                textView.setVisibility(View.GONE);
                selectAlarm1.setVisibility(View.VISIBLE);

                //fixing minute format
                if (Global.intMinute1 <= 9) {
                    selectAlarm1.setText("Alarm 1 is set for " +
Global.intHour1 + ":0" + Global.intMinute1);
                } else {
                    selectAlarm1.setText("Alarm 1 is set for " +
Global.intHour1 + ":" + Global.intMinute1);
                }

            } else if (Global.intHour1 == 0 && Global.intMinute1 == 0) {

                textView.setVisibility(View.VISIBLE);

            }
            if (Global.intHour2 != 0 && Global.intMinute2 != 0) {
                selectAlarm2.setVisibility(View.VISIBLE);

                //fixing minute format
                if (Global.intMinute2 <= 9) {
                    selectAlarm2.setText("Alarm 1 is set for " +
Global.intHour2 + ":0" + Global.intMinute2);
                } else {
                    selectAlarm2.setText("Alarm 1 is set for " +
Global.intHour2 + ":" + Global.intMinute2);
                }
            } else {

            }
            if (Global.intHour3 != 0 && Global.intMinute3 != 0) {
                selectAlarm3.setVisibility(View.VISIBLE);

                //fixing minute format
                if (Global.intMinute3 <= 9) {
                    selectAlarm3.setText("Alarm 1 is set for " +
Global.intHour3 + ":0" + Global.intMinute3);
                } else {
                    selectAlarm3.setText("Alarm 1 is set for " +
Global.intHour3 + ":" + Global.intMinute3);
                }
            }
            else {

            }
            if (selectAlarm1.getVisibility() == View.INVISIBLE &&
selectAlarm2.getVisibility() == View.INVISIBLE &&
selectAlarm3.getVisibility() == View.INVISIBLE) {
                textView.setVisibility(View.VISIBLE);

            }
            else
            {

            }
        }
    }

    public void openMainActivity () {

        Intent openAlarm = new Intent(this, MainActivity.class);

        startActivity(openAlarm);

    }
    public void openMainActivity2 () {

        Intent openAlarm2 = new Intent(this, MainActivity2.class);

        startActivity(openAlarm2);

    }
    public void openMain3Activity () {

        Intent openAlarm3 = new Intent(this, Main3Activity.class);

        startActivity(openAlarm3);

    }
    public void makeTextVisible () {

    }

}

I want the code to recognize when the intHour1-3 and intMinute1-3 are changed and change the visibility state of a button so that when the user returns to the homepage they can see which alarms are set.


text:
Q: Configuring word-wrap in column header of an Antd Table I already spent too much time searching on how to configure the column headers of Antd tables, in the official Antd table docu and elsewhere, but I was not successful: Is there a simple way of adjusting the word-wrap of the column header?
Right now, if the column is too small (e.g. when resizing the browser window), letters are floating into new lines in an uncontrolled manner. English hyphenation would be cool, but for a start I would appreciate having 2 or 3 ellipsis dots instead of freely dropping characters.
Any Antd-experts out there who could help me out, please?
Minimal non-working example
import { Table } from "antd";
const { Column } = Table;

const dataSource = [
  {
    key: '1',
    name: 'Mike',
  },
  {
    key: '2',
    name: 'John',
  },
];

const columns = [
  {
    title: 'My very-very-very long column-name',
    dataIndex: 'name',
    key: 'name',
  },
];

;

Related questions

*

*Overwriting a single (nested) property when extending a React class is the more general problem I am facing.

*How can we configure the Header of ant design table component?

*Customize React Antd table header with table data

A: Table.Column.title accepts a ReactNode, so you only need to render an Ellipsis component.
You should use antd built-in Ellipsis, for that use Typoghrapy API.
Note: You should strain container's width so the ellipsing will work:
const COLUMN_STYLE = { width: 200 };
<Typography.Text ellipsis={true} style={COLUMN_STYLE}>
  A very long text
</Typography.Text>

You can achieve the same effect with pure CSS, refer to text-overflow.
const dataSource = [
  {
    key: '1',
    name: 'Mike'
  },
  {
    key: '2',
    name: 'John'
  }
];

const COLUMN_STYLE = { width: 200 };

const customColumn = {
  title: (
    <Typography.Text ellipsis={true} style={COLUMN_STYLE}>
      My very-very-very long column-name My very-very-very long column-name My
      very-very-very long column-name
    </Typography.Text>
  ),
  dataIndex: 'name',
  key: 'custom'
};

const normalColumn = {
  title: 'My very-very-very long column-name',
  dataIndex: 'name'
};

const TOTAL_COLUMNS = 6;

const columns = [...Array(TOTAL_COLUMNS).keys()].map(key => ({
  ...normalColumn,
  key
}));

const App = () => (

);

A: Since I am (yet) stuck with an old version of Antd, I went the inline-CSS way suggested by Dennis Vash. Within the render() function, I defined
var myColTitleStyle = {
            textOverflow: 'ellipsis',
            // overflow: "hidden",
            whiteSpace: 'nowrap'
};

Interestingly, I had to comment the parameter overflow out, although https://developer.mozilla.org/en-US/docs/Web/CSS/text-overflow suggests that it is required for the property text-overflow to work. Also note the CamelWritingStyle of the css-properties within React.
Inside the component, the imports are
import { Table } from "antd";
const { Column, ColumnGroup } = Table;

The actual call of Antd's Column contains a
 within the title, plus the inline-CSS:
<Column
   title={
My long-long title
}
   width=10
>

Please also note that textOverflow will only work with absolute widths, which are dimensionless in React. It will not work when using percentage-widths.


text:
Q: How to modify the elements of one list based on another I have two lists like
lst1 = ['a', 'b', 'c', 'd', 'e']
lst2 = ['q', 'r', 's']

Now, suppose I generate a mapping from list2 to list1 one like (4, 0, 3) meaning update the 4th element of list1 with the 0th element of list2, update the 0th element of list1 with the 1st element of list2, etc. such that the resulting list looks like
lst1 = ['r', 'b', 'c', 's', 'q']

How can I do this?

A: One way would be to use enumerate:
lst1 = ['a', 'b', 'c', 'd', 'e']
lst2 = ['q', 'r', 's']
mapping = [4, 0, 3]

for lst2_n, lst1_n in enumerate(mapping):
    lst1[lst1_n] = lst2[lst2_n]


text:
Q: MySQL Date, Minutes Add to a value I cant seem to get this to work, It returns Null
SELECT sdt, timeFor, DATE_ADD(TIMESTAMP(sdt), INTERVAL timeFor MINUTE) FROM tbl_day

The return keeps returning
sdt, timeFor, DATE_ADD(TIMESTAMP(sdt), INTERVAL timeFor MINUTE)
'0000-00-00 01:00:00', 15, ''

Columns Type

*

*sdt DATETIME

*timeFor BIGINT(20)

Any ideas

A: MySQL usually returns NULL on date/time operations when column value is incomplete datetime. Something like 2010-00-05 11:22:33, etc. Also using timestamp function on sdt column might not be a good idea. I'd suggest providing normal datetime value.


text:
Q: Some questions about BJT in saturation region In below circuit I sweep Vb from zero to 5V Vcc.
And I obtain the following plots for the currents:

I have a bit problem with understanding two things in saturation region:
1-) Why/how does the Ic decreases with Vb after the saturation point?
2-) How can I quantify/formulate Ib at saturation region?

A: The collector current in your circuit decreases because, when the BJT is in saturation, by definition, the junction B-C is forward biased.
Therefore you'll have that the collector voltage will be just \$V_C=V_B-V_{BC}\$.
As a result, the current in the resistor Rc will be:
$$I_C=\frac {V_{CC}-V_C}{R_C} = \frac{V_{CC}-(V_B-V_{BC})}{R_C}$$
Therefore the higher \$V_B\$, the smaller \$I_C\$.
To answer the second question, simply use KCL at the BJT. You know that \$I_C+I_B-I_E=0\$ (assuming base and collector currents entering  the BJT. Emitter current exits the BJT).  Hence \$I_B=I_E-I_C\$. In fact in your plot, \$I_B\$ is the difference of the other two currents.
As a first order approximation, you can assume constant \$V_{BC}\$ and \$V_{BE}\$. This allows you to calculate \$I_C\$ and \$I_E\$ easily.


text:
Q: how to call function when my (monaca /onsen UI ) start in my (monaca /onsen UI angularjs ) application I want to load my projects when the project is start

and this is the html page

 <ons-sliding-menu
  menu-page="menu.html" main-page="home.html" side="left"
  var="menu" type="reveal" max-slide-distance="260px" swipable="true">
</ons-sliding-menu>
<ons-template id="home.html">
  <ons-navigator var="myNav">
  <ons-page>
    <ons-toolbar>

        <ons-toolbar-button ng-click="menu.toggle()">
          <ons-icon icon="ion-navicon" size="28px" fixed-width="false"></ons-icon>
        </ons-toolbar-button>

Projects

        <ons-toolbar-button>
            <ons-icon icon="refresh" size="30px" fixed-width="true"></ons-icon>
        </ons-toolbar-button>

    </ons-toolbar>

    <ons-list>
        <ons-list-item ng-click="app.showDetails()" ng-repeat="item in app.projects">
              {{item.projectcode}}
        </ons-list-item>

 Levels

    </ons-list>
  </ons-page>
  </ons-navigator>
</ons-template>

as you can see I need to call the function  getProjects() from the AppController when the application start so I can get the projects from DB to display it

A: There are 3 easy ways to achieve what you want. The differences are minor, but it's best to know them.

*

*using the ons-page's ons-init attribute
<ons-navigator var="myNav">
  <ons-page ons-init="app.getProjects()">
    ...
  </ons-page>
</ons-navigator>

This will load the data when the page is initialized (becomes attached to the DOM).

*using the ons-page's ons-show attribute
<ons-navigator var="myNav">
  <ons-page ons-show="app.getProjects()">
    ...
  </ons-page>
</ons-navigator>

This will load the data when the page is shown (for example if you are switching between many pages). This means that if you go to another page with the navigator and then go back it will be called again (that way refreshing the projects).

*using the ons.ready function. If you want to call the function only once after onsen is ready to do its magic ui stuff you can use this. It makes sure that DOMContentReady, deviceready and some other events have been triggered and then calls your function. Usage:
ons.ready(function(){
  // get the data
});

Note: it takes a function - that means that you shouldn't actually call it yourself - it should be like this ons.ready(myFunction) , NOT ons.ready(myFunction()).
Feel free to choose the method which you think is most relevant for your case.
Some final notes:

*

*The attribute is swipeable - you missed the e. Your example works because it's swipeable by default.

*I don't see you having $http as a dependency. Unless you have it from somewhere else you should do:
ons.bootstrap()
  .controller('AppController', function($http) {
    ...
  });


text:
Q: Spring CrudRepository not saving more than 32,000 characters I am trying to save an entity using Springs crud repository (repo.save(Entity)) to my sql db - for some reason though when the entity is saved, the entity's variables/payloads are cut off at 32,000 characters in the db. Is there a limit that is causing this? (The column in my SQL db is type LONGTEXT - max of ~4million characters).

A: Solved it with annotating the column with @Lob, and specifying as columnDefinition = "LONGTEXT"


text:
Q: Bus error when printing to output file I keep recieving a bus error when trying to write to my output file. my binary function converts incoming text, from the input file, to binary and puts it in the output file. But I keep getting this bus error when I run, and I do not know why!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>

#define MAXLEN 255
#define FLAG 1
#define INPUT 2
#define OUTPUT 3

int binary(unsigned char x){ //, int argc, char* argv[]){
  FILE* out;

  unsigned char i, n = (sizeof(x) * CHAR_BIT) -1;
  int t;
  for(i=0; i<= n; i++){

    fprintf(out, "%d",(x >> (n-i) & 1));
  }
  fprintf(out, " \n");
}

int main(int argc, char *argv[]){

  FILE *in, *out;
  char instring[MAXLEN];
  const char *p;

  in = fopen(argv[INPUT], "r");
  if(in == NULL){
    printf("Error: This File is Empty.\n");
    exit(1);
  }else{
     out = fopen(argv[OUTPUT], "w");

  if(strcmp(argv[FLAG], "-b") == 0){
    fgets(instring, MAXLEN, in);

    for(p = instring; *p != '\0'; p++){
      // fprintf(out, "%d", binary(*p));
      binary(*p);
  }
 }
   else
   if(strcmp(argv[FLAG], "-t") == 0){

  }

   else{
    printf("Error: Flag Not Recognized.\n");
    return 0;
   }
 }
  fclose(in);
  fclose(out);
}


text:
Q: Largest triangle from a set of points
Possible Duplicate:
How to find largest triangle in convex hull aside from brute force search

I have a set of random points from which i want to find the largest triangle by area who's verticies are each on one of those points.
So far I have figured out that the largest triangle's verticies will only lie on the outside points of the cloud of points (or the convex hull) so i have programmed a function to do just that (using Graham scan in nlogn time).
However that's where I'm stuck. The only way I can figure out how to find the largest triangle from these points is to use brute force at n^3 time which is still acceptable in an average case as the convex hull algorithm usually kicks out the vast majority of points. However in a worst case scenario where points are on a circle, this method would fail miserably.
Dose anyone know an algorithm to do this more efficiently?
Note: I know that CGAL has this algorithm there but they do not go into any details on how its done. I don't want to use libraries, i want to learn this and program it myself (and also allow me to tweak it to exactly the way i want it to operate, just like the graham scan in which other implementations pick up collinear points that i don't want).

A: Don't know if this help, but if you choose two points from the convex hull and rotate all points of the hull so that the connecting line of the two points is parallel to the x-Axis, either the point with the maximum or the one with the minimum y-coordinate forms the triangle with the largest area together with the two points chosen first.
Of course once you have tested one point for all possible base lines, you can remove it from the list.

A: Off the top of my head, perhaps you could do something involving gridding/splitting the collection of points up into groups? Maybe... separating the points into three groups (not sure what the best way to do that in this case would be, though), doing something to discard those points in each group that are closer to the other two groups than other points in the same group, and then using the remaining points to find the largest triangle that can be made having one vertex in each group? This would actually make the case of all points being on a circle a lot simpler, because you'd just focus on the points that are near the center of the arcs contained within each group, as those would be the ones in each group furthest from the other two groups.
I'm not sure if this would give you the proper result for certain triangles/distributions of points, though. There may be situations where the resultant triangle isn't of optimal area, either because the grouping and/or the vertex choosing aren't/isn't optimal. Something like that.
Anyway, those are my thoughts on the problem. I hope I've at least been able to give you ideas for how to work on it.

A: Here's a thought on how to get it down to O(n2 log n). I don't really know anything about computational geometry, so I'll mark it community wiki; please feel free to improve on this.
Preprocess the convex hull by finding for each point the range of slopes of lines through that point such that the set lies completely on one side of the line. Then invert this relationship: construct an interval tree for slopes with points in leaf nodes, such that when querying with a slope you find the points such that there is a tangent through those points.
If there are no sets of three or more collinear points on the convex hull, there are at most four points for each slope (two on each side), but in case of collinear points we can just ignore the intermediate points.
Now, iterate through all pairs of points (P,Q) on the convex hull. We want to find the point R such that triangle PQR has maximum area. Taking PQ as the base of the triangle, we want to maximize the height by finding R as far away from the line PQ as possible. The line through R parallel to PQ must be such that all points lie on one side of the line, so we can find a bounded number of candidates in time O(log n) using the preconstructed interval tree.
To improve this further in practice, do branch-and-bound in the set of pairs of points: find an upper bound for the height of any triangle (e.g. the maximum distance between two points), and discard any pair of points whose distance multiplied by this upper bound is less than the largest triangle found so far.

A: I think the rotating calipers method may apply here.

A: How about dropping a point at a time from the convex hull?  Starting with the convex hull, calculate the area of the triangle formed by each triple of adjacent points (p1p2p3, p2p3p4, etc.).  Find the triangle with minimum area, then drop the middle of the three points that formed that triangle.  (In other words, if the smallest area triangle is p3p4p5, drop P4.)  Now you have a convex polygon with N-1 points.  Repeat the same procedure until you are left with three points.  This should take O(N^2) time.
I would not be at all surprised if there is some pathological case where this doesn't work, but I expect that it would work for the majority of cases.  (In other words, I haven't proven this, and I have no source to cite.)


text:
Q: Erlang Documentation/SMP: single-node and multi-node per machine or per application, and the confusion that may follow I'm studying Erlang's process model at the moment. I have hit a snag in a tech report (section 3, paragraph 2) on Erlang:

This explains why it in some cases can be more efficient to run several SMP VM's
  with one scheduler each instead on one SMP VM with several schedulers. Of course
  the running of several VM's require that the application can run in many parallel tasks
  which has no or very little communication with each other.

Now this paragraph is confusing me; I can see the uni-process multiple scheduler scenario, but I am failing to see multiple processes with a single scheduler; Presumably each process would have a different node name, and this would mean a certain application, without modification, cannot be used with this model; the virtue of not requiring modification has been mentioned as a key feature of SMP in the report. If the multiple processes have the same node names, than performance would be disastrous due to inter-Erlang-process messaging storms -- this assume the use of in-memory amnesia. Is there some process model that is not introduced in the article and that I am missing here ?
What is the author trying say here ? is he trying to suggest that an application would have to be rewritten (to take multiple unique node-names into account) for the multi-process single-scheduler case ?
-- edit 1: Clarification of Source of Problem  --
The question has been answered through discussion; the following is an outline of the trouble I had.
The issue for this question has been that the documentation, as I recall, does not touch on a scenario of running multiple Erlang emulators per physical machine -- it has always been shown that the emulator represents your physical machine (in industrial usage); also, the scenario of having to explicitly partition a program for computational efficiency has never been considered. This sudden introduction has been the source of my woe.
The convention is still biased towards creating LOTS of processes and that the future holds many improvements for the SMP emulator for Erlang, and this means that single node per machine is still a very viable option assuming favourable application design.

A: Rewrite after reading article:

This explains why it in some cases can
  be more efficient to run several SMP
  VM's with one scheduler each instead
  on one SMP VM with several schedulers.

*

*Non-SMP VM has no-lock so runs fast.

*Single scheduler SMP VM 10% slower, due to cost of checking locks

*Multiple scheduler SMP VM slower again due to using/waiting for locks

Of course the running of several VM's
  require that the application can run
  in many parallel tasks which has no or
  very little communication with each
  other.

*

*I think: Nodes on the same server have to have different names.

*Inter process messaging while by slower due to the inter-process nature verse intra process messaging of a VM node.

A: If you have multiple schedulers in a single VM, they will inevitably contend over various resources (e.g. ets meta table, atom-table, scheduler run-queue during migration, etc.) because of the inner architecture. If you have a single scheduler, contention will obviously not occur. Lock checking and acquiring will still be done though, so running a non SMP VM instead shall yield even better performance (but requires a rebuilding of the VM from source).
Take a four-core machine for example. Option one means that you run four instances of the Erlang VM, each with a single scheduler, affinity set to different processor cores. Option two means running a single Erlang VM with four schedulers, each scheduler's affinity set to different processor cores.
If you have a whole lot of independent processes to run, option two will result in better performance, because the four cores will be fully utilized (theoretically). In contrast, in option one, this won't be possible, because the lock contention will make execution on cores wait for each other every now and then.
On the other hand if your processes need to chatter a lot, option one is the way to go because the inter-process communication is way cheaper than communication between different VMs. You gain more with this than you lose with lock contention.

A: I believe the answer is in the preceding paragraph:

The SMP VM with only one scheduler is slightly slower (10%) than the non
  SMP VM.
  This is because the SMP VM need to use locks for all shared
  datastructures. But as
  long as there are no lock-conflicts the overhead caused by
  locking is not that high (it
  is the lock conflicts that takes time).

Scheduler's reliance on locks for shared data structures can impose an overhead on a given system. It seems to follow that having multiple schedulers on one SMP VM imposes a collectively greater overhead.

A: There are some advatanges with several nodes on one physical machine.
1) Resource locking overhead as mentioned.
2) Fail-over. In telecom products you really don't want to have the beam come crashing down on you. If you have NIFs or linked-in drivers in your system this might occur.
3) Memory locality. Few nodes gives you a poor-mans way to force processes to a few cores. This could be a big boost for NUMA archs typically but also for SMP. The scheduler don't take NUMA into account (yet). You can spawn a process to a specific scheduler and lock it to it, it won't migrate but that is an undocumented feature ... or it was removed all together. I forget.
With several nodes you will need a load balancer between the nodes of course but that is the usual way to do it anyways. Some logic that supervises the nodes.
However, the numbers from the EUC papers are over a year old [@] and I wouldn't recommend a multi-node approach if you don't really need it. The runtime system is much better at handling these types of problems today. A lot of lock overhead has been removed and the mrq-scheduler has been improved.
@ 2009's numbers look like this.
Edit:
Regarding 3) the spawn feature i mentioned is,

spawn_opt(fun() -> ... end, [{scheduler, Id}]) -> pid(),
    where Id is an integer and refers to a specific scheduler.

I wouldn't recommend using it since it undocumented.


text:
Q: MergeSort - Implementation After many recursive calls low becomes equal to high and the recursion breaks. What happens after that? Can anyone please explain. Merge procedure is clear to me: when mergesort(0,5) is called, it calls itself again: mergesort(0,2) and then mergesort(0,1). Finally mergesort(0,0) and then recursion breaks.
What happens after that? Where does the control go in the code? Where is stack used? Please help me.
public class MergeSort {
private int[] numbers;
private int[] helper;

private int number;

public void sort(int[] values) {
    this.numbers = values;
    number = values.length;
    this.helper = new int[number];
    mergesort(0, number - 1);
}

private void mergesort(int low, int high) {
    // check if low is smaller than high, if not then the array is sorted
    if (low < high) {
        // Get the index of the element which is in the middle
        int middle = low + (high - low) / 2;
        // Sort the left side of the array
        mergesort(low, middle);
        // Sort the right side of the array
        mergesort(middle + 1, high);
        // Combine them both
        merge(low, middle, high);
    }
}

private void merge(int low, int middle, int high) {

    // Copy both parts into the helper array
    for (int i = low; i <= high; i++) {
        helper[i] = numbers[i];
    }

    int i = low;
    int j = middle + 1;
    int k = low;
    // Copy the smallest values from either the left or the right side back
    // to the original array
    while (i <= middle && j <= high) {
        if (helper[i] <= helper[j]) {
            numbers[k] = helper[i];
            i++;
        } else {
            numbers[k] = helper[j];
            j++;
        }
        k++;
    }
    // Copy the rest of the left side of the array into the target array
    while (i <= middle) {
        numbers[k] = helper[i];
        k++;
        i++;
    }

}

 public static void main(String[] args){
     int arr[] = {78,9,45,7,2,90};
     new MergeSort().sort(arr);
        for(int i = 0; i < arr.length;i++){
            System.out.print(arr[i] + "\t");
        }
 }

}

A: You could put else statement and observe that the executions are still done after low >= high. Here, these calls are just skipped.
        private void mergesort(int low, int high) {
    // check if low is smaller than high, if not then the array is sorted
     if (low < high) {
    // Get the index of the element which is in the middle
int middle = low + (high - low) / 2; // Sort the left side of the array mergesort(low, middle); // Sort the right side of the array
mergesort(middle + 1, high); // Combine them both
merge(low, middle, high); }

    else
    System.out.prinln("low is higher than high. Low is " +low+ "high is" +high);
     }

A: For top down merge sort, no merging occurs until two runs of size 1 are produced from the recursive splitting of an array. This will be the first instance where the mergesort() calls merge(). Then that instance of mergesort() returns to the prior instance of mergesort(), eventually reaching it's call to merge() and so on. The merge order is depth first / left first.
By contrast, a bottom up merge sort (most libraries use some variation of bottom up merge sort like timsort), skips the recursion and treats an array of n elements as n runs of size 1, and immediately starts merging the runs. The indices to the runs are generated iteratively (via loops).
This is an example of the order of operations for a top down merge sort, which is depth first, left first.
The vertical bars represent the split between left and right halves of the current array.
|4 2 8 6 0 5 1 7 3 9|
|4 2 8 6 0|5 1 7 3 9|
|4 2|8 6 0|
|4|2|
|2 4|
    |8|6 0|
      |6|0|
      |0 6|
    |0 6 8|
|0 2 4 6 8|
          |5 1|7 3 9|
          |5|1|
          |1 5|
              |7|3 9|
                |3|9|
                |3 9|
              |3 7 9|
          |1 3 5 7 9|
|0 1 2 3 4 5 6 7 8 9|

A: What happens is that every stacked method call is executed. If you represent graphically the stack you have the following in every step:
1.- bottom/top --> mergeSort(0, 5)

2.- top    --> mergeSort(0, 2)
    bottom --> mergeSort(0, 5)

3.- top    --> mergeSort(0, 1)
               mergeSort(0, 2)
    bottom --> mergeSort(0, 5)

4.- top    --> mergeSort(0, 0) --> breaks and go back
               mergeSort(0, 1)
               mergeSort(0, 2)
    bottom --> mergeSort(0, 5)

5.- top    --> mergeSort(0, 1) --> finish and continue with next line
               mergeSort(0, 2)
    bottom --> mergeSort(0, 5)

6.- top    --> mergeSort(2, 2) --> next line after mergeSort(0, 1)
               mergeSort(0, 2)
    bottom --> mergeSort(0, 5)

7.- etc.

With this first steps represented graphically, you can figure out the rest. Hope that helps


text:
Q: How to make a JSON object out of getAllResponseHeaders method I am currently writing a google chrome extension, and I need to find out information about websites' response headers. In order to do this, I used the getAllResponseHeaders method, but I need to put it in a JSON object. Unfortunately, I keep getting the error message SyntaxError: Unexpected token D in JSON at position 0 at main.
Here is the code I am using to do this so far:
xmlhttp.open("GET", url, false);
xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        allResponseHeaders = xmlhttp.getAllResponseHeaders();
    }
};
xmlhttp.send();

var responseHeaders = JSON.parse(allResponseHeaders);
obj.headers = responseHeaders;

When I put an alert immediately after the allResponseHeaders = xmlhttp.getAllResponseHeaders(); call, the alert shows that the call was a success; the response headers have all been retrieved. The first response header is the Date, which I think has to do with the Unexpected token D part of my error message, but I don't know why it won't parse properly. How do I fix this? Thanks in advance.
EDIT: I would like my JSON object to look something like this:
{
  "headers": {
    "Date": "June 20, 2016",
    "Content-Type": "charset=UTF/8",
    ...
  }
}

A: See https://msdn.microsoft.com/en-us/library/ms536428(v=vs.85).aspx. The return headers are a crlf delimited string where each line contains key values separated by a colon. You will probably have to adjust the code below to account for whitespace.
var arr = allResponseHeaders.split('\r\n');
var headers = arr.reduce(function (acc, current, i){
      var parts = current.split(': ');
      acc[parts[0]] = parts[1];
      return acc;
}, {});

A: I use the following function to extract all response headers as JS object using getAllResponseHeaders():
function getResponseHeaderMap(xhr) {
  const headers = {};
  xhr.getAllResponseHeaders()
      .trim()
      .split(/[\r\n]+/)
      .map(value => value.split(/: /))
      .forEach(keyValue => {
        headers[keyValue[0].trim()] = keyValue[1].trim();
      });
  return headers;
}

A: You should put JSON.parse logic inside the callback onreadystatechange, since Ajax is an asynchronous call and allResponseHeaders may not be initialized when you use it right after sending the http request.

A: Simplified version of the accepted answer and fixed issue reported by @Emrah Tuncel :

The first item of the return value is incorrect. { "": undefined }

// ES6:
const headers = request.getAllResponseHeaders().trim().split('\r\n').reduce((acc, current) => {
      const [x,v] = current.split(': ');
      return Object.assign(acc, { [x] : v });
}, {});


text:
Q: Narrowing down a bad test by running junit tests in various combinations using Maven or other tool I have 1000 junit tests and one "bad" test that is modifying a shared resource causing a subsequent test to fail. It passes if run alone.  I'm looking for a Maven plugin or Java application or tool that will take as input a test class name.  It will then run the 1000 tests in various combinations until it finds the "bad" test. Assume it is one "bad" test.

A: As you may noticed, writing dependant tests IS the problem ! Every solutions would be a workaround, maybe with side effectfs, complexity the first one.
Assuming you REALLY can't change that, you may have different strategies to solve your issue, but they are not necessary related to maven :
Ordering
Order your test to run the "bad one" at the end ... be carefull that you me affected again if you have a second bad test !

*

*User TestNG instead of JUnit and @Groups and @AfterGroups annotations to split your tests and run them as you want

*Use @AfterClass and BeforeClass with a test suite: Cleanup after all junit tests

*Manually describe a Test Suite (not sure if you can achieve what you want)

Provide good data

*

*Use setUp and tearDown methods to prepare and clean data in order to always have a stable environment, on each tests classes

*Rollback the test that modify you resource (pretty the same thing indeed)

Step back thoughts :
Just a piece of minds :

If you cannot run tests independently, they are not unit tests.