text:
Q: Scaling a node.js application, nginx as a base server, but varnish or redis for caching? I'm not close to being well versed in using nginx or varnish but this is my setup at the moment.
I have a node.js server running which is serving either json, html templates, or socket.io events. Then I have nginx running in front of node which is serving all static content (css, js, etc.).
At this point I would like to cache both static content and dynamic content to memory.
It's to my understanding that varnish can cache static content quite well and it wouldn't require touching my application code. I also think it's capable of caching dynamic content too but there cannot be any cookie headers?
I do use redis at the moment for holding session data and planned to use it for other things in the future like keeping track of non-crucial but fun stats.
I just have no idea how I should handle caching everything on the site. I think it comes down to these options but there might be more:

*

*Throw varnish in front of nginx and let varnish cache static pages, no app code changes. Redis would cache dynamic db calls which would require modifying my app code.

*Ignore using varnish completely and let redis handle caching everything, then use one of the nginx-redis modules. I'm not sure if this would require a lot of app code changes (for the static files).
I'm not having any luck finding benchmarks that compare nginx+varnish vs nginx+redis and I'm too inexperienced to bench it myself (high chances of my configs being awful).
I'm basically looking for the solution that would be the most efficient in terms of req/sec and scalable in the future (throw new hardware at the problem + maybe adjust some values in a config = new servers up and running semi-painlessly).

A: For the purely static content, you normally gain very little advantage by running Varnish in front of any mature web server such as nginx or Apache.  (I can't speak for node.js because I have not yet used it.)  The reason for this is that the kernel maintains a filesystem cache which stores recently accessed files in RAM.  It's possible that Varnish does a slightly better job than the kernel at choosing exactly which files to keep in the cache and which to eject but it's also possible that it does a worse job.  This will depend on what else your system does as well as the differences in the cache retention policies.  The extra latency caused by having a proxy in front of your web server will far exceed any differences between Varnish and kernel filesystem caching.
You are correct about Varnish not caching responses sent with a Set-Cookie: header.  It also skips looking at the cache if the request contains a Cookie: header.  The reason for this is that there will be one such unique response for each and every user who visits any given page and each user is unlikely to re-visit the same page meaning that your cache would be full of entities that will never be used.
Varnish can cache dynamic content and this is where it shines.  Let's say the front page of your website requires a PHP code compile and 20 database queries on cold caches.  On warm caches (APC, memcached, Redis, MySQL query cache, etc.) it still requires lookups to memcached/Redis and doing a stat() on every PHP file included in the request.  Assuming you have a reasonably well optimised site, this is still likely to be at least 1/10th of a second (and that's pretty well optimised; 1 - 3 whole seconds is far more common in my experience).  Varnish will happily serve the same page in under 1/1000th of a second.  But it means that your users can't be logged in on the front page of your website because they can't get their Cookie: headers but  if this is acceptable to you, Varnish is an easy win.
Varnish also requires correct caching headers.  If it isn't sure that it's safe to cache an object, it won't.  If you meet all these requirements, Varnish might be the tool for you.  That said, just putting the correct headers in place will cause the clients to cache the content themselves which can make a much larger difference than Varnish can.
If you lack the experience to benchmark your setup yourself, now is the time to get that experience.  You are benchmarking to gauge the appropriateness of your configs.  Try something and run ab over it, then change one thing and run ab in exactly the same way against that configuration.  Now you know which one is "better".  Rinse, repeat.  (Also, always run ab twice and ignore the first result.  This will make sure you only test warm caches and don't end up erroneously thinking one configuration is worse because it was tested against cold caches.)
Architecting a scalable solution for your website is a complex enough topic that it won't fit in a ServerFault answer.  We can certainly help with individual parts of that (such as "How do I scale out my memcached server to a memcached cluster?") when you run into those problems.
Further reading:
I wrote an answer a while ago that had a section on finding the bottleneck when benchmarking.
Womble recently pointed me at an excellent post on finding bottlenecks.


text:
Q: Magento 1 Admin panel a lot of problems please help We started to get a lot of problems in our magento admin back panel.
The problem is that we cannot enter to products and to some of extensions.
It simply loaded for several minutes and than going to nothing or to 504 time out gateway.
The guys of server says no any restrictions. "All ok from our side"
The sucuri guys ( we use sucuri) also says that "all ok from our side"
The front web is running excellent without any problem. Getting customers everyday no any issues with orders or checkout.
It simply not possible to make any change fron admin panel.
For example we installed the extension for google merchant feed. Also not possible to open it.
Some functions like "open customers, open orders, send tracking numbers are working without problem"
I asked from server guy to send the live error logs when I try to open any of products and see these errors

[Thu Feb 28 06:22:13.022649 2019] [autoindex:error] [pid 30938:tid
  47894805636864] [client 192.88.135.5:25599] AH01276: Cannot serve
  directory /home/sextoyzone/public_html/media/: No matching
  DirectoryIndex (index.php) found, and server-generated directory index
  forbidden by Options directive
[Thu Feb 28 05:59:02.148870 2019] [autoindex:error] [pid 16384:tid
  47894818244352] [client 192.88.135.5:3703] AH01276: Cannot serve
  directory /home/sextoyzone/public_html/media/: No matching
  DirectoryIndex (index.php) found, and server-generated directory index
  forbidden by Options directive
[Thu Feb 28 02:40:47.701871 2019] [autoindex:error] [pid 30791:tid
  47894826649344] [client 66.249.75.85:58755] AH01276: Cannot serve
  directory
  /home/sextoyzone/public_html/media/catalog/product/cache/1/image/x200/040ec09b1e35df139433887a97daa66f/2/3/:
  No matching DirectoryIndex (index.php) found, and server-generated
  directory index forbidden by Options directive
[Wed Feb 27 15:18:04.016345 2019] [:error] [pid 1727:tid
  47838238512896] [client 192.88.135.5:8492] client denied by server
  configuration:
  /home/sextoyzone/public_html/master-series-crimson-tied-embossed-ankle-cuffs.html
[Wed Feb 27 15:17:56.575693 2019] [:error] [pid 1727:tid
  47838236411648] [client 192.88.135.5:6122] client denied by server
  configuration: /home/sextoyzone/public_html/magebird_popup, referer:
  https://www.sextoyzone.com/sexual-enhancers/female-enhancers/orgasm-sensitivity.html

Any help will be appretiate. Feeling stupid that cannot change my own product on my own online store... Weird situation.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pass a value from a third activity to a first so I have a doubt, I have 3 activities, in the first one I send some data to the second one, and in the second one I send some data to the third one and finish the second one, is there a way I can finish the third activity and send some data to the first activity from the third?
This is what I'm doing in the first activity.
  mStartGame.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent i = new Intent(view.getContext(), GameInProgress.class);
            i.putExtra("questionObject", questions);
            startActivityForResult(i,DETAIL_REQUEST);
        }
    });

And in the second one after i get the extra I do this to send data to the third activity:
 Intent i = new Intent(view.getContext(), StatisticsActivity.class);
            i.putExtra("questionObject", questionInfo);
            startActivity(i);
            finish();

Now in the third I get the extras and then I:
Intent returnIntent = new Intent();
            isCorrect = true;
            returnIntent.putExtra("questionCorrection", isCorrect);
            setResult(RESULT_OK, returnIntent);
            finish();

I though this would work because when I finish the third activity the onActivityResult in the first activity method is working but when I try to access the Extras I get a nullpointerexception, so I don't know, thank you.

A: Sorry dude but I doubt your procedure of sending data from 3rd to 1st Activity.If data is simple string or integer. You can use  Shared Preference Follow link
How to use Shared preference
Edit Shared Preference
Why Don't you also finish First activity and start new Instance of same activity through intent?


text:
Q: jquery tabs change background picture when tab changes How can I change the panel's background picture, whenever a tab changes?
I need to change the .ui-tabs-panel css dynamically
I hve tried this but it seems to work only when the page is loaded, then the tabs panel goes back to the stylesheet value
$( "#mytabs" ).tabs({

     select: function(event, ui) {

        // Do your validation here
         $('.ui-tabs-panel').css('background-image','bo.jpg');

          /* */
    }

    });

});
Thanks

A: Thanks for not helping me, I have found the solution myself...
And I am posting it here for others that may need it:
 $( "#mytabs" ).tabs({

     select: function(event, ui) {

        // Do your validation here
         $('.ui-tabs-panel').css('background-image',"url('yourimage.jpg')");

          /* */
    }

    });


text:
Q: Installing Oracle 11g for 64bit on Ubuntu 10.04 server 64bit? I want to install Oracle 11g for 64bit on a Ubuntu 10.04 64bit server.Does anybody knows how to install the Oracle 11g on Ubuntu from the scratch(pre-installation to post-installation)?

A: Is this for development or personal use or for production? I'd review the release notes for Oracle to see if Ubuntu is supported, but further, I'd ask yourself why you want Oracle on Ubuntu. Nothing against Ubuntu but Oracle is a finicky beast an it is best not to stray too far from the supported platforms especially if this is a production setup. You may be better off biting the bullet and installing on RHEL or CentOS (not Fedora Core) because RHEL is supported and CentOS is known to work, being derived from RHEL sources. Again, while Ubuntu LTS may work nicely for 90% of your infrastructure, Oracle is very demanding - deviate from supported configurations at your peril.
Oracle's dependency checks are not for show. People run Oracle for two reasons - either they need the reliability and features of Oracle, or they're running it because someone else told them to (vendor, administrator, client, etc.) If you don't need it, don't use it because it's a severe pain for a neophyte to manage. If you do need it, you obviously have deep pockets - don't waste your time trying to get Oracle running on a desktop OS. Pay for RHEL or if you know what you're doing or don't care, use CentOS because it's as close a production OS for Oracle as you'll get without buying RHEL. I like Ubuntu too, but it's the wrong platform in this case.

A: I have both Oracle 10g release 2 and 11g running on my laptop Ubuntu 8.04 64-bit. I have following the phytian guide... What is the exact error you get during install?
BTW - some have suggested you install in a supported environment. If you want - create a new VM and install Oracle EL - a clone of RHEL, fully supported, fully free. I would just get the EL 5.3 from here.
BTW - if you use VirtualBox - the version in the Ubuntu 8.04 repository used to be old and didn't support 64-bit guests, so if you use VirtualBox and not VmWare, get the latest release from their site
----- EDIT -----
OK, I found my notes of the steps I took. I believe it is quite accurate.
Oracle Documentation talks about user "oracle" with groups "dba","oinstall". Since this is just a laptop, I used the default user/group (in my case, ofir/ofir), so change it to your
user.
PRE-INSTALL
as root run:
ln -s /usr/bin/basename /bin/basename
ln -s /usr/bin/awk /bin/awk
ln -s /usr/bin/rpm /bin/rpm
mkdir /etc/rc.d
ln -s /etc/rc0.d /etc/rc.d/rc0.d
ln -s /etc/rc2.d /etc/rc.d/rc2.d
ln -s /etc/rc3.d /etc/rc.d/rc3.d
ln -s /etc/rc4.d /etc/rc.d/rc4.d
ln -s /etc/rc5.d /etc/rc.d/rc5.d
ln -s /etc/rc6.d /etc/rc.d/rc6.d
ln -s /etc/init.d /etc/rc.d/init.d
add to /etc/sysctl.conf :
fs.file-max = 65535
kernel.shmall = 2097152
kernel.shmmax = 2147483648
kernel.shmmni = 4096
kernel.sem = 250 32000 100 128
net.ipv4.ip_local_port_range = 1024 65000
net.core.rmem_default = 1048576
net.core.rmem_max = 1048576
net.core.wmem_default = 262144
net.core.wmem_max = 262144
add to /etc/security/limits.conf (replace ofir with your username):
ofir soft nproc 2047
ofir hard nproc 16383
ofir soft nofile 1023
ofir hard nofile 65535
Add to /etc/pam.d/login :
session required /lib/security/pam_limits.so
session required pam_limits.so
sudo apt-get  install gcc make rpm libmotif3 libstdc++5 gawk alien  ksh gcc-3.3 g++-3.3 libstdc++5 libc6 libc6-dev gcc make binutils lesstif2 ++-multilib
INSTALLING
(I assume you have done it before, if not - just follow the GUI and cosult the docs):
run the 11.1.0.6 installer, choose software only install. Ignore a few minor link errors (there were no link errors after 11.1.0.7 patch)
If needed, install the 11.1.0.6 examples disk as well
Install the 11.1.0.7 (available from metalink)
run netca to create a new listener (accept all the defaults)
run dbca to create a new database (even the database console works great for me)

A: As a note... last time I installed Oracle, it depended on some binary packages that were 32bit, so I had to install the ia32-libs package ( aptitude install ia32-libs ) , for it to work...
Do you have any concrete problem?

A: Maybe you can take look here:
www.pythian.com/news/968/installing-oracle-11g-on-ubuntu-804-lts-hardy-heron
or
www.pythian.com/news/1355/installing-oracle-11gr1-on-ubuntu-810-intrepid-ibex

A: There are quite a few oracle-on-linux HOWTO documents on the web.  Do a google search for some keywords in this space - there's quite a good chance you will come up with relevant documents.

A: I spent about a week last fall pulling my hair out trying to get Oracle 10g installed on Ubuntu.  I finally gave up and switched to RedHat and had it up and running in one day.

A: I installed Oracle 10 on Debian, and it sometimes failed on "make"'ing some files. Basically, I simply had to read the log, do the "make" by hand with the needed changes (usually some mangled path) then click "ignore" in the installer. Hope this helps.

A: I like the response given by arclight answered Jun 1 '09 at 6:48
I have been trying to get oracle to work on various linux distros not supported but all have issues. I will try RHEL or Centos for optimum performance.


text:
Q: How to set chart legend's position (achartengine) My legend is running into my x axis values, I can't figure out how to fix it.
I already tried both
renderer.setFitLegend(true);

and
renderer.setLegendHeight(10);

Both of them just make the legend disappear and the latter one sometimes cuts my chart from the screen.
Here is how it currently looks:
Thanks

A: Try renderer.setMargins(new int[] { 50, 50, 25, 22 });


text:
Q: mongodb get sum of value within time period I am trying to find some records that has created within specific time period.
Then I want to calculate the sum of value of these record.
{"member_id":"3755","value":184607,"create_time":"2017-8-11 10:36:58"
{"member_id":"3234","value":74582,"create_time":"2017-8-11 10:36:58",
{"member_id":"4857","value":36776,"create_time":"2017-8-11 10:36:58",
{"member_id":"2042","value":15753,"create_time":"2017-8-11 10:36:58",
{"member_id":"1374","value":655103,"create_time":"2017-8-11 10:36:59"
{"member_id":"3777","value":595437,"create_time":"2017-8-11 10:36:59"
{"member_id":"5271","value":306364,"create_time":"2017-8-11 10:36:59"
{"member_id":"2143","value":164831,"create_time":"2017-8-11 10:36:59"
{"member_id":"1374","value":655103,"create_time":"2017-8-11 10:36:59"
{"member_id":"3777","value":595437,"create_time":"2017-8-11 10:36:59"
{"member_id":"5271","value":306364,"create_time":"2017-8-12 10:36:59"
{"member_id":"2143","value":164831,"create_time":"2017-8-12 11:28:59"
{"member_id":"3777","value":595437,"create_time":"2017-8-12 14:46:59"
{"member_id":"5271","value":306364,"create_time":"2017-8-13 11:36:59"
{"member_id":"2143","value":164831,"create_time":"2017-8-13 13:36:59"
...

Here are the code for getting the sum of value, how can I get the sum of value between 2017-8-11 10:36:00 and 2017-8-12 14:00:00
  connection.aggregate([{
                $match: match
            },
            {
                $group: {
                    _id: null,
                    total: {
                        $sum: "$value"
                    }
                }
            }
        ], function(err, result) {
            if (err) throw (err);
            result = {
                member_id: member_id,
                total: result[0].total,
            }
            cb(result);
        });

A: Don't store date as string. Store it with date format and Try below query
 db.connection.aggregate([{
        "$match" : { "create_time" : { "$gt" : new ISODate("2017-08-11T10:36:00.000Z"), "$lt" : new ISODate("2017-08-12T14:00:00.000Z") }},
        "$group" : { "_id": "$member_id", "total": { "$sum": 1 }}
    }])

A: let todayDate = new Date();
let beforeDate = new Date();
beforeDate.setDate(beforeDate.getDate() - 15); // 15 is days
db.collections.aggregate([
    {
        "$match":
            {
                "insertDate":
                    {
                        "$lte": todayDate,
                        "$gte": beforeDate
                    }
            }
    }
])
.exec()
.then((result) => {
    //result
})
.catch((err) => {
    // error
});


text:
Q: Doubts using Amazon S3 monthly calculator I'm using Amazon S3 to store videos and some audios (average size of 25 mb each) and users of my web and android app (so far) can access them with no problem but I want to know how much I'll pay later exceeding the free stage of S3 so I checked the S3 monthly calculator.
I saw that there is 5 fields:

*

*Storage: I put 3 gb cause right now there are 130 files (videos and audios)

*PUT/COPY/POST/LIST Requests: I put 15 cause I'll upload manually around 10-15 files each month

*GET/SELECT and Other Requests: I put 10000 cause a projection tells me that the users will watch/listen those files around 10000 times monthly

*Data Returned by S3 Select: I put 250 Gb (10000 x 25 mb)

*Data Scanned by S3 Select: I don't know what to put cause I don't need that amazon scans or analyze those files.

Am I using that calculator in a proper way?
What do I need to put in "Data Scanned by S3 Select"?
Can I put only zero?

A: For audio and video, you can definitely specify 0 for S3 Select -- both data scanned and data returned.
S3 Select is an optional feature that only works with certain types of text files -- like CSV and JSON -- where you make specific requests for S3 to scan through the files and return matching values, rather than you downloading the entire file and filtering it yourself.
This would not be used with audio or video files.
Also, don't overlook "Data transfer out."  In addition to the "get" requests, you're billed for bandwidth when files are downloaded, so this needs to show the total size of all the downloads. This line item is data downloaded from S3 via the Internet.


text:
Q: Unicode text confounding Mysql queries I have a PHP script that extracts attachments (Unicode text csv files) from gmail and uploads them to a mysql database.  All of that works fine.  But once in the database I cannot run the simplest of queries against the data.
If I first bring the file into Excel then export as a CSV file then all works fine, I can query and get the expected results.
I have done enough reading to understand (I think) that the issue is somehow related to the fact that Unicode text is either UTF8 or UTF16, but when I convert the table to either of those, the data comes in fine but I still cannot run a successful query.
Update:
I have an individual named White in the lastrep column of the data.  The only way I can pull the associated records is by using wild cards between characters, as in:
SELECT * FROM `dailyactual` WHERE `lastrep` like "%W%h%i%t%e%"

Any help would be appreciated.
Jim

A: Use the UTF8MB4 collation. Instructions https://dev.mysql.com/doc/refman/5.7/en/charset-unicode-upgrading.html

A: In utf8 or utf8mb4 character set, 'White' would be 'White' (hex 57 68 69 74 65).  In utf16, there would be (effectively) a zero byte between each character; hex: 0057 0068 0069 0074 0065.
Can you get a hex dump of part of the file?
If you can specify the output of excel, do so.  Else specify the input for mysql to be utf16 or whatever the encoding says.  Since there are many ways of bringing a csv file into mysql, I can't be more specific.


text:
Q: Finding shapes after merging together contours with opencv I would like to find specific shapes (circles and the triangles) in the following image there are:
Two triangles and two circles in different sizes

I have used the:
cv2.findContours(image=current_bw_img, mode=cv2.RETR_TREE, method=cv2.CHAIN_APPROX_NONE)

for getting all 8 contours.
Afterwards I have laid on each blank canvas a subset of contours since some of the contours are part of a recognizable shape, so this way I managed to get a recognizable shapes (triangles and circles).
I have done it in a non efficiently manner (2^8), have generated the whole powerset groups of contours even though there are contours which are disjointed, not adjacent to each other which should be ignored. I guess a more correct approach would be to find the nearby contours.
def check_all_combinations(current_bw_img, all_contours):
     contours_ids = range(len(all_contours))
     contours_combinations_id = list(powerset(contours_ids))
     for img_id, relevant_contours in enumerate(contours_combinations_id):
          shape_size = current_bw_img.shape
          img_blank_bw = np.ones((shape_size[0], shape_size[1], 1), np.uint8) * 255
          for cnt_id in relevant_contours:
                cv2.drawContours(image=img_blank_bw, contours=[all_contours[cnt_id]], contourIdx=0, color=0, thickness=-1)
                cv2.imshow(winname="img_blank_bw", mat=img_blank_bw)

          img_name = "img_" + str(img_id) + ".png"
          cv2.imwrite(filename=img_name,img=img_blank_bw)

For example I got this image (one image out of 256 subgroups) which is invalid, since they don't form a single shape (NOT adjacent contours)

Is there a much better approach?
I'll be glad to hear,
Thank you!!


text:
Q: Prove that $\sum_{n\geqslant 1} x^n/n$ is not uniformly convergent
Prove that $\displaystyle\sum_{n\geqslant 1} \frac{x^n}{n}$ is not uniformly convergent on $(-1,1)$ using the Uniform Cauchy Criterion.

The negation of Uniform Cauchy Criterion is the following: $$\exists \epsilon\, \forall N \,\exists x\in(-1,1)\,\exists n,m>N:\displaystyle\left\vert \sum_{k=m}^n \dfrac{x^k}{k}\right\vert\geqslant\epsilon.$$
I derived that
$$\sum_{k=m}^n \frac{x^k}{k}\leqslant \frac{1}{m}\sum_{k=m}^n x^k=\frac{1}{m}\frac{x^{m+1}-x^{n+1}}{1-x}.$$
How should I proceed? I always find it difficult to prove these things, since I need to pick an $\epsilon$ and pick an $x$ et cetera..

A: Assume that it were, then for some $N$, for all $x\in(-1,1)$ and $m\geq N$, we have
\begin{align*}
\left|\sum_{k=m}^{n}\dfrac{x^{k}}{k}\right|<\epsilon,
\end{align*}
taking $x\rightarrow 1^{-}$, we have
\begin{align*}
\sum_{k=m}^{n}\dfrac{1}{k}\leq\epsilon,~~~~m\geq N,
\end{align*}
this shows that $\left\{\displaystyle\sum_{k=1}^{n}\dfrac{1}{k}\right\}_{n=1}^{\infty}$ is Cauchy and hence convergent, a contradiction.

A: First, your last term in the UCC should be $\left\vert \sum_{k=m}^n \dfrac{x^k}{k}\right\vert\geqslant\epsilon$.
Hint 1: Try picking $n=2m$. You can do this because you need to find $m,n,x$.
Your problem boils to
$$\left\vert \sum_{k=m}^{2m} \dfrac{x^k}{k}\right\vert\geqslant\epsilon$$
Hint 2 Note that
$$\left\vert \sum_{k=m}^{2m} \dfrac{x^k}{k}\right\vert\geqslant \left\vert \sum_{k=m}^{2m} \dfrac{x^{2m}}{2m}\right\vert=\frac{x^{2m}}{2}$$
If you can make this greater than $\epsilon$ you are done.
Hint 3 Use that for a fixed $N$, if you pick any $m>N$, for this fixed $m$ you have
$$\lim_{x \to 1} \frac{x^{2m}}{2}=\frac{1}{2}$$
All you need to do is pick the right $\epsilon$, then for all $N$ fix some $m>N$, pick $n=2m$ and find the right $x$.


text:
Q: Expanding a list to a path I have a list like this:
 input = [[1,1], [3,3], [5,5], [7,7]]

I want this output:
[[[1,1],[3,3]],[[3,3],[5,5]],[[5,5],[7,7]]]

(The goal is to have the path made of edges [1,1]-[3,3], [3,3]-[5,5], [5,5]-[7,7]... I would not be surprised that this question is a duplicate by the way.)
I'am able to get this output like this:
> map (\i -> [input!!i, input!!(i+1)]) [0 .. length input-2]
[[[1,1],[3,3]],[[3,3],[5,5]],[[5,5],[7,7]]]

Do you have a cleaner solution? There's surely something cleaner.

A: You can zip input with its tail in order to get a list of tuples:
Prelude> zip input $ tail input
[([1,1],[3,3]),([3,3],[5,5]),([5,5],[7,7])]

From there, if you need it, you can write a function that makes a list out of each tuple, e.g.
tupleToList :: (t, t) -> [t]
tupleToList (x, y) = [x, y]

This enables you to map over the zipped list:
Prelude> fmap tupleToList $ zip input $ tail input
[[[1,1],[3,3]],[[3,3],[5,5]],[[5,5],[7,7]]]

Be aware that tail is unsafe, in that it throws an exception if the original list is empty.

A: let xs = [[1,1], [3,3], [5,5], [7,7]] in zipWith (\a b -> [a,b]) xs (tail xs)
-- [[[1,1],[3,3]],[[3,3],[5,5]],[[5,5],[7,7]]]


text:
Q: hide connection user password in memory in delphi TadoConnection I have made a sample application in Delphi xe10
and make user id and password and database name encrypted
and decrypt on connecting the problem is when I open exe process in memory by memory scanner I can find all of them easily by searching some part of the connection string
is it such easy to find secure connection data in win applications or I did something wrong?

A: Don't put the password in the connection string. Instead assign an OnWillConnect event handler to TADOConnection and supply the password there in the supplied parameter.

A: Try to protect the memory. Use CryptProtectMemory and CryptUnprotectMemory.
https://msdn.microsoft.com/de-de/library/windows/desktop/aa380262(v=vs.85).aspx
Here is an small snippet from my class. Play with it:
        uses
         Winapi.Windows,
          System.SysUtils;
        ....

TMyMemEncryptBlaBla = class
    private
    //......
     public
      function MemEncrypt(const StrInp: String; CryptFlags: DWORD = 0): TBytes;
      function MemDecrypt(const EncInp: TBytes; CryptFlags: DWORD = 0): String;
     end;

    {
 BOOL WINAPI CryptProtectMemory(_Inout_ LPVOID pData,
                                _In_    DWORD  cbData,
                                _In_    DWORD  dwFlags );

 }
function CryptProtectMemory(Data: Pointer; Size: DWORD; Flags: DWORD) : BOOL; stdcall;
 {
 BOOL WINAPI CryptUnprotectMemory(_Inout_ LPVOID pData,
                                  _In_    DWORD  cbData,
                                  _In_    DWORD  dwFlags );

 }

function CryptUnProtectMemory(Data: Pointer; Size : DWORD;Flags: DWORD) : BOOL; stdcall;

// CryptProtectMemory and CryptUnprotectMemory.

 CRYPTPROTECTMEMORY_SAME_PROCESS  = 0; // Set as default
 CRYPTPROTECTMEMORY_CROSS_PROCESS = 1;
 CRYPTPROTECTMEMORY_SAME_LOGON    = 2;
 CRYPTPROTECTMEMORY_BLOCK_SIZE = 16;

implementation

function CryptProtectMemory;  external 'Crypt32.dll' Name 'CryptProtectMemory';
function CryptUnProtectMemory; external 'Crypt32.dll' Name 'CryptUnprotectMemory';

// encrypt
function TMyMemEncryptBlaBla.MemEncrypt(const StrInp: String; CryptFlags: DWORD): TBytes;
begin
  Result := TEncoding.Unicode.GetBytes(StrInp);
  try
    if Length(Result) mod CRYPTPROTECTMEMORY_BLOCK_SIZE <> 0 then
      SetLength(Result, ((Length(Result) div CRYPTPROTECTMEMORY_BLOCK_SIZE) + 1) * CRYPTPROTECTMEMORY_BLOCK_SIZE);
  except
    on E:Exception do
     begin
      MessageBox(0, PChar(E.Message), PChar('E_OUTOFMEMORY'), MB_ICONERROR or MB_OK);
     end;
  end;
  try
     if not CryptProtectMemory(Result, Length(Result), CryptFlags) then
      begin
        MessageBox(0, PChar('MemCrypt: ' + SysErrorMessage(GetLastError)), PChar('MemEncrypt failed'), MB_ICONERROR or MB_OK);
        ZeroMemory(Result, Length(Result));
      end;
  except
    on E:Exception do
      begin
        MessageBox(0, PChar(E.Message), PChar('MemEncrypt Exception'), MB_ICONERROR or MB_OK);
      end;
  end;
end;
//decrypt
function TMyMemEncryptBlaBla.MemDecrypt(const EncInp: TBytes; CryptFlags: DWORD): String;
var
  DecTmp: TBytes;
begin
  DecTmp := Copy(EncInp);
  try
     if CryptUnprotectMemory(DecTmp, Length(DecTmp), CryptFlags) then
        Result := TEncoding.Unicode.GetString(DecTmp)
     else
        MessageBox(0, PChar('MemDecrypt: ' + SysErrorMessage(GetLastError)), PChar('MemDecrypt failed'), MB_ICONERROR or MB_OK);

      ZeroMemory(DecTmp, Length(DecTmp));
  except
    on E:Exception do
        MessageBox(0, PChar(E.Message), PChar('MemDecrypt Exception'), MB_ICONERROR or MB_OK);
  end;
end;

end.

Axel

A: Thinking out of box....
why you want hide  password?
If database is on user's computer, Then he/she can open database simply by windows authentication mode using SQL management studio with out password!
If Database is on a remote server sure it is better to write a web service that fetch  data and send result in XML for you program instead of remote opening database .


text:
Q: How can I create an empty 3d multidimensional array This code is my attempt at creating an empty 3d array.
n=3
board = [[[ 0 for _ in range(n)]
            for _ in range(n)]
            for _ in range(n)]
print(board)

So, what that creates is exactly what I'm looking for a 3d array with dimensions n by n by n, but the list is filled with 0's and if I take out the 0 an error occurs. How would I create this same list but empty?

A: You need to use [] instead of 0 as:
n = 5
empty_list = [[[ [] for _ in range(n)] for _ in range(n)] for _ in range(n)]

Value hold by empty_list will be:
[[[[], [], [], [], []],
  [[], [], [], [], []],
  [[], [], [], [], []],
  [[], [], [], [], []],
  [[], [], [], [], []]],
# Repeated 4 more times

For example:
>>> empty_list[0][0][0]  # Access element with nest level 3 in list
[]


text:
Q: How Paypal works in a failover I am working for a customer that has the following architecture:

*

*Back End

*

*Java Server

*Front End

*

*Proxy (Node JS + Express application)

All the requests that we make to the server needs to go through the Proxy (security feature).
We need to integrate Paypal API in our application, so we have created two actions for OK and KO callbacks (let's say /proxy/paymentOK and /proxy/paymentKO) that calls our server and update the status of a record.
Now is the time for our problems:

*

*Let's say that a user makes a payment. So, paypal will call our OK callback (/proxy/paymentOK). If a problem appears between proxy and server (for example, power or network failure), what happens with the payment? The payment will be returned to the customer automatically? How Paypal knows that everything goes fine after make the call?

*Before send  the paypal request I will persist some values, so I have an ID for a record with status PENDING_PAYMENT. Paypal needs to know this parameter, because whether payment accepts or rejects, I have to update the record with ACCEPTEDor REFUSED status. How can I send this ID to Paypal and how can a get it when Paypal makes the callback?
Thanks everyone!

A: The process goes like this:

*

*Create a payment
This just declare the detail about the transaction but does not engage the user into a payment. The payment can be edited as many time as you want until step 2. You will receive an ID and urls for this payment.

*User pay
You give the user the url for the transaction, user pay. You get notified (you should not trust the OK/KO callbacks, just the payment id).

*Approve payment
You check the payment status and if it's in pending state, you execute/approve it. The transaction is complete.
If you crash step 1, nothing to worries, the transaction did not even start. You can safely start another one.
If you crash step 2, when starting the server back you have all your payment Ids and should do the step 3 for every one of them.
If you crash step 3, you can safely redo it, paypal will informs you that this payment have been executed or not and gives you its status.
Notice: that even if you lost information, you can retrieve it at anytime. (List payments or get a payment informations)


text:
Q: Silent Hill 3 Puzzle Unsolvable I'm currently playing Silent Hill 3 on PS2 in normal difficulty and get stuck in a puzzle. The level is Dark Shopping Mall. I have to get rid of some flying bugs with poisonous chloride gas, which I have to mix with bleach and detergent. The problem is I didn't take the bleach in the women' bathroom early on and now I cannot return there. It is the room with the ladder from ceiling where the door won't open.

A: The return to the bathroom in which the bleach is located is in fact possible. After you jump in the room with the ladder from ceiling there is a door in front of you. This door is locked so you must go in the opposite direction. It is hard to spot but there is the door from which you went in to the room earlier. The game will not respawn new monsters so you can walk safely. Search for the bathroom and the bleach is there. There is another bathroom  2 floors above that one which looks more or less the same, but going there is pointless except for hiding from monsters


text:
Q: Any risk of breaking anaconda python when force upgrading packages using conda-forge? In my anaconda setup, some python packages like arrow in anaconda uses the pypi channel. However, these packages are not the latest version. The latest version is found in the conda-forge channel. For example, to upgrade to the latest version of arrow using conda-forge, I run the following command;
$ conda install -c conda-forge arrow

There should be some reason why the default channel is pypi and not conda-forge. So, will there be any risk of breaking anaconda packages if I were to force upgrade packages using conda-forge channel?
I installed anaconda 2018.12 which runs on Windows 10.

A: The safest thing to do is to make a new env
conda create -n myenv -c conda-forge arrow

The most dangerous thing to do, in my anecdotal experience of seeing people on StackOverflow with broken Conda installations, is to install things in base. Unfortunately, this is what many Anaconda users do, likely because Anaconda distributes with everything installed in base already.


text:
Q: Why do I get a String to System.SelectOption conversion error? I'm getting the following error when I click on the commandbutton in my Visualforce page:

EXCEPTION_THROWN [EXTERNAL]|System.TypeException: Invalid conversion
  from runtime type String to System.SelectOption

From an earlier question, I've learned that the setters in the controller get called with the view state before the action method gets called.
Here's the Visualforce column with the problem.  If I comment it out, I don't get the error.  I don't see why there would be a string to be converted in the set, but perhaps someone else here can see what I'm missing.
<apex:pageBlockTable value="{!ScholarList}" var="sl" id="table" rows="100">
...
<apex:pageBlockSectionItem >
<apex:commandButton action="{!removeSelectedNow}" value="Remove Selected Now" rerender="tablepanel,tableblock,table,panelMsg" id="theRemoveBtn"/><p/>
</apex:pageBlockSectionItem>
...
<apex:column headervalue="Reason Removed">
<apex:selectList size="1" value="{!sl.RemoveReason}">
<apex:selectOptions value="{!RemoveOptions}"/>
</apex:selectList>
</apex:column>apex:column>

Here's the Apex side:
//list of scholars for the controller/VF page
public List<SiteScholar> ScholarList {get; set;}
public List<SelectOption> RemoveOptions {get;set;}
...
//wrapper class to hold individual scholar info
public class SiteScholar {

public Boolean forWithdrawAction{get;set;}
public SelectOption RemoveReason {get;set;}
...
// method to load the selectoptions
public List<SelectOption> RemoveOptionsLoad(){
       List<SelectOption> options = new List<SelectOption>();
       options.add(new SelectOption('None','--None--'));
       Schema.DescribeFieldResult fieldResult = Scholar_Program_Application__c.Status_Change_Reason__c.getDescribe();
       List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
       for(Schema.PicklistEntry p : ple)
           options.add(new SelectOption(p.getValue(), p.getValue()));
       return options;
 }

The selectoptions appear in the VF page, but I see the conversion error listed above when I click the command button.

A: You should change
public SelectOption RemoveReason {get;set;}

to
public String RemoveReason {get;set;}

since the value of <apex:selectList>resolves to a String (it is independent of the <apex:selectOptions>)


text:
Q: WPF datagrid IsReadOnly exception I have a datagrid where i have added a Checkbox column. I want the entire datagrid to be IsReadOnly except the Checkbox column. I have tried:
  <DataGrid x:Name="DataGridView_Customer_Information" HorizontalAlignment="Left" Margin="10,200,0,0" VerticalAlignment="Top" Height="410" Width="697" CanUserAddRows="False" IsReadOnly="True" >
        <DataGrid.Columns>
            <DataGridCheckBoxColumn x:Name="CheckBoxSelectRow" IsReadOnly="False"/>
        </DataGrid.Columns>
    </DataGrid>

But i can imagine that <DataGridCheckBoxColumn x:Name="CheckBoxSelectRow" IsReadOnly="False"/> is overruled by the previous statement. Since its only one column that needs to be able to allow edit (allow to checkmark the checkbox) is it possible to make an expection in the IsReadOnly?
Thanks in advanced

A: You have two options.
Both assumes, that DataGrid.AutoGenerateColumns is False.

*

*Remove IsReadOnly="True" from DataGrid element and set IsReadOnly for each column: False for DataGridCheckBoxColumn, True for the rest of columns.

*Leave IsReadOnly="True" for DataGrid as is, and instead of DataGridCheckBoxColumn add DataGridTemplateColumn with CheckBox inside template:
<DataGrid IsReadOnly="True" AutoGenerateColumns="False" ItemsSource="{Binding Guests}">
    <DataGrid.Columns>
        <DataGridTemplateColumn Header="Is invited">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <CheckBox IsChecked="{Binding IsInvited}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>

        <DataGridTextColumn Header="Name" Binding="{Binding Name}" IsReadOnly="False"/>
    </DataGrid.Columns>
</DataGrid>

The second approach has another benefit. Default behavior of DataGridCheckBoxColumn is weird - to change check mark you need to select cell first, which is not convenient. CheckBox inside DataGridTemplateColumn accepts user input without selecting cell, and this looks natural.

A: You can set each other column IsReadOnly to false.
Update
Or you can add into DataGrid.Resources styles for other columns
<DataGrid.Resources>
    <Style TargetType="{x:Type DataGridTextColumn}">
        <Setter Property="IsReadOnly" Value="True" />
    </Style>
</DataGrid.Resources>


text:
Q: Merge multiple list comprehensions I have a list of dictionaries and I want to get the list of 2 of the keys in the list. Here is how I do it now:
l_id = [d['id1'] for d in l_data]
l_id.extend([d['id2'] for d in l_data])

Is there a pythonic way to do the list comprehension once and get the same result? (id order does not matter)

A: How about
l_id = [d[key] for key in ['id1', 'id2'] for d in l_data]

A: You can iterate over your dictionaries items in each iteration and check if the key is id1 or id2 then preserve the value :
[j for d in l_data for i,j in d.items() if i=='id1' or i=='id2']

As an alternative way you can also use operator.itemgetter with map function:
>>> data = [ {'id1':1, 'col1':'va1', 'id2':1001}, {'id1':2, 'col1':'va2', 'id2':1002}]
>>> map(itemgetter('id1','id2'),data)
[(1, 1001), (2, 1002)]

A: l_id = [d[key] for key in ('id1', 'id2') for d in l_data]

A: If you want all values of key id1, followed by all values of key id2, you can do it like this:
l_id = [ d[k] for k in ["id1", "id2"] for d in l_data if k in d ]

If you already know that every dictionary has all the IDs you need, you can skip the test (if k in d).


text:
Q: How to enable system title bar in Chrome to make it visible on every workspace? Starting two days ago (9/22/21) on both of my Kubuntu machines Chrome no longer displays system title bars and borders. The option in settings is enabled. Disable/re-enable/reboot hasn't fixed it. All other applications display this correctly.

My machines are both Kubuntu. lsb_release -a says Ubuntu 20.04.3 LTS. Chrome is 94.0.4606.61.
I've received no responses on the KDE-users list. On the Gentoo list the one person who responded said he also didn't have the system title bar but when he reenabled the feature and for him it works.
Using the system title bar allows Chrome to be pinned to all virtual desktops which I need for media. In the immediate term I'm using Firefox for that purpose but would prefer to use Chrome.
Thanks in advance.

A: Per Google this is a new issue from 94
From Reddit, here is a (temporary) quick fix:

*

*Ensure that "Use system title bar and borders" is set

*Go to chrome://flags

*Find the "use-ozone-platform" setting and change it from "default" to "disabled"

*Relaunch Chrome

A: Solution
Right click on the Chrome title bar, and check Use system title bars and borders (I tested this on Chromium in XFCE, but it should work on Chrome in KDE too).

 Before enabling title bar
Now the title bar is there, and you can make it visible in every workspace.

 After enabling title bar

Background
Chrome is a GTK app. Like most other GTK apps it switched to CSD (client side decoration) in the recently released version 94. Now it draws its own title bar, instead of using the title bar provided by KDE Plasma.

A: Google Chrome beta works OK so hopfully when it migrates to stable this fault will be gone.

A: My answer is specifically for KDE but I suspect other desktop environments has similar capabilities.
SystemSettings->Shortcuts->KWin->Keep Window on All Desktop
and program it to something. I chose Meta+a (Windows key and a for 'all')
It appears to work for all app and it's a toggle.


text:
Q: discord.py bot sends message each and finishes only when sending each words I'm new in this, it's really annoying that the bot would send each bad word one by one until it finishes. Here's the code.
@client.event
async def on_message(message):
  if message.author == client.user:
      return
  if message.author.bot:
      return

  with open('badwords.txt') as file:
    file = file.read().strip()

  for badwords in file:
    if badwords in message.content.lower():
       msg = await message.channel.send(f'{message.author.mention}Please avoid using malicious and insulting words in the future! words you used: {badwords}',delete_after=10)
       await msg.add_reaction('<a:cRight:819401530964836382>')
       await msg.add_reaction('<a:Heart:819401449095692309>')
       await msg.add_reaction('<a:cLeft:819403565440827423>')
       await message.channel.send('messages delete after 10 seconds',delete_after=5)
       guild = message.guild
       role = discord.utils.get(guild.roles, name="Muted")
       await message.author.add_roles(role)
       embed = discord.Embed(title="Muted!", description=f"{message.author.mention} Muted for 1 minute", colour=discord.Colour.blue())
       embed.add_field(name="reason",value=f"Badwords moderation, word that was used: {badwords}",inline=False)
       await message.channel.send(embed=embed,delete_after=300)
       await asyncio.sleep(60)
       await message.author.remove_roles(role)
       embed = discord.Embed(title="Unmuted", description=f"Unmuted - {message.author.mention} ", colour=discord.Colour.blue())
       await message.channel.send(embed=embed,delete_after=300)

  await client.process_commands(message)

I'm trying to make the bot send all the bad words in one message and as in the code,
the bot would send a message and mute, but it would repeat based on how many bad words there are in the message and would also repeat muting the user who used bad words in her/his message.
The code has no problems it works perfectly fine, I ask thee on changes to only make the bot send once no matter how many bad words in the message and to also list the bad words in the message that the bot sends.

In the image it would repeat until it finishes sending all words, and I am completely clueless on what should I add or change to make the bot compile each bad word and would send the embed and mute the user who used the bad word
(ignore this it seems like stack overflow keeps telling me to add details..... I'm filling it up)
I used the method open file in this code pls help and ps I'm new don't say I'm bad and I'm still 14 learning on coding :)
I would be really glad to someone who will help me :)

A: Your bot is sending multiple messages because your logic lives in the forloop, meaning that for each instance of a "bad word" your bot will execute the given instruction set.
One way to mitigate that is to construct a list of words that you want to warn users against using the forloop and then, send a single message which holds all of the context. For example:
  included_badwords = []
  for badwords in file:
    if badwords in message.content.lower():
       included_badwords.append(badwords)

  msg_content = '{0} Please avoid using malicious and insulting words in the future! words you used: {1}'.format(message.author.mention, ','.join(included_badwords))
  msg = await message.channel.send(msg_content, delete_after=10)
  await msg.add_reaction('<a:cRight:819401530964836382>')
  await msg.add_reaction('<a:Heart:819401449095692309>')
  await msg.add_reaction('<a:cLeft:819403565440827423>')
  await message.channel.send('messages delete after 10 seconds',delete_after=5)
  guild = message.guild
  role = discord.utils.get(guild.roles, name="Muted")
  await message.author.add_roles(role)
  embed = discord.Embed(title="Muted!", description=f"{message.author.mention} Muted for 1 minute", colour=discord.Colour.blue())
  embed.add_field(name="reason",value=f"Badwords moderation, word that was used: {badwords}",inline=False)
  await message.channel.send(embed=embed,delete_after=300)
  await asyncio.sleep(60)
  await message.author.remove_roles(role)
  embed = discord.Embed(title="Unmuted", description=f"Unmuted - {message.author.mention} ", colour=discord.Colour.blue())
  await message.channel.send(embed=embed,delete_after=300)

I'd also advise to load your wordlist into memory instead of reading from file every time a message comes in.
Hope this helps, feel free to ping me if you require further assistance.

A: If you loop through your badwords file and store all the used words in a list, you can then afterwards send a message with all the collected bad words.
Something like this:
@client.event
async def on_message(message):
  if message.author == client.user:
      return
  if message.author.bot:
      return

  with open('badwords.txt') as file:
    file = file.read().strip()

  found_words = list()

  for badword in file:
    if badword in message.content.lower():
      found_words.append(badword)

  msg_str = f'{message.author.mention}Please avoid using malicious and insulting words in the future! words you used: {", ".join(found_words)}'
  msg = await message.channel.send(msg_str,delete_after=10)
  await msg.add_reaction('<a:cRight:819401530964836382>')
  await msg.add_reaction('<a:Heart:819401449095692309>')
  await msg.add_reaction('<a:cLeft:819403565440827423>')
  await message.channel.send('messages delete after 10 seconds',delete_after=5)
  guild = message.guild
  role = discord.utils.get(guild.roles, name="Muted")
  await message.author.add_roles(role)
  embed = discord.Embed(title="Muted!", description=f"{message.author.mention} Muted for 1 minute", colour=discord.Colour.blue())
  embed.add_field(name="reason",value=f"Badwords moderation, word that was used: {", ".join(found_words)}",inline=False)
  await message.channel.send(embed=embed,delete_after=300)
  await asyncio.sleep(60)
  await message.author.remove_roles(role)
  embed = discord.Embed(title="Unmuted", description=f"Unmuted - {message.author.mention} ", colour=discord.Colour.blue())
  await message.channel.send(embed=embed,delete_after=300)

  await client.process_commands(message)

A: The for loop as it is checks one word at a time whether it is in the message, and if that is the case it shoots the whole procedure. Not optimal!
One simple improvement that addresses your specific problem could be
# first define an empty list where you can put eventual bad words used
badwords_list = []

# add words to the list if they appear
for badwords in file:
  if badwords in message.content.lower():
    badwords_list.append(badwords)

# assuming the list is not empty, join its content in a single string and send the message as you did before
if badwords_list:
  all_badwords = ','.join(badwords_list)
  msg = await message.channel.send(f'{message.author.mention}Please ... words you used: {all_badwords}',delete_after=10)

  [...etc etc etc...]

But the fact of going through all the words in the file like that... I think there might be some better solution


text:
Q: UITableView backgroundColor always gray on iPad When I set the backgroundColor for my UITableView it works fine on iPhone (device and simulator) but NOT on the iPad simulator. Instead I get a light gray background for any color I set including groupTableViewBackgroundColor.
Steps to reproduce:

*

*Create a new navigation-based project.

*Open RootViewController.xib and set the table view style to "Grouped".

*Add this responder to the RootViewController:- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor blackColor];
}

*Select Simulator SDK 3.2, build and run.

*You will get a black background (device and simulator).

*Select your target in the project tree.

*Click on Project : Upgrade Current Target for iPad.

*Build and run.

*You will get a light gray background.

*Revert the table view style to Plain and you will get a black background.

Thanks for your help!

A: On iPad the backgroundView property seems to be used to create the gray background color for grouped tables. So for changing the background color for grouped tables on iPad one should nil out the backgroundView property and then set the backgroundColor on the desired table view.
- (void)viewDidLoad
{
    [super viewDidLoad];

    // If you need to support iOS < 3.2, check for the availability of the
    // backgroundView property.
    if ([self.tableView respondsToSelector:@selector(setBackgroundView:)]) {
        self.tableView.backgroundView = nil;
    }
    self.tableView.backgroundColor = [UIColor whiteColor];
}

A: Thanks a lot for this solution.
I applied this on a UITableView property with IBOutlet in a UIViewController and it works well like:
[panelTable setBackgroundView:nil];
[panelTable setBackgroundView:[[[UIView alloc] init] autorelease]];
[panelTable setBackgroundColor:UIColor.clearColor]; // Make the table view transparent

A: Try one of these.
[myTableView setBackgroundView:nil];
[myTableView setBackgroundView:[[[UIView alloc] init] autorelease]];

A: I think it is worth noting that as of Xcode 6.1 and iOS 8.1, specifically for iPad (if you want to set cell background as well) it seems that you must set table background AND cell background.
For instance, on an iPhone storyboard you can set a cell to clear color, then set background image of table programmatically for a transparent table with background image.  However if you were to view this same configuration on iPad the cells would not be clear.  Cells will need to be set to clear programmatically for iPad.

A: tried setting backgroundColor and View for the table, had no luck (Xcode 5 iOS7.1 iPad simulator), looked OK for iPhone, but light grey background color on iPad...
working with backgroundColor for the cell itself fixed this for me on iOS 7.1  4/2014
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

        static NSString *CellIdentifier = @"ViewSomeTriggerCell";

        // get a cell or a recycled cell
        sictVCViewSomeTriggerCell *cellTrigger = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

        // put a picture and a word in the cell (positions set in .xib)
        NSString * tname = [self.fetchedTriggersArray objectAtIndex:indexPath.row];
        cellTrigger.imageTrigger.image = [UIImage imageNamed:@"icon_appicon.png"];
        cellTrigger.labelName.text = tname;

        // set background color, defeats iPad wierdness
        // http://stackoverflow.com/questions/2688007/uitableview-backgroundcolor-always-gray-on-ipad

        // clearColor is what I wanted, and it worked, also tested with purpleColor
        cellTrigger.backgroundColor =[UIColor clearColor];
        return cellTrigger;

}

A: If your application targets both iPhone and iPad you can do it like this:
[myTableView setBackgroundColor:[UIColor clearColor]]; // this is for iPhone

if ([[UIDevice currentDevice] userInterfaceIdiom] != UIUserInterfaceIdiomPhone) {
    [myTableView setBackgroundView:nil];
    [myTableView setBackgroundView:[[UIView alloc] init]];
} // this is for iPad only

Notice that the TableView alloc doesn't have autorelease for ARC.

A: If you are adding a UIViewController to another UIViewController you also need to set your view's background to clearColor in addition to UITableView or else you will get a white background instead of light grey.
if ([myViewController.myTableView respondsToSelector:@selector(setBackgroundView:)]) {
    [myViewController.myTableView setBackgroundView:nil];
}
myViewController.myTableView.backgroundColor = [UIColor clearColor];
myViewController.view.backgroundColor = [UIColor clearColor];

A: *

*Simulating iPad 2

*Running iOS 7.1 through 8.3

*Built from XCode 6.3

None of the above worked for my UIViewController->UITableView specified using a single XIB. What did work was moving the whole setup into a Storyboard, and setting the background color using the IB inspector.

A: I also got this kind of problem. The UITableView background color will be always groupTableViewBackgroundColor no matter what I set.
The symptom is like this issue - UITableView is resetting its background color before view appears
After I set the background color in init function, it is correct. In viewDidLoad and viewWillAppear stage, it is correct. However, in viewDidAppear, the background color is reset to its default color.
The accepted answer does not work now.
[myTableView setBackgroundView:nil];
[myTableView setBackgroundView:[[UIView alloc] init]];

Here is my solution. Just set the tableView's background color in viewDidLoad function rather than init or viewWillAppear.
- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.backgroundColor = [UIColor clearColor];
}


text:
Q: Output a map collection in facelets JSF 2 I have seen a couple other examples on SO discussing some weird workarounds but none seem to work and they were all addressed at versions prior to JSF 2. So, it it possible to simply output the keys of a map? I've tried ui:repeat and c:forEach like below with no luck:
<c:forEach items="${myBean.myMap.keySet}" var="var">
   <h:outputText value="#{var}"/>
</c:forEach>

A: From your code:
<c:forEach items="${myBean.myMap.keySet}" var="var">

This is not going to work. This requires a getKeySet() method on the Map interface, but there is none.
If your environment supports EL 2.2 (Servlet 3.0 containers like Tomcat 7, Glassfish 3, etc), then you should invoke the keySet() method directly instead of calling it as a property:
<c:forEach items="#{myBean.myMap.keySet()}" var="key">
    <h:outputText value="#{key}"/>
</c:forEach>

Or if your environment doesn't support EL 2.2 yet, then you should iterate over the map itself directly which gives a Map.Entry instance on every iteration which in turn has a getKey() method, so this should do as well:
<c:forEach items="#{myBean.myMap}" var="entry">
    <h:outputText value="#{entry.key}"/>
</c:forEach>

None of above works with <ui:repeat> as it doesn't support Map nor Set. It supports List and array only. The difference between <c:forEach> and <ui:repeat> is by the way that the <c:forEach> generates multiple JSF components during view build time and that the <ui:repeat> creates a single JSF component which generates its HTML output multiple times during view render time.

A: It turns out the correct syntax to output map keys is:
<ui:repeat value="#{myBean.myMap().keySet().toArray()}" var="var">
   <h:outputText value="#{var}"/><br/>
</ui:repeat>


text:
Q: Insert elements in an empty matrix python using FOR loop I am trying to do matrix multiplication. First i created  an empty matrix C and then using for loop I am trying to do matrix multiplication and assign the results to matrix C.
# Matrix Multiplication
A = [[1, 2] , [3, 4]]
B = [[2, 3] , [2, 1]]
n = len(A) # No. of rows
j = len(A[0]) # No. of columns
C =[[]]
for i in range(len(A)):
    for j in range(len(A[0])):
        C[i][j] = 0
        for k in range(len(A)):
            C[i][j] = C[i][j] + A[i][k] * B[k][j]
print(C)

I am getting the error "list assignment index out of range".

A: You need to create C which has the number of rows same with A's and the number of columns same as B's.
# Matrix Multiplication
A = [[1, 2] , [3, 4]]
B = [[2, 3] , [2, 1]]
n = len(A) # No. of rows
j = len(A[0]) # No. of columns
C =[[0 for j in range(len(B[0]))] for i in range(len(A))]
for i in range(len(A)):
    for j in range(len(A[0])):
        for k in range(len(A)):
            C[i][j] = C[i][j] + A[i][k] * B[k][j]
print(C)

Output
[[6, 5], [14, 13]]

The matrix multiplication can be done via
import numpy as np
A = np.array([[1, 2] , [3, 4]])
B = np.array([[2, 3] , [2, 1]])
np.dot(A,B)


text:
Q: Antlr3 - Non Greedy Double Quoted String with Escaped Double Quote The following Antlr3 Grammar file doesn't cater for escaped double quotes as part of the STRING lexer rule.  Any ideas why?
Expressions working:

*

*\"hello\"

*ref(\"hello\",\"hello\")

Expressions NOT working:

*

*\"h\"e\"l\"l\"o\"

*ref(\"hello\", \"hel\"lo\")

Antlr3 grammar file runnable in AntlrWorks:
grammar Grammar;

options
{
    output=AST;
    ASTLabelType=CommonTree;
    language=CSharp3;
}

public oaExpression
   : exponentiationExpression EOF!
   ;

exponentiationExpression
    :       equalityExpression ( '^' equalityExpression )*
    ;

equalityExpression
    :       relationalExpression ( ( ('==' | '=' ) | ('!=' | '<>' ) ) relationalExpression )*
    ;

relationalExpression
    :       additiveExpression ( ( '>' | '>=' | '<' | '<=' ) additiveExpression )*
    ;

additiveExpression
    :       multiplicativeExpression ( ( '+' | '-' ) multiplicativeExpression )*
    ;

multiplicativeExpression
    :       primaryExpression ( ( '*' | '/' ) primaryExpression )*
    ;

primaryExpression
    :       '(' exponentiationExpression ')' | value | identifier (arguments )?
    ;

value
    :       STRING
    ;

identifier
    :       ID
    ;

expressionList
    :       exponentiationExpression ( ',' exponentiationExpression )*
    ;

arguments
    :       '(' ( expressionList )? ')'
    ;

/*
 * Lexer rules
 */

ID
    :       LETTER (LETTER | DIGIT)*
    ;

STRING
    :       '"' ( options { greedy=false; } : ~'"' )* '"'
    ;

WS
    :       (' '|'\r'|'\t'|'\u000C'|'\n') {$channel=Hidden;}
    ;

/*
 * Fragment Lexer rules
 */

fragment
LETTER
    :       'a'..'z'
    |       'A'..'Z'
    |       '_'
    ;

fragment
EXPONENT
    :       ('e'|'E') ('+'|'-')? ( DIGIT )+
    ;

fragment
HEX_DIGIT
    :       ( DIGIT |'a'..'f'|'A'..'F')
    ;

fragment
DIGIT
    :       '0'..'9'
    ;

A: Try this:
STRING
 : '"'                          // a opening quote
   (                            // start group
     '\\' ~('\r' | '\n')        // an escaped char other than a line break char
     |                          // OR
     ~('\\' | '"'| '\r' | '\n') // any char other than '"', '\' and line breaks
   )*                           // end group and repeat zero or more times
   '"'                          // the closing quote
 ;

When I test the 4 different test cases from your comment:
"\"hello\""
"ref(\"hello\",\"hello\")"
"\"h\"e\"l\"l\"o\""
"ref(\"hello\", \"hel\"lo\")"

with the lexer rule I suggested:
grammar T;

parse
 : string+ EOF
 ;

string
 : STRING
 ;

STRING
 : '"' ('\\' ~('\r' | '\n') | ~('\\' | '"'| '\r' | '\n'))* '"'
 ;

SPACE
 : (' ' | '\t' | '\r' | '\n')+ {skip();}
 ;

ANTLRWorks' debugger produces the following parse tree:

In other words: it works just fine (on my machine :)).
EDIT II
And I've also used your grammar (making some small changes to make it Java compatible) where I replaced the incorrect STRING rule into the one I suggested:
oaExpression
   :        STRING+ EOF!
   //: exponentiationExpression EOF!
   ;

exponentiationExpression
    :       equalityExpression ( '^' equalityExpression )*
    ;

equalityExpression
    :       relationalExpression ( ( ('==' | '=' ) | ('!=' | '<>' ) ) relationalExpression )*
    ;

relationalExpression
    :       additiveExpression ( ( '>' | '>=' | '<' | '<=' ) additiveExpression )*
    ;

additiveExpression
    :       multiplicativeExpression ( ( '+' | '-' ) multiplicativeExpression )*
    ;

multiplicativeExpression
    :       primaryExpression ( ( '*' | '/' ) primaryExpression )*
    ;

primaryExpression
    :       '(' exponentiationExpression ')' | value | identifier (arguments )?
    ;

value
    :       STRING
    ;

identifier
    :       ID
    ;

expressionList
    :       exponentiationExpression ( ',' exponentiationExpression )*
    ;

arguments
    :       '(' ( expressionList )? ')'
    ;

/*
 * Lexer rules
 */

ID
    :       LETTER (LETTER | DIGIT)*
    ;

//STRING
//    :       '"' ( options { greedy=false; } : ~'"' )* '"'
//    ;
STRING
    :       '"' ('\\' ~('\r' | '\n') | ~('\\' | '"'| '\r' | '\n'))* '"'
    ;

WS
    :       (' '|'\r'|'\t'|'\u000C'|'\n') {$channel=HIDDEN;} /*{$channel=Hidden;}*/
    ;

/*
 * Fragment Lexer rules
 */

fragment
LETTER
    :       'a'..'z'
    |       'A'..'Z'
    |       '_'
    ;

fragment
EXPONENT
    :       ('e'|'E') ('+'|'-')? ( DIGIT )+
    ;

fragment
HEX_DIGIT
    :       ( DIGIT |'a'..'f'|'A'..'F')
    ;

fragment
DIGIT
    :       '0'..'9'
    ;

which parses the input from my previous example in an identical parse tree.

A: This is how I do this with strings that can contain escape sequences (not just \" but any):
DOUBLE_QUOTED_TEXT
@init { int escape_count = 0; }:
    DOUBLE_QUOTE
    (
        DOUBLE_QUOTE DOUBLE_QUOTE { escape_count++; }
        | ESCAPE_OPERATOR .  { escape_count++; }
        | ~(DOUBLE_QUOTE | ESCAPE_OPERATOR)
    )*
    DOUBLE_QUOTE
    { EMIT(); LTOKEN->user1 = escape_count; }
;

The rule additionally counts the escapes and stores them in the token. This allows the receiver to quickly see if it needs to do anything with the string (if user1 > 0). If you don't need that remove the @init part and the actions.


text:
Q: How to clear specific cookies using Flask I create cookies with Java Script and refresh the page like so...
document.cookie = "driveValue=" + "Runner"
document.cookie = "cachedOffset=" + "56"
location.reload()

I then retrieve a dictionary of the cookies with Python Flask showed below...
@app.route('/config', methods=('GET', 'POST'))
def config():
cookie = request.cookies
cookieItems = cookie.items()

Now that I have a dictionary mapping the name to the values, i want to clear those specific cookies (or change the value to an empty string). How do I go about doing this. So far, I have tried this example listed below...
resp = make_response(render_template('master.html', form=form, cookieItems=cookieItems)
resp.set_cookie("cachedOffset", "", expires=0)
resp.set_cookie("driveValue", "", expires=0)
return resp

I thought this would work but it is not changing any of the cookies to an empty space.
Here is where the cookies are located that I would like to change.


text:
Q: MKCoordinateRegion setRegion issue I used this code for iPhone iOS 5.0 device. And everything was OK:
self.mapView = [[[MKMapView alloc]init] autorelease];
mapView.delegate = self;
mapView.frame = CGRectMake(0, 0, 320, 414);
[myView addSubview:mapView];
MKCoordinateRegion zoomRegion = MKCoordinateRegionForMapRect(MKMapRectWorld);
MKCoordinateRegion adjustedRegion = [mapView regionThatFits:zoomRegion];
[mapView setRegion:adjustedRegion animated:NO];

Then I tried it on iPhone 6.0, and it crashes at the string [mapView setRegion:adjustedRegion animated:NO];
    *** Terminating app due to uncaught exception 'NSInvalidArgumentException',
 reason: 'Invalid Region <center:+0.00000000, +0.00000000 span:+176.06470039, +360.00004292>'

What should I change in my code?

A: I think you have to set latitude span and longitude span before setRegion like this,,,,
MKCoordinateRegion zoomRegion = MKCoordinateRegionForMapRect(MKMapRectWorld);

MKCoordinateRegion adjustedRegion;
adjustedRegion.center = self.mapView.userLocation.coordinate;
adjustedRegion.span.latitudeDelta = 0.01;
adjustedRegion.span.longitudeDelta = 0.01;
adjustedRegion = [mapView regionThatFits:zoomRegion];
[mapView setRegion:adjustedRegion animated:NO];

A: EDIT
In your case [mapView regionThatFits:zoomRegion]; it create issues.. remove it :
MKCoordinateRegion zoomRegion = MKCoordinateRegionForMapRect(MKMapRectWorld);
   // MKCoordinateRegion adjustedRegion = [self.mapView regionThatFits:zoomRegion];
    [self.mapView setRegion:zoomRegion animated:NO];


text:
Q: Flyway - EmbeddedMysql failing - SpringBoot Junits When I am running JUnits, those are executing fine in local but failing in Jenkins Pipeline with below error:
SQL State  : 08001
Error Code : 0
Message    : Could not create connection to database server. Attempted reconnect 3 times. Giving up.

Below are pom.xml dependencies:
    <!-- https://mvnrepository.com/artifact/com.wix/wix-embedded-mysql -->
            <dependency>
                <groupId>com.wix</groupId>
                <artifactId>wix-embedded-mysql</artifactId>
                <version>4.6.1</version>
                <scope>test</scope>
            </dependency>

<!-- https://mvnrepository.com/artifact/org.flywaydb/flyway-core -->
        <dependency>
            <groupId>org.flywaydb</groupId>
            <artifactId>flyway-core</artifactId>
        </dependency>

Properties of MySQL:
spring.jpa.database=mysql
spring.datasource.url=jdbc:mysql://localhost:2205/?autoReconnect=true&useSSL=false
spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

spring.main.allow-bean-definition-overriding=true

# HIBERNATE
spring.jpa.properties.hibernate.proc.param_null_passing=true
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

# FLYWAY
spring.flyway.enabled=true
spring.flyway.schemas=test

Can anyone please suggest why it failing with above error message when running Junits in Jenkins pipeline?


text:
Q: Find partial name matches between two columns Column A

Camisi, Terry
Goodman, Harris
Kostin, Heidi
Malachi, Lorrie

Column B

Terry
Harris
Lorri
Heidi

I'd like to create a formula that looks for a partial match of a name in two columns (Column A and Column B) in the same sheet, and if there is a partial match between the two names, it returns the value of Column B in Column C. Pls note, names are not in sequence.
@Harun24HR, Please see modified question below:
Column A (Last Name, First Name)
Camisi, Terry
Goodman, Harris
Kostin, Heidi
Malachi, Lorrie

Column B (Last Name)
Goodman
Malachi
Kostin
Camisi

Column C (First Name)
Harris
Lorri
Heidi
Terry

I have three columns, I need to compare Column A vs. Column B & C to find a partial match. If there's a match Name from Column A should be visible in Column D. Please advise. Thx

A: You can try MATCH() function with wildcard matching.
=INDEX($B$1:$B$4,MATCH("*"&B1&"*",$A$1:$A$4,0))

Or below one
=IF(ISNUMBER(MATCH("*"&B1&"*",$A$1:$A$4,0)),B1,"")


text:
Q: Parse Migration Issue I have lost my data base because I am not able to migrate parse database.
Please give us suggestions. Is it able to get my database from parse server ?
I was pay for it.I have not any back up of my database.

A: If you didn't migrate before the end of January, and you don't have any backups, all your data is probably lost.
You can try emailing the Parse.com migration team at migration@parse.com. But as you had a year to migrate,  I doubt they will be able to help, even if they have backups.


text:
Q: Customizing Spacy's Text Categorizer I am trying to to train a spacy model with a small dataset in Spacy 2.2. It is overfitting, I want to customize the architecture of the TextCategorizer. I referred to this post on GitHub :
https://github.com/explosion/spaCy/issues/3320
However, I am unable
from spacy.pipeline import TextCategorizer
from thinc.api import layerize
from spacy.language import Language

class StupidTextCategorizer(TextCategorizer):
    name = 'stupid_textcat'
    @classmethod

    def Model(cls, nr_class, **cfg):
        return create_dummy_model(nr_class, cfg.get('preferred_class', 0))

def create_dummy_model(nr_class, preferred_class):
    """Create a Thinc model that always predicts the same class."""
    def dummy_model(docs, drop=0.):
        scores = model.ops.allocate((len(docs), nr_class))
        scores[:, preferred_class] = 1.0
        return scores

    model = layerize(dummy_model)
    return model

However, when I'm trying to pass it to my training script, it throws this error which I can't seem to understand.
"[E002] Can't find factory for 'stupid_textcat'. This usually happens when spaCy calls `nlp.create_pipe` with a component name that's not built in - for example, when constructing the pipeline from a model's meta.json. If you're using a custom component, you can write to `Language.factories['stupid_textcat']` or remove it from the model meta and add it via `nlp.add_pipe` instead."

PS : Still learning Spacy but I can't find any helping documentation or tutorial for the above.


text:
Q: Front end printing emulator `paper.css` not working with background color I am using a solution, called paper.css, to emulate a printed text which is type-set in html using these css rules.
I noticed that when I create an element with background-color, and then use my Chromium Print menu to "Save as PDF", the background color becomes white, just like the whole page.
How one can print the html file to pdf and still keep the background color?
A MMW, based on the A4 example in the project's repository, is this:

<!DOCTYPE html>

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/paper-css/0.4.1/paper.css">

This is an A4 document.

Compare with the printed PDF:

A: Make sure you have the More settings > Options > Background graphics option checked in the Chrome print dialog.


text:
Q: Twilio MMS wont send video. I keep getting error Error - 11200 I am linking this file for my media URL:
my goal is for this to be sent as a MMS. I first had a file size error. I fixed that, now I am stuck with this error.
The video will play on my browser. But not on my phone, but it will play on my laptop.
Does anyone have any ideas what I might be doing wrong?

HTTP retrieval failure: Attempt to retrieve media failed. Possible
Causes Web server returned a 4xx or 5xx HTTP response to Twilio
Misconfigured Web Server Network disruptions between Twilio and your
web server No Content-Type header attached to response Content-Type
doesn't match actual content, e.g. an MP3 file that is being served
with Content-Type: audio/x-wav, instead of Content-Type: audio/mpeg
Possible Solutions Double check that your TwiML URL does not return a
4xx or 5xx error Make certain that the URL does not perform a 302
redirect to an invalid URL Confirm the URL requested is not protected
by HTTP Auth Make sure your web server allows HTTP POST requests to
static resources (if the URL refers to .xml or .html files) Verify
your web server is up and responsive Check to see that the URL host is
not a private or local IP address Verify the ping times and packet
loss between your web server and www.twilio.com
Error Description There was a failure attempting to retrieve the
contents of this URL. An 11200 error is an indicator of a connection
failure between Twilio and your service. When Twilio requests a page
from your server, we wait a maximum of 15 seconds for a response. A
connection failure will occur if no response is returned in that time.
There are many reasons a connection timeout can occur; common causes
are long running database queries or outside processes and calls to
external systems taking a long time to return. It may be possible your
application experienced one of these issues. If you are encountering
this error only intermittently, it is possible that your web server
was temporarily unavailable or experiencing a network outage. 502 Bad
Gateway errors If your debugger is reporting a 502 Bad Gateway error,
this may mean that Twilio's internal server had trouble retrieving
content from your website. Your request must contain a Content-Type
that is valid. Twilio may also have had problems resolving your DNS
name to an IP address, or issues with the network connection. Check
that your web server is started, and is available over the public
Internet.
Request Inspector
+ Expand All
GET https://meetlete.com/media/small-met.mp4 2021-02-21 05:05:07 UTC404 Request URL Parameters Message TextShow Raw
Msg   "Attempt to retrieve media failed."
httpResponse  "404"
EmailNotification "false"
url   "https://meetlete.com/media/small-met.mp4"
LogLevel  "ERROR"

A: Twilio developer evangelist here.
It might be the case that Twilio cached a 404 response to your video at some point.  I just tried sending a media message using your URL and it was processed correctly and the video was ingested by Twilio.
I would advise you try again. If you still find that your account has cached the URL response, you could try moving the video to a different address and trying with that instead.


text:
Q: Search text file to see if string is present I am very new to programing so I apologize in advanced.
So I am trying to create a Win App to make copying files using Robocopy easier and eventually other tasks. Basically what I have so far is a Button that calls the Sub Robcopy_EXE. There is a tab on the form with 100 check boxes, one for each terminal, that will be designated by the user and a check box to determine if you want a detailed report or not from Robocopy. I also have a text box for the user to input the first 3 octets of the site IP Address. The check boxes and Input field are used to create string "Terminal_input" which is what runs Robocopy in CMD. Robocopy logs its progress to a text file that I have labeled "Status.txt". That is as far as I have gotten.
At this moment I need to know when the the current running update is done to progress to the the next terminal. I am trying to continuously read the "Status.txt" file and look for the word "ENDED" to progress to the next terminal. If the word "ENDED" is not present I want to update LABEL3 to "Updating Terminal"
Ultimately I would like to have a way of making the checkbox# a variable that increments as it progresses through each checkbox#, but I will mess with that after I figure out how to check for 1 terminal to be completed.
Like I said I'm new to programing and I am having a lot of fun figuring this out, but I am very stumped on this procedure and I am going about it the worst way possible :D
Thanks in advanced.
   Private Sub RoboCopy_EXE()
        Dim Robocopystart = "Robocopy C:\wtg\update \\"
        Dim Robocopymid = IP_Input.Text
        Dim Robocopyend = ".42\c$\wtg /E /copy:datsou /r:3 /w:20 /log+:status.txt /tee /ns /nc /nfl /"
        Dim Terminal_Input = Robocopystart + Robocopymid + Robocopyend
        If CheckBox10.Checked Then
            If RoboCopy_Detailed_Progress.Checked = True Then
                Shell("CMD.exe", vbNormalFocus)
                Threading.Thread.Sleep(400)
                SendKeys.SendWait(Terminal_Input)
                Label3.Text = items
            Else : RoboCopy_Detailed_Progress.Checked = False
                Shell("CMD.exe", vbNormalFocus)
                Threading.Thread.Sleep(500)
                SendKeys.Send("Test2")
            End If
        End If
    End Sub

A: There could be probably better ways (and even way betters!) to do this. But for the sake of easy things, you should read about a timer control, and execute it once a second, and check the status of the file. and read the last line and compare it with the one you are looking for.

A: How big are these log files? You could do something along the lines of
While true
    Dim sr as new StreamReader(fileName)
    Dim contents as String = sr.ReadToEnd()
    sr.Close
    ForEach(string line in contents)
        if (line = "ENDED") then
            exit While
        Endif
    Next
    Thread.Sleep(1000)
Loop

(forgive any syntax errors, written off the top of my head and I'm mainly C# these days)
Although you should probably beef that up with some error handling and a way out of the loop so it doesn't loop forever (if it goes 100 times exit with error?).
Additionally, you should put all that on a BackGroundWorker so it doesn't lock the UI (you will find updating labels and such problematic otherwise).
Finally, instead of 100 checkboxes (yuck!), perhaps a dynamically generated listbox with checked items, or a DataGridView with similar? You could just iterate through the checked items that way.


text:
Q: Laravel race condition dynamic database connections problem i think i will have a problem with race condition because of dynamic database.
My API in each request will connect to a different database, multiple clients will use it, but each client has his own data base (SQL SERVER).
I'm changing the connection in the constructor of the controller:
On construct:
DB::disconnect(env("DB_CONNECTION"));
    Config::set('database.connections.' . env("DB_CONNECTION"), array(
        'driver'    => $data->driver,
        'host'      => $data->servername,
        'database'  => $data->database,
        'username'  => $data->user,
        'password'  => $data->password,
        'charset'   => 'utf8',
        'prefix'    => '',
    ));

On destruct:
    DB::disconnect(env("DB_CONNECTION"));

With this, the rest of the controller, can work normal with the ORM.
My question is, if i have about 200 requests on each client, how are the chances, of a wrong connection?
Because the config is global, if another request comes in, before the last is finished, what will happen?
I'm thinking to change the connetion in the model, it will be focused there, and not long before, like de controller. But I dont know if will be enough. PHP only suports one connection at time rigth? So it is not even a laravel problem.
I'm using:

*

*Laravel 9

*PHP 8

*SQL SERVER

Thank you all for your time, have a great day.


text:
Q: ASP bind SQL time(5) in format HH:mm I have a SQL DB data binding to a formview and am trying to format a time(5) filed to an HH:mm format.
I have no problem formatting a date field but can't find a format for the time field.
            <asp:TextBox ID="End_DateTextBox" runat="server" Text='<%# Bind("End_Date", "{0:dddd dd MMMM yyyy}") %>' Width="320px"/>
            <br />
             <asp:Label ID="Label7" runat="server" Text="Start_time:" Width="90px"></asp:Label>
            <asp:TextBox ID="Start_timeTextBox" runat="server" Text='<%# Bind("Start_time", "{0:HH:mm}") %>' Width="80px"/>

I nave tried many variations and get 'Input string was not in a correct format. " with all


text:
Q: Evaluate $\lim _{x\to \infty }\int _{\frac{1}{x}}^x\:f\left(t\right)dt$ and a big mistake in the book We have to evaluate $\lim _{x\to \infty }\int _{\frac{1}{x}}^x\:f\left(t\right)dt$ where $f\left(t\right)=\frac{1}{\left(1+t^2\right)\left(1+t^3\right)}$.
In my book they say that $\int _{\frac{1}{x}}^1\:f\left(t\right)dt=\int _1^x\:t^3\cdot f\left(t\right)dt$ to split $\int _{\frac{1}{x}}^x\:f\left(t\right)dt=\int _{\frac{1}{x}}^1\:f\left(t\right)dt+\int _1^x\:f\left(t\right)dt=\int _1^x\:\left(t^3+1\right)f\left(t\right)dt$ which is equal with $\frac{\pi }{4}$.
The big problem is that in my recent post I found that $\int _{\frac{1}{x}}^1\:f\left(t\right)dt$ is not equal with $\int _1^x\:t^3\cdot f\left(t\right)dt$, so what can I do?

A: Assuming $x>1$,
$$\begin{eqnarray*}\int_{1/x}^{x}\frac{dt}{(1+t^2)(1+t^3)}&=&\int_{1/x}^{1}\frac{dt}{(1+t^2)(1+t^3)}+\int_{1}^{x}\frac{dt}{(1+t^2)(1+t^3)}\\&=&\int_{1}^{x}\frac{u^3 du}{(1+u^2)(1+u^3)}+\int_{1}^{x}\frac{dt}{(1+t^2)(1+t^3)}\\&=&\int_{1}^{x}\frac{(1+t^3)\,dt}{(1+t^2)(1+t^3)}\\&=&\int_{1}^{x}\frac{dt}{1+t^2}\xrightarrow[x\to +\infty]{}\arctan 1=\color{red}{\frac{\pi}{4}}.\end{eqnarray*}$$
We just used the substitution $t=\frac{1}{u}$, from which $dt=-\frac{du}{u^2}$, in the second step.
So, there is no mistake in your book.


text:
Q: Mac System Services - application "(null)" The problem is that I added my app to the system services and it was working fine, but, now, when I select the text, go to the Services menu and select my app the system says something like that:
"The service "xxx" could not be used because the application "(null)" is not compatible with the computer".
I have revised the code and everything seems to be ok, and in the bps results my app looks fine.
Any ideas of what can be happening?

A: I was able to fix this by doing the following:
Uninstall and remove all traces of the application in question.
Kill Launch Services: /System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Support/lsregister -kill
and then:
When reinstalling the app, make sure it's being installed from a dmg. This is what caused the problem for me and a coworker....installing our app not from the dmg. Not sure why but this fixed it for us.

A: Solved this after some serious head scratching today. Apparently the last part of your bundle identifier and the "Port Name" specified in your service settings in the Info.plist file have to match. Otherwise you get this weird error.
So basically, if you have the following bundle identifier:
com.yourcompany.yourapp

Your NSPortName should be yourapp. Otherwise you get the "application is not compatible" error.


text:
Q: Pretty Json object in html How do I pretty print JSON object in html? I tried this solution  but not working. Please help me what I need to do to achieve this. I tried using json pipe:

{{placeDetail |json}}

A: For native JS: :
For angular you need to add the  tag
Angular:

{{placeDetail |json}}

Native JS:

A: You can try with |json

{{placeDetail |json}}

A: Angular2 solution:
https://plnkr.co/edit/msa5JDjPUxGMFcHptTu8?p=preview
javascript solution:

var placeDetail = {
    'a': {
        'b': 1,
        'c': 2
    },
    'd': 3
};
document.getElementById("json-result").innerHTML = JSON.stringify(placeDetail, undefined, 2);


text:
Q: Using a generic type argument with `typeof T` I have a factory-like function that is meant to return an sub-class instance of BaseApi. It currently looks something like this (trimmed out irrelevant parts):
function getApi<T extends BaseApi>(apiClass: typeof BaseApi): T {
    return new apiClass();
}

And I use it like this:
const someApi = getApi<SomeApi>(SomeApi);

This works, but I would like <SomeApi> to be inferred by virtue of the fact that I'm passing the SomeApi constructor in. If I omit <SomeApi> then someApi is inferred to be of type BaseApi, not SomeApi. Worse, there's really no compiler correlation between <T extends BaseApi> and typeof BaseApi being the same thing, so you can incorrectly do something like getApi<SecondApi>(FirstApi) without a compiler error.
So I tried defining the apiClass as typeof T:
function getApi<T extends BaseApi>(apiClass: typeof T): T {
    return new apiClass();
}

And I found that TS did not understand this usage of T. Is there any way to do this?

A: What you actually want is new() => T, since you intend to use the argument as a constructor and produce a T. Even if you could write typeof T, that wouldn't be what you want, since T might not have a zero-argument constructor.
Remember that the typeof operator takes a value and produces a value. T is already a type; it is not a value.
Naturally, this is addressed in the TypeScript FAQ https://github.com/Microsoft/TypeScript/wiki/FAQ#why-cant-i-write-typeof-t-new-t-or-instanceof-t-in-my-generic-function


text:
Q: javascript dynamic data loading progress bar JavaScript dynamic data loading progress bar
i tried some of the codes found here but i am not able to get result
    var req = new XMLHttpRequest();

    req.addEventListener("progress", onUpdateProgress);
    req.addEventListener("load", onTransferComplete);
    req.addEventListener("error", onTransferFailed);
    req.addEventListener("abort", onTransferFailed);

    req.open("GET", "http://stackoverflow.com/questions/3790471/xmlhttprequest-js-image-loading");
    req.send();

    function onUpdateProgress(e) {
        var percent_complete = e.loaded/e.total;
        console.log(percent_complete);
    }

    function onTransferFailed(e) {
        alert("Something went wrong. Please try again.");
    }

    function onTransferComplete(e) {
        //Problem
    }

i should get the percent load in console, but i am not able to get it

A: Try this
req.addEventListener("progress", onUpdateProgress, false);

and/or
 req.open("GET", "http://stackoverflow.com/questions/3790471/xmlhttprequest-js-image-loading", false);


text:
Q: Removing characters from a string using erase and remove I found this solution on Stack Overflow and other forums for removing characters from a string. Say I wanted to remove the white spaces from a string I'd do:
currentLine.erase( std::remove( currentLine.begin(), currentLine.end(), ' ' ), currentLine.end() );

where currentLine is the name of the string.
This sort of thing appears to work for people but if I use it I get:
/local/yrq12edu/Desktop/Bens_C++_Utilities/simuPOPtoFASTA/simuPOP2FASTA.cpp|54|error: cannot convert 'std::basic_string<char>::iterator {aka __gnu_cxx::__normal_iterator<char*, std::basic_string<char> >}' to 'const char*' for argument '1' to 'int remove(const char*)'|

As a compile error.
I think it's something to do with the iterator that is returned by the std::remove function not working with the erase method, but apparently it should work. How do I fix this?

A: What headers have you included?  It looks like the only std::remove that the compiler is seeing is the one in <cstdio> (perhaps included through <iostream> or one of the other iostream heaaders).  If you include <algorithm>, you should find the right one.


text:
Q: validate WTForm after selectfield choices updated dynamically with jquery I am creating a flask app and I created a form using WTForms. The form has two SelectFields (dropdowns) and a submit button. I would like the dropdowns to be dynamic - basically, the user will select an option from dropdown A, this will trigger a database query in the background which will return the choices for dropdown B.
I have found some good solutions for this

*

*For example, this youtube video shows how to use javascript +
WTForms to achieve this

*and this stackoverflow question uses jquery and regular forms.
I ended up using the second answer to the linked stackoverflow question to model my solution. The basic idea is that the jquery calls a flask endpoint which does the database query and returns the new options for the dropdown which are dynamically populated
I want to do some additional processing once the form is submitted, and to do this, I am using if form.validate_on_submit(): in the index endpoint to wrap the additional processing and to validate the form. None of the answers to this question that I have found have attempted to validate the form. The problem is that the choices field on dropdown B are now invalid. I started with some default values, which the validator function expects and then updated the choices dynamically using jquery without updating the choices. As described in the solution, the database query is processed in a different endpoint from the index endpoint where I'm checking the form validation, so it does not have access to these new choices to populate them.
What is the best way to update the choices for the form in the index endpoint (after the choices have been updated) so that the form will be valid on submit?
Some code snippets
jquery (mostly copied from the linked stackoverflow answer)
 <script type="text/javascript">
      $(document).ready(function() {

        $('#dropdown_one').change(function(){

          $.getJSON('/_update_dropdown', {
            selected_class: $('#dropdown_one').val()

          }).done(function(data) {
                $('#dropdown_two').html(data.html_string_selected);
           })
        });
      });
    </script>

form class
class Form(FlaskForm):
    dropdown_one = SelectField("Choose an option", choices = [options])
    dropdown_two = SelectField("Choose option based on dropdown one")
    submit = SubmitField("Submit")

python/flask index endpoint
@bp_views.route('', methods=["POST", "GET"])
def index():
    form = Form()

    form.dropdown_two.choices = [(None, "Choose item on dropdown one first")] # default value for the second dropdown

    if form.validate_on_submit():
        # further processing
        # this check fails because the choices have been updated from the default values and the choice isn't valid

    return render_template('index.html', form=form)

python/flask update endpoint (mostly copied from the linked stackoverflow answer
@bp_views.route('/_update_dropdown')
def update_dropdown():
    # the value of the first dropdown (selected by the user)
    selected_class = request.args.get('selected_class', type=str)

    # get values for the second dropdown
    updated_values = db.fetch_data(selected_class)

    # create the value sin the dropdown as a html string
    html_string_selected = ''
    for entry in updated_values:
        html_string_selected += '<option value="{}">{}</option>'.format(entry, entry)

    return jsonify(html_string_selected=html_string_selected)

A: I ran into this problem as well.  My solution was to dynamically create the selected choice on submission so that it could be valid.
This is an example of how it could work:
if request.method == 'POST':
    for k,v in form.data.items():
        if isinstance(form[k].widget, wtforms.widgets.Select):
            form[k].choices = [(form[k].data, form[k].data)]

    if form.validate_on_submit():

It should be noted that in this example, validation is being bypassed for SelectFields.  A malicious actor could submit any value they wanted and it would become valid on submission, unless additional server-side steps are taken to limit what choices could be created.


text:
Q: unset() not working as expected Following is my code to delete an object inside a JSON array.
if($_GET['method']=='deleteStudentReflections'){

        $jsonString = file_get_contents('../admin/data/student_reflection.json');

        $data = json_decode($jsonString, true);
        print_r($data["student_reflections"]);
        unset($data["student_reflections"][$_GET['obj_val']]);

        $newJsonString = json_encode($data);

        file_put_contents('../admin/data/student_reflection.json', $newJsonString);

        print_r($_GET);

}

it should do this:
Before calling function JSON array value:
{"english_courses":[{"name":"Abdullah","detail":"Bad Boy","image_link":"images\/dp.jpg"},{"name":"Course Chin 2","detail":"Course det 2","image_link":"images\/explicit feedly 3.PNG"},{"name":"courses 3 chinese","detail":"courses detail chinese 3","image_link":"images\/site turorial.png"}]}

it should delete any object inside 'english_courses' courses array, but instead of deleting it does this:
{"english_courses":{"0":{"name":"Abdullah","detail":"Bad Boy","image_link":"images\/dp.jpg"},"2":{"name":"courses 3 chinese","detail":"courses detail chinese 3","image_link":"images\/site turorial.png"}}}

this is obj_val code:
function deleteEnglishCourse() {
           var obj_val=$('#op').val();
           console.log(obj_val);
           var deleteConfirm = confirm("Press 'Ok' to continue, Press 'Cancel' to Cancel ");
          if (deleteConfirm == true) {
             $.ajax ({ type: "GET", url: 'delete.php', data: "obj_val="+obj_val+"&method=deleteEnglishCourse", success: function(data) {alert(data); location.reload(); } }); } else { } }

this is how '#op' is set:
function displayData(data){
            var html="<select id='op' class='form-control' onchange='valueSelect(this.value);'>"; for(var i=0;i<data["english_courses"].length;i++){ html+='<option value="'+i+'">' + data["english_courses"][i]["name"] + '</option>'; }
   html+='</select>';
   $('#name_dropdown').append(html); }

basically dropdown is populated by dynamic data. and when a value is selected it gets to a php file where a particular obj of a json array is deleted based on the value of obj_val
this error only occurs when obj_val is '0' and php function has to delete the first index of the array. Otherwise it works fine
please help !!

A: you have to Re-Index $data array, the problem is when you attempt unset($data....) so the first index start from "1" it should be start from "0" , then it will work fine
How to Remove Array Element and Then Re-Index Array?


text:
Q: real media player video and audio files. (.rm and .ram) used in html code not working in current browser I have a code containing real media player video and audio files. (.rm and .ram). They are not working in browsers. Can you please suggest a solution. The code contains an embed tag which has a .rpm file in src. The .rpm file contains path to a .smi file which contains the .rm video and audio files to be played on clicking a button in browser. But this is not working as it should.
Thanks.

A: Convert the RealMedia files to a modern format, such as MP3 for audio files, or MPEG4 for video files.
RealMedia has been effectively obsolete for the last five to ten years (depending on how you define "obsolete"), and is no longer playable in any modern web browser.


text:
Q: Norm of a Vector equality As I prepare for the exam, I have encountered the following question:

I am not very good on this Norm calculations, so your help is important.
This is where I am so far:

How do I continue from here? I have proven (I guess) the equivalence, but not the inequality.
Thanks,
Alan

A: Using $\triangle$-inequality & CS-inequality: $LHS = ||\displaystyle \sum_{i=1}^n \lambda_iy_i||^2\leq \left(\displaystyle \sum_{i=1}^n |\lambda_i|\cdot ||y_i||\right)^2\leq RHS $


text:
Q: ios swift how to set a save button in the navigation bar I have a MainViewController which is a table view controller, with custom cells where the user can select some data. There is a button on this MainViewController that goes to PreferencesViewController, which has two buttons on the navigation bar, one for back (it is wokring now good), and the other one for save (here is my problem)
This is a screenshot of the navitation bar in the PreferencesViewController:

I drag a segue from the save bar button back to the MainViewController.
 my problem
when I hit save, the MainViewController appears, but without saving the values the the user has already selected. sounds like a new instance of this MainViewContoller is being created.
What am i missing here? what other approach i should have already used please?

A: You need to connect your save button to an IBAction, not a segue.
In that IBAction, do whatever you need to do to save your data, and then do a dismissViewController:animated: call yourself in code.
If you wanted to use a segue you wouldn't be able to (easily) save your data, and yes, it creates a new instance.
An alternative would be to connect your save button to an unwind segue, rolls back, or unwinds, one or more segues to get back to a previous view controller. To do that you'd have to put your save logic in prepareForSegue (with code to test which segue is being invoked and only save in response to the save segue.)

A: i found the solution myself using:
1- custom delegate:
2- self.navigationController?.popViewControllerAnimated(true)