text:
Q: Context in Type Theory I am reading a book on type theory. On page 105, the author says that

If one views valid contexts as theories (in the sense of ordinary logics) a consistent context corresponds to a consistent theory in the traditional sense.

Then the author gives the following definition:

Definition (Consistent Contexts) A valid context $\Gamma$ is consistent if and only if not very $\Gamma$-formula
   is provable in $\Gamma$, or equivalently, if and only if $\perp$ is not provable in $\Gamma$.

If I understand correctly, this implies that (a) not every context ($\Gamma$ : ctx) is consistent in type theory, and (b) if $\Gamma$ is consistent, then we won't be able to have both $x_1:A$ and $x_2:\neg A$ as assumptions, as they result in $\perp$?

A:
(a) not every context $(Γ : \text{ctx})$ is consistent in type theory

Indeed, the context $x : \bot$ is inconsistent.

(b) if $\Gamma$ is consistent, then we won't be able to have both $x_1:A$ and $x_2:\neg A$ as assumptions, as they result in $\bot$

Yes, but this is just a trivial example. Inconsistencies can be sneakier.
To level up, try to think of a context with 3 assumed propositions that is inconsistent, but removing any one of them results in a consistent context.


text:
Q: Formatting output of Write-verbose I have a script which when i output an array of file information like this i get the following output
$output
Productversion Fileversion FileName
1.2.3.4         1.2.3.4     test.exe

However when i do output it in the following way
write-verbose $output

I lose the nice output and get everything for each line of $output. Is it possible to format the verbose output to look like standard output? (I need to use write-verbose for a powershell on remote machine TFS task)
Thanks

A: This should work:
$output | Out-String | Write-Verbose

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python: print unicode string stored as a variable In Python (3.5.0), I'd like to print a string containig unicode symbols (more precisely, IPA symbols retrieved from Wiktionary in JSON format) to the screen or a file, e.g.
print("\u02c8w\u0254\u02d0t\u0259\u02ccm\u025bl\u0259n")

correctly prints
ˈwɔːtəˌmɛlən

- however, whenever I use the string in a variable, e.g.
ipa = '\u02c8w\u0254\u02d0t\u0259\u02ccm\u025bl\u0259n'
print(ipa)

it just prints out the string as-is, i.e.
\u02c8w\u0254\u02d0t\u0259\u02ccm\u025bl\u0259n

which isn't of much help.
I have tried out several ways to avoid this (like going via deocde/encode) but non of that helped.
I cannot work with
u'\u02c8w\u0254\u02d0t\u0259\u02ccm\u025bl\u0259n'

either since I am already retrieving the string as a variable (as the result of a regex-match) and at no point in my code enter the actual literals.
It might as well be that I made a mistake during the conversion from the JSON result; by now I have converted the byte stream into a string using str(f.read()), extracted the IPA part via regex (and done a replace on the double backslashes) and stored it in a string variable.
Edit:
This is the code I had so far:
def getIPAen(word):
    url = "https://en.wiktionary.org/w/api.php?action=query&titles=" + word + "&prop=revisions&rvprop=content&format=json"
    jsoncont = str((urllib.request.urlopen(url)).read())
    jsonmatch = re.search("\{IPA\|/(.*?)/\|", jsoncont).group(1)
    #print("jsomatch: " + jsonmatch)
    ipa = jsonmatch.replace("\\\\", "\\")
    #print("ipa: " + ipa)
    print(ipa)

After modification with json.loads:
def getIPAen(word):
    url = "https://en.wiktionary.org/w/api.php?action=query&titles=" + word + "&prop=revisions&rvprop=content&format=json"
    jsoncont = str((urllib.request.urlopen(url)).read())
    jsonmatch = re.search("\{IPA\|/(.*?)/\|", jsoncont).group(1)
    #print("jsonmatch: " + jsonmatch)
    jsonstr = "\"" + jsonmatch + "\""
    #print("jsonstr: " + jsonstr)
    jsonloads = json.loads(jsonstr)
    #print("jsonloads: " + jsonloads)
    print(jsonloads)

For both versions, when calling it with
getIPAen("watermelon")

what I get is:
\u02c8w\u0254\u02d0t\u0259\u02ccm\u025bl\u0259n

Is there any way to have the string printed/written as already decoded, even when passed as a variable?

A: You don't have this value:
ipa = '\u02c8w\u0254\u02d0t\u0259\u02ccm\u025bl\u0259n'

because that value prints just fine:
>>> ipa = '\u02c8w\u0254\u02d0t\u0259\u02ccm\u025bl\u0259n'
>>> print(ipa)
ˈwɔːtəˌmɛlən

You at the very least have literal \ and u characters:
ipa = '\\u02c8w\\u0254\\u02d0t\\u0259\\u02ccm\\u025bl\\u0259n'

Those \\ sequences are one backslash each, but escaped. Since this is JSON, the string is probably also surrounded by double quotes:
ipa = '"\\u02c8w\\u0254\\u02d0t\\u0259\\u02ccm\\u025bl\\u0259n"'

Because that string has literal backslashes, that is exactly what is being printed:
>>> ipa = '"\\u02c8w\\u0254\\u02d0t\\u0259\\u02ccm\\u025bl\\u0259n"'
>>> print(ipa)
"\u02c8w\u0254\u02d0t\u0259\u02ccm\u025bl\u0259n"
>>> ipa[1]
'\\'
>>> print(ipa[1])
\
>>> ipa[2]
'u'

Note how the value echoed shows a string literal you can copy and paste back into Python, so the \ character is escaped again for you.
That value is valid JSON, which also uses \uhhhh escape sequences. Decode it as JSON:
import json

print(json.loads(ipa))

Now you have a proper Python value:
>>> import json
>>> json.loads(ipa)
'ˈwɔːtəˌmɛlən'
>>> print(json.loads(ipa))
ˈwɔːtəˌmɛlən

Note that in Python 3, almost all codepoints are printed directly even when repl() creates a literal for you. The json.loads() result directly shows all text in the value, even though the majority is non-ASCII.
This value does not contain literal backslashes or u characters:
>>> result = json.loads(ipa)
>>> result[0]
'ˈ'
>>> result[1]
'w'

As a side note, when debugging issues like this, you really want to use the repr() and ascii() functions so you get representations that let you properly reproduce the value of a string:
>>> print(repr(ipa))
'"\\u02c8w\\u0254\\u02d0t\\u0259\\u02ccm\\u025bl\\u0259n"'
>>> print(ascii(ipa))
'"\\u02c8w\\u0254\\u02d0t\\u0259\\u02ccm\\u025bl\\u0259n"'
>>> print(repr(result))
'ˈwɔːtəˌmɛlən'
>>> print(ascii(result))
'\u02c8w\u0254\u02d0t\u0259\u02ccm\u025bl\u0259n'

Note that only ascii() on a string with actual Unicode codepoints beyond the Latin-1 range produces actual \uhhhh escape sequences. (For repl() output Python can still fall back to \uhhhh escapes if you terminal or console can't handle specific characters).
As for your update, just parse the whole response as JSON, and load the right data from that. Your code instead converts the bytes response body to a repr() (the str() call on bytes does not decode the data; instead you doubly escape escapes this way). Decode the bytes from the network as UTF-8, then feed that data to json.loads():
import json
import re
import urllib.request
from urllib.parse import quote_plus

baseurl = "https://en.wiktionary.org/w/api.php?action=query&titles={}&prop=revisions&rvprop=content&format=json"

def getIPAen(word):
    url = baseurl.format(quote_plus(word))
    jsondata = urllib.request.urlopen(url).read().decode('utf8')
    data = json.loads(jsondata)
    for page in data['query']['pages'].values():
        for revision in page['revisions']:
            if 'IPA' in revision['*']:
                ipa = re.search(r"{IPA\|/(.*?)/\|", revision['*']).group(1)
                print(ipa)

Note that I also make sure to quote the word value into the URL query string.
The above prints out any IPA it finds:
>>> getIPAen('watermelon')
ˈwɔːtəˌmɛlən
>>> getIPAen('chocolate')
ˈtʃɒk(ə)lɪt


text:
Q: Replace Method for multiple strings The data frame is about cars. So in seller columns have car company names and none(cars which selling by owner. So my aim is to change all company names to a simple string -'avtosalon'.
I've used for and replace method, code is running but, I can't get the result

for seller in data['Seller']:
    if seller== 'none':
        print('ok')
    else:
        seller=data['Seller'].replace('seller','avtosalon')
        print('done')

A: These are a few methods used to Replace Method for multiple strings

*

*Use str. replace() to Replace Multiple Characters in Python.

*Use re. sub() or re. subn() to Replace Multiple Characters in Python.

*translate() and maketrans() to Replace Multiple Characters in Python.

refer here: https://www.delftstack.com/howto/python/python-replace-multiple-characters/


text:
Q: Extending twig template when both are within /app directory I'm trying to make custom error pages in symfony2 but having problems using my site theme/layout within error.html.twig
As in stated here: http://symfony.com/doc/current/cookbook/controller/error_pages.html
I've overridden the error file and put my own into app/Resources/TwigBundle/views/Exception/error.html.twig. If I use static content this all works fine, but I'd like to use {% extends '::base.html.twig' %} like I do with all other pages, so I can copy my current layout and styles.
base.html.twig is located at app/Resources/views/base.html.twig. How do I go about extending this template?
Also, just out of curiosity, is there any way of overriding error pages from within one of my bundles without making a 'TwigBundle' bundle especially for it?
UPDATE
Ok, solved this with the help of 'wouter J'. It turns out the file was being found but the file it was extending was using is_granted. Adding app.user and to the if statement as it says in the docs solved it.

A: The ::base.html.twig syntax is not relative. That means it'll work everywhere.
The full syntax for template paths is BundleName:DirName:FileName. So AcmeDemoBundle:Page:home.html.twig refers to @AcmeDemoBundle/Resources/views/Page/home.html.twig.
If the DirName is not used, e.g. AcmeDemoBundle::layout.html.twig, it'll be resolved to @AcmeDemoBundle/Resources/views/layout.html.twig.
If the BundleName is not used, it is assumed the template lives in app/Resources/views.
So ::base.html.twig just refers to the absolute path app/Resources/views/base.html.twig (this is not absolute, since I don't know the absolute path to the app dir in your case, but it'll be absolute when Symfony does it).
In short: You can just use ::base.html.twig


text:
Q: Authenticating to YouTube with AuthSub I am finding two conflicting accounts from Google. I think because the developer guide hasn't been updated. I have received my httpClient (I think) and I am now to this point in the developer guide:
$yt = new Zend_Gdata_YouTube($httpClient, $applicationId, $clientId, $developerKey);

When I go to check my developer key and try to seach for an application id and client id I find this paragraph:

The Developer Key should be provided in every YouTube API request. Learn more
  Note that you no longer need to provide a Client ID with YouTube API requests.
  You may request an Apiary client key here.

So what should I use for the application and client IDs? I have tried leaving them blank and using arbitrary stings. Here is the error I get when I try to post a comment:
Fatal error: Uncaught exception 'Zend_Gdata_App_HttpException' with message 'Expected response code 200, got 401

<TITLE>User authentication required.</TITLE>

User authentication required.

Error 401

in /home/justinrob/ZendFramework/library/Zend/Gdata/App.php:709 Stack trace:
#0 /home/justinrob/ZendFramework/library/Zend/Gdata.php(221): Zend_Gdata_App->performHttpRequest('POST', 'http://gdata.yo...', Array, '<atom:entry xml...', 'application/ato...', NULL)
#1 /home/justinrob/ZendFramework/library/Zend/Gdata/App.php(900): Zend_Gdata->performHttpRequest('POST', 'http://gdata.yo...', Array, '<atom:entry xml...', 'application/ato...')
#2 /home/justinrob/ZendFramework/library/Zend/Gdata/App.php(975): Zend_Gdata_App->post(Object(Zend_Gdata_YouTube_CommentEntry), 'http://gdata.yo...', NULL, NULL, Array)
#3 /home/justinrob/mhjrmusic.com/common/zend/tests/bootstrap.php(99): Zend_Gdata_App->insertEntry(Object(Zend_Gdata_YouTube_CommentEn in /home/justinrob/ZendFramework/library/Zend/Gdata/App.php on line 709


text:
Q: Extendable database schema for contacts (social) I have an old application that needs upgrading. Doesn't everything now days?
The existing DB schema consists of predefined fields like phone, fax, email. Obviously with the social explosion over the last 5-7 years (or longer depending on your country) end users need more control over creating contact cards the way they see fit rather than just what I think might be useful.
Im concerned here with "digital" addresses. i.e. One line type addresses. phone=ccc ccc ccc ccc etc
Since physical addresses are pretty standard in terms of requirements in this case users will have to use what they are given (location, postal, delivery) in order to keep the scope managable.
So I'm wondering what the best practice format for storing digital info is. To me it seems I have two choices:

*

*A simple 4 field table (ContactId, AddressTypeId, Address, FormatterId)

1000, "phone", "ccc ccc ccc ccc", phoneformatter
1000, "facebook", "myfacebook", facebookformatter

This would then be JOINED anywhere it's need. The table would get massive though and the join performance would degrade over time i suspect.

*

*A json blob that would require additional processing once read (ContactId, Addresses)

1000, {{"phone": "ccc ccc ccc ccc"}, {"facebook": "myfacebook"}}

Or ... something else.
This db is for use in a given country by customers only trading domestically with client bases ranging from 3000-12000 accounts and then however many contacts per account - averages about 10 in current system.
My primary concern is user flexibility but performance is a key consideration in that. So I dunno, just do whatever and throw heaps of hardware at it ;)
Application is in C# if that makes any difference re: post query processing.

A: I would not go for the JSON blob.  This will be nasty if you need to answer any queries like:-

*

*Does anyone have me in their Facebook contacts?

*What's the most popular type of social media contact?

You would be forced to parse the JSON for every record and be unable to create a simple index.
Your additional solution is nearly correct, however FormatterId would need to be on a AddressType table.   What you have is not normalised as FormatterId would depend only on AddressTypeId.  So you would have three tables:-

*

*Contact

*ContactAddress

*AddressType

You haven't stated if you need to store two addresses of the same type against a single contact. e.g. if someone has two twitter accounts.  Answering this question will allow you to define the correct primary key on ContactAddress.  It would either be (ContactId, AddressTypeId) if you can only have one of each type per contact or create a synthenic key (ContactAddressId).

A: Well, I believe you have a table named contact
contact(contactid, contact details, other details)
and now you want to remove this contact details from the contact table because the contact details may contain digital address, phone number and all.
But the table you are considering
(ContactId, AddressTypeId, Address, FormatterId) is not in normal form and you can't uniquely identify a tuple until you read all the four columns which is bad and in this case indexing also not going to help you.
So better if you have if separate table for each type of the digital address, and have indexing on contactID
facebookdetails(contactid, rest of the details)
phonedetails(contactid, rest of the details)

And then the query can be join of all the tables, it will not degrade the performance.
Hope this will help :)


text:
Q: Ubuntu Data recovery after Format My Ubuntu was giving error so I thought to re-install it. I took backup of my project files and then re-installed Ubuntu 16 from a USB drive. After reinstalling I realized that I missed 2 of my projects to take backup.
I searched for the data recovery software and found testdisk and photorec. But it says that data can be recover before any installation and these software needs to be installed on any other media.
My question is, as I've re-installed the Ubuntu, is it now possible to retrieve/restore the data? Secondly, I need to install the testdisk and photorec on another media i.e. USB drive?

A:
I need to install the testdisk and photorec on another media i.e. USB drive?

Yes, You first need to make a bootable USB drive that contains testdisk. You can do this by using another computer, or your windows partition. Then boot from the USB you have created and follow the instructions, for example https://www.maketecheasier.com/recover-data-and-partitions-for-free-with-testdisk/
I suggest you make an image of your Linux partion first, with https://www.maketecheasier.com/clone-drives-and-partitions-with-clonezilla/ and work from that image.


text:
Q: Is it true that $\det(A-A^T) \geq 0$ for all $A \in R^{n\times n}$?
Is it true that $\det(A-A^T) \geq 0$ for all $A \in \mathbb{R}^{n\times n}$?

For $n = 2$, this says that $\det\begin{pmatrix} 0 & a_{1,2}-a_{2,1} \\ a_{2,1}-a_{1,2} & 0 \end{pmatrix} \geq 0$, which is easily confirmed (the determinant is $\left(a_{1,2}-a_{2,1}\right)^2$ in this case).

A: $A-A^T$ is skew-symmetric so its complex eigenvalues are $0$ or purely imaginary. If $0$ is an eigenvalue, $\det(A-A^T)=0$ and the inequality holds.
Otherwise, since $A-A^T$ has real entries, complex eigenvalues come in conjugate pairs and $$\det(A-A^T) = \prod_i \lambda_i \overline{\lambda_i} = \prod_i |\lambda_i|^2 \geq 0$$

A: A proof that doesn't use complex eigenvalues:
Let $B = A - A^T$.  We note that $B^T = -B$.  Note that for any vector $x$, we have $x^TBx = 0$ since
$$
x^TBx = (x^TBx)^T = x^TB^Tx = -(x^TBx).
$$
Claim: For any $t > 0$, $\det(B + tI) \neq 0$.
Proof: Suppose for contradiction that $(B + tI)$ is singular. Let $x$ be a non-zero element of $\ker(B + tI)$.  We have
$$
(B + tI)x = 0 \implies Bx = -tx \implies x^TBx = x^T(-tx) \implies 0 = -t(x^Tx),
$$
which is a contradiction.  $\qquad \square$
Now, consider the polynomial $p(t) = \det(B + tI)$ over the domain $[0,\infty)$.  We note that $p(t)$ has no zeros on the interval $(0,\infty)$, and (by the continuity of the determinant)
$$
\lim_{t \to \infty} \frac{p(t)}{t^n} = \lim_{t \to \infty}t^{-n}\det(B + tI) = \lim_{t \to \infty} \det(t^{-1}B + I) = \det(0 \cdot B + I) = 1.
$$
Thus, $\lim_{t \to \infty}p(t) = +\infty$. By the intermediate value theorem, we can conclude that $p(t)$ is positive over the interval $(0,\infty)$.
By the the continuity of $p$, we can conclude that $p(0) = \lim_{t \to 0^+} p(t) \geq 0$, which is to say that $\det(B) \geq 0$, which was the desired conclusion.

A: $A-A^T$ is skew-symmetric. It is well-known that all odd-sized skew-symmetric matrices are singular. So, it suffices to prove that every even-sized skew-symmetric matrix $K$ has a nonnegative determinant.
This can be proved by mathematical induction. The base case where the matrix is $2\times2$ is easy. In the induction step, consider an even-sized skew-symmetric matrix $K$. The result follows immediately if $K=0$. Suppose $K$ is nonzero. Then it must contain a nonzero principal $2\times2$ matrix $K_1$. Without loss of generality, we may assume that
$$
K=\pmatrix{K_1&-B^T\\ B&K_2}.
$$
Since $K_1$ is nonzero and skew-symmetric, it is nonsingular. It follows that the Schur complement $K_2-BK_1^{-1}B^T$ exists and is skew-symmetric. The result now follows from the identity $\det(K)=\det(K_1)\det(K_2-BK_1^{-1}B^T)$ and the induction hypothesis.

A: The result can be generalized as follows -and that is known since 1849 (Jacobi and Cayley)-.
$\textbf{Proposition}$. Let $A\in M_n(R)$ where $R$ is a commutative ring and $A$ is skew-symmetric.
Then $\det(A)$ is the square of an element of $R$.
For a proof, cf.
https://en.wikipedia.org/wiki/Pfaffian
https://core.ac.uk/download/pdf/82800447.pdf
For example, when $n=6$


text:
Q: Local structure of the quotient of a Lie group action Suppose $M$ is a smooth manifold and a compact Lie group $G$ acts freely on $M$, then it is well known that $M/G$ has a manifold structure.
Are there any results for the general case? (a) If the action is not free, what can we say about the local structure of the quotient? Can we define a stratification on the space? How regular are the strata? (b) Moreover, what can we say if $M$ and $G$ are Hilbert manifolds?
Thanks a lot!

A: Suppose one relaxes the condition that the action is free, replacing it with the condition that every point in $M$ has a finite $G$-stabilizer. In this case, the topological quotient $M/G$ carries a natural orbifold structure. The local model is therefore the quotient of $\mathbb{R}^n$ by a finite group acting linearly.
In general, $M/G$ is a stratified space, and the stratification is indexed by conjugacy classes of $G$-stabilizers.

A: If you know German, then I strongly recommend you the Habilitation thesis of Markus Pflaum:  "Ein Beitrag zur Geometrie und Analysis auf stratifizierten Räumen" for the stratification of the orbit space. If I remember correctly, then Ortega & Ratiu "Momentum Maps and Hamiltonian Reduction" also contains some general results about the orbit space although the main focus of this book lies on symplectic reduction.


text:
Q: qmake TEMPLATE = subdirs visual studio project generation in my project I'm using in my "main" .pro file TEMPLATE = subdirs that includes other sub-projects(2 additional libraries + target executable). As an outcome I would like to have an application that is linked against those 2 libraries. Based on my pro files structure I would like to generate visual studio 2008 or 2010 project file as some people prefer visual studio than Qt Creator as their IDE. What I have tried was:
qmake -t vcapp -spec win32-msvc2008 main.pro

but it gives some kind of an empty visual project file. If I repeat the same step for all my subdir project everything is fine. Only creating "the main one" that should have sub-projects in dependencies is not working correctly. I'm using qmake that comes with qt 4.7.3 release on Windows.

A: Use this:
qmake main.pro -tp vc -r


text:
Q: OS user interface guidelines: when to ignore? A line in this answer, "Get used to using the Mac on its own terms", took me aback a little bit, and made me start to think about something I pondered ages ago and still haven't come up with a good answer to.
Each OS has its own guidelines for how to develop an application's interface so it fits with the OS, and consequently the mindset of the user.
While no one really enforces this to any great degree (aside from the usual "made for xyz OS" programs) it bothers me that I have to make a choice when developing an application that suggests functionality that is different from the OS suggestion.  It may be the application itself is better with a different user interface, or it may be due to implementation, such as being a webapp or cross-platform.
App vs OS:

*

*What are the ramifications if I choose to develop against those UI recommendations assuming I have a good reason to do so?

Webapp vs OS:

*

*If I'm developing a webapp that's meant to be used as if it were a desktop app what do I do:

*

*Develop and follow my own convention (or one of the major OS's conventions)

*Check the user's OS and follow that convention (and thus a user would get a different experience on different computers even if using the same account)

*Follow the convention of another major webapp (gmail/docs, live, etc)

Cross platform vs OS:

*

*In developing an app that is cross platform

*

*Follow one OS's convention

*Use a cross platform library that follows most of the OS conventions depending on the OS it's being run on, though none are perfect

*Custom interface for each OS that is fully native

I realize it depends greatly on resources available, and various other unknowables, but what are the considerations, tactics, and arguments you use when considering this choice.

A: I remember some app that was adamant about keeping the same look and feel across platforms, touting all sorts of benefits when moving between platforms.  The problem is that most people don't use one app on different platforms, they use multiple apps on one platform.  If one of those apps behaves significantly differently than what they expect based on every other app they use, they aren't going to like it.

A: The general rule is that you can deviate from the style guide of a platform when you have compelling reason to believe that the deviation results in a net improvement user performance. That is, the gains provided by the deviation for the user are greater than the cost.
"Compelling reason" generally means empirical evidence –usability test data confirming the net improvement of the deviation. A designer's hunch is not good enough. Most OS guidelines are not arbitrary but associated with user performance advantages over the alternatives, probably including the one you're thinking of. The usability tests should be formulated to realistically assess both the performance cost and gains so they can be compared quantitatively. Ties go to following the style guide.
Even when a guideline is arbitrary, there is still always a cost associated with external inconsistency for any deviation, a cost that can be difficult to quantify but must be accounted for through designer's judgment. External inconsistency costs are primarily the effort to learn the deviation and the errors associated with trying the use the deviation in the context of other apps. The effective cost for learning is less if training is provided and/or the frequency of use is high (the latter justifying the learning overhead). Frequency of errors for a deviation are associated with the frequency and context of app use. The effective cost of errors is less if your app is used extensively and separately from other apps of the platform. As a rule of thumb, unless users use your app for hours a day every day, you need to demonstrate overwhelming superior user performance to justify a deviation.
Generally, inconsistency in UI behavior is a more serious problem than inconsistency in UI appearance. Also, contradictions (something that looks like something from the style guide but means something different) are more serious than irregularities (something that looks different from something in the style guide but means the same thing).
Conformance with OS style guides is generally more important for an app than conformance with web conventions because web conventions are functionally weaker, applying to fewer apps the user is likely to come across. One should not follow the conventions of a single app like Gmail at the expense of OS guidelines unless most of your users use the single app and the single app is used in conjunction with your app. For maximum usability, you should follow the guidelines of whatever OS your users are using. There is no substitute.

A: I don't think there's a really good answer here, other than just to do what you can to follow the de-facto conventions of the platform you're targetting. If you're developing a Web-app with a rich GUI, you should still try to follow general web design principles.
If you have a multi-platform app and you can't have a different front end for each, you can try to fuse together the conventions of the various platforms, but perhaps follow the conventions of the platform where you will have the most users.
You must know the rules before you can break them.

A: I think that the general idea is to give the user a sense of familiarity. So it is best to make your app behave like any app on the platform you target. This is particulary true on Mac OS X where OS, Apple apps and third party apps have a consistent look and feel (of course exceptions exist but are considered as such: not the best user experience on the platform).
For Web apps, consistency is among all web apps, where the rule seems to be creativity (like for games or DVDs). And usually it works.
For cross-platform apps, I would suggest a common core (e.g., app menu with File, Edit, View, ... Help), together with specificities on each platform.


text:
Q: Com funciona a propriedade Position? Já li sobre a propriedade position, mas ainda não conseguir entender o proposito dela. Os valores absolute e relative não entraram na minha cabeça. Também queria saber quando eu devo utilizar essa propriedade.

A: Existem quatro valores para a propriedade Position: Static, Relative, Fixed e Absolute
Static
O position: static; não tem por base as propriedades top, left, bottom ou right, ele simplesmente fica no lugar onde você o colocou "estático" e acompanha no fluir normal da página.
Relative
O valor relative faz com que o elemento seja posicionado relativamente de acordo com o valor informado em top, left, bottom ou right.
Ex.: se você configurar um elemento assim:
position: relative;
left: 10;

Ele ficará na posição normal no fluir da página acrescentado +10px de distância da lateral esquerda.
Fixed
Um elemento configurado com fixed, ficará fixo na tela, não importando o quanto você desça a página para baixo. Quando você vê um site que tem um menu superior que fica sempre no topo, independente de você descer a barra de rolagem para baixo, provavelmente está marcado como position: fixed;.
Absolute
O elemento com position: absolute; fica posicionado relativamente ao elemento "superior" a ele (caso esteja dentro de um outro elemento), ou relativamente ao body (caso não esteja dentro de outro elemento). Se você o configurar assim:
position: absolute;
left: 10;
top: 20;

Ele se manterá na posição "10, 20", e diferente do fixed, quando você descer o scroll da tela, ele irá se mover, mantendo sempre a posição absoluta em relação ao elemento "superior".
Caso ele esteja dentro de uma outra div, a posição "10, 20" que citei antes, seria referente à ela.
Ex: se a div pai estiver na posição "20, 30", a div absoluta estaria na "20, 50".


text:
Q: How to disable autocommit in sqlite4java? I have recently been playing with the sqlite4java library.
I think I have it pretty much figured out. The only think that bothers me is that I do not know how to switch off the auto-commit using this library. Can anyone please help?
A code example would be much appreciated.
Thanks in advance,
Boro

A: Jefromi and king_nak are correct - you just need to issue SQL statements that begin and end a transaction.
SQLiteConnection con = new SQLiteConnection();
con.exec("BEGIN");
// do transaction work - auto-commit is disabled
con.exec("COMMIT");
// auto-commit is enabled again

A: Edit: I confused sqlite4java with the sqliteJDBC package. So the below code will not help. I'm keeping it for reference nevertheless.
After you obtained the connection, just call setAutoCommit(false)

java.sql.Connection con = DriverManager.getConnection("jdbc:sqlite:/your/db/file", "user", "password");
con.setAutoCommit(false);

A: Referring to SQLite's C interface description:

The sqlite3_get_autocommit() interface returns non-zero or zero if the given database connection is or is not in autocommit mode, respectively. Autocommit mode is on by default. Autocommit mode is disabled by a BEGIN statement. Autocommit mode is re-enabled by a COMMIT or ROLLBACK.

So you disable auto-commit by a BEGIN TRANSACTION statement. No separate API function is present for this


text:
Q: Words or phrases for someone that is ready to escape quickly, usually due to danger I'm looking for a word or short phrase that describes a situation in which there is danger and you should be ready to move / escape quickly.
The only thing that comes to mind is "Pack Light" or "Sleep Light", but it's not exactly what I'm looking for. Any ideas?

A: How about "vigilant"?

alertly watchful especially to avoid danger

https://www.merriam-webster.com/dictionary/vigilant

A: An expression for this is to sleep with one eye open:
From The Free Dictionary:

To stay awake or sleep very lightly so as to remain very wary, cautious, or alert. I won't forget this insult. You'd better start sleeping with one eye open, because I'll get my revenge.

From Oxford Dictionaries:

Sleep very lightly, aware of what is happening around one.
'the woman was like a cat sleeping with one eye open, watching everything that went on'
'She must have heard something because according to her father she slept with one eye open at all times.'
'I have spent my life in an area where you needed to sleep with one eye open to survive.'


text:
Q: MySQL is very slow when querying a row that doesn't exist I have a User table with more than 100m rows, there is no partition:

    create table User {
        user_id int primary key auto_increment,
        user_email varchar(50) unique,
        ...//no more than 20 columns
    }  ENGINE=MyISAM

most of time it's ok with following sql:
select user_id, .... from User where user_email=?

but if I gave an email address that does not exist in DB, then it could be very slow, maybe more that 1s.
what the problem could be?
=======update==========
the database has a slave, I just tested that the SQL is pretty fast even if no such record.
is it because the database run for a long time(for about 3 years)?


text:
Q: What box to use when cropping a rotated image in opencv I have rotated an image and now I want to crop it so that the borders are cut out and the full cropped image is viewable. I tried a method I found on the net but it didn't work and to be honest I don't fully understand what it was trying to do. I understand the rotating part. What points is he pushing to points? Is it the four corners of the image? As his method of pushing those points does not work for me. I used the four corners of the image instead which worked for rotating but when I try to run getRectSubPix an exception occurs probably because my box is wrong but I'm not sure what getRectSubPix needs then?
Here is the output I get after running this code. Clearly the output is iverted (Why does he do this is it important?) and also the crop doesn't work.

cv::bitwise_not(img, img);

std::vector<cv::Point> points;
cv::Mat_<uchar>::iterator it = img.begin<uchar>();
cv::Mat_<uchar>::iterator end = img.end<uchar>();
for (; it != end; ++it)
if (*it)
  points.push_back(it.pos());

cv::RotatedRect box = cv::minAreaRect(cv::Mat(points));
cv::Mat rot_mat = cv::getRotationMatrix2D(box.center, angle, 1);
cv::Mat rotated;
cv::warpAffine(img, rotated, rot_mat, img.size(), cv::INTER_CUBIC);
cv::Size box_size = box.size;
if (box.angle < -45.)
  std::swap(box_size.width, box_size.height);
cv::Mat cropped;
cv::getRectSubPix(rotated, box_size, box.center, cropped);


text:
Q: Trouble with subscribing to keyspace notifications I have a list in redis managed by bull. I'd like to monitor the length of this list a different process. I'm new to redis so while I think I've found the "correct" way to do this, I'm running into issues.
From a little research I leaned that Redis has Keyspace Notifications from 2.8.0 onwards and they sounded appropriate.
Before I go further I just want to confirm I have keyspace events enabled:
127.0.0.1:6379> CONFIG GET notify-keyspace-events
1) "notify-keyspace-events"
2) "AKE"

Also, according to INFO, I think I'm on database 0:
# Keyspace
db0:keys=315,expires=0,avg_ttl=0

With that out of the way: I'm having trouble subscribing to the channels I want. The module creates and manages a list under the key: 'bull:Test Queue:wait', so based on the documentation for keyspace notifications my understanding is I should be doing the following to listen to push and pop events.

*

*SUBSCRIBE "__keyspace:0__:bull:Test Queue:wait rpush"

*SUBSCRIBE "__keyspace:0__:bull:Test Queue:wait lpush"

*SUBSCRIBE "__keyspace:0__:bull:Test Queue:wait rpop"

*SUBSCRIBE "__keyspace:0__:bull:Test Queue:wait lpop"
If I run 1. in one process, and then in another process do:
RPUSH "bull:Test Queue:wait" 222

Then the subscribe doesn't get the message. Weirdly, if I use PSUBSCRIBE and listen to "__keyspace:0__:bull:Test Queue:wait*" then it does fire appropriately. But I'm not looking for all events, just pushes and pops. So this isn't quite what I'm after.
If someone could tell me what I'm doing wrong it would be much appreciated.
Thanks for your time.

A: I was misunderstanding the docs.
The channel is __keyspace:0__:bull:Test Queue:wait and the message is rpush, lpush, etc. Alternatively, the channel could be: __keyspace:0__:rpush and the message would be bull:Test Queue:wait.
Thank to Jan-Erik Rediger who helped me out on the discussion board.


text:
Q: Display pst or universal time with javascript or jquery I am trying to display time for a timestamp with javascript by converting it yo local time. How can I add pst or ut next to time with javascript or jquery with out other libraries?
function formatTimeStamp(timeStamp) {
    var localDate = new Date(timeStamp).toLocaleTimeString();
    return localDate;
}

Returns 11:03:28 AM
I am trying to display as
11:03:28 AM PST

A: Use options:
.toLocaleTimeString('en-GB',{ timeZoneName: 'short' });

More here: docs.


text:
Q: Restrict an IP address to the internet only Can I restrict, a static IP address on my network, to internet access but no other internal IPs should be accessible (apart from the gateway)?
Is there a routing option for such a thing on home routers?

A: There are so many routers with so many different facilities that one cannot generalise. On some a single port can be assigned as a DMZ (demilitarised zone), so this would provide the isolation you need if assigned to the machine in question; on others there is no DMZ, or the DMZ works differently. Note that a machine in a DMZ needs very good internet security protection.
You could achieve the result you want by setting all the firewalls on the subnet to reject the port assigned to the machine in question, but this would not stop access to webcams and the like, which do not have firewalls.
You would need administrator rights on the machine that you want to exclude, and its users would need to be excluded from the same, so that they cannot assign their own, different static address within the same subnet, thereby bypassing the firewall blocks or taking it out of the DMZ.


text:
Q: c++ - Flaky atomic lock.. but why? Question solved: see the edit.
x86_64, Linux, gcc 11.1, gnu++20.
Before using const std::lock_guard <mutex> lock( mut );
I wanted to give a go to my own implementation of multithreading lock, to have a better understanding of the whole thing.
The problem:
While using the lock_guard is always reliable, that code below isn't:
Godbolt snippet
Here is the code, for those willing to read it here:
  #include <atomic>
#include <future>
#include <iostream>
#include <mutex>
#include <string>
#include <thread>
#include <vector>

using namespace std;

class Lock_free_sync {
    atomic<bool> &object;
    const bool expected_input;
    bool already_released = false;
    bool got_lock = false;
    const unsigned debug_id = 0;

   public:
    Lock_free_sync(atomic<bool> &object_to_lock, const bool expected_input_)
        : object(object_to_lock), expected_input(expected_input_) {
        get_lock();
    }

    auto get_lock() -> void{
        bool expected_tmp= expected_input;
        const bool new_object_value = !expected_tmp;

        while (object.compare_exchange_strong(expected_tmp, new_object_value) ==
               false) {
            expected_tmp= expected_input;
            object.wait(expected_tmp);
        }

        got_lock = true;
    }

    auto release_lock() -> void{
        if (!got_lock) {
            return;
        }

        object = expected_input;
        object.notify_all();

        already_released = true;
    }

    ~Lock_free_sync() {
        if (!already_released) {
            release_lock();
        }
    }
};

mutex h;

auto printer(unsigned id, string &&what) {
#if 0
        const std::lock_guard <mutex> lock( h );

        cout << id << " " << what << endl;
#endif
}

auto printer(unsigned id, string &&what, unsigned complement) {
#if 0
        const std::lock_guard <mutex> lock( h );

        cout << id << " " << what << " " << complement << endl;
#endif
}
auto printer2(unsigned id, string &&what, unsigned complement) {
#if 1
    // const std::lock_guard <mutex> lock( h );
    cout << id << " " << what << " " << complement << endl;
#endif
}
int main() {
    atomic<bool> flag = false;
    atomic<bool> terminate = false;

    auto lambda_thread = [](unsigned i, auto flag_in, auto terminate_in) {
        atomic<bool> &flag = flag_in.get();
        auto &terminate = terminate_in.get();

        printer(i, " >>> in thread");
        printer(i, " >>> the bool is lock free? ", flag.is_lock_free());
        printer(i, " >>> the bool is always lock free? ",
                flag.is_always_lock_free);

        unsigned count = 0;

        while (1) {
            bool expected_value = false;
            Lock_free_sync lock(flag, expected_value);
            // const std::lock_guard <mutex> lock( h );
            printer(i, " >>> in loop working <<<<<<<<<<<<");
            ++count;
            printer(i, " >>> flag is", flag);
            this_thread::sleep_for(1s);

            printer(i, " >>> check terminate");

            // just make sure we are not trapped
            if (terminate) {
                // const std::lock_guard <mutex> lock( h );
                printer2(i, "stop thread", count);

                return;
            }

            printer(i, "about to reloop");
        }
    };

    vector<thread> vect_threads;

    {
        thread a(lambda_thread, 1, ref(flag), ref(terminate));

        vect_threads.push_back(move(a));
    }
    {
        thread a(lambda_thread, 2, ref(flag), ref(terminate));

        vect_threads.push_back(move(a));
    }

    flag.notify_all();
    cout << "real sleep" << endl;
    this_thread::sleep_for(2s);
    cout << "about to call terminate" << endl;
    terminate = true;

    cout << "wait for join" << endl;

    cout << "terminate is" << terminate << endl;

    terminate.notify_all();

    for (auto &&elem : vect_threads) {
        elem.join();
    }

    cout << "end the main thread" << endl;

    return 0;
}

If it shows a result, just reload the page and see it fail (tells time is exceeded because one thread is trapped)
What do I get:
Running this flaky code multiple times will yield correct behaviour sometimes.
But at some point, one thread won't finish.
The deadlock is here:
                bool search_for = locked_value;
                const bool new_object_value = !search_for;

                while ( object.compare_exchange_strong( search_for, new_object_value ) == false ){
                        // at this point, search_for has a wrong value in it, otherwise we would not have entered the loop. Set it properly and wait on the value we expect:
                        search_for = locked_value;
                        object.wait( search_for );
// at this point, the object has our value but we need to get the flag otherwise, another thread could run the loop at the same time
                    }

is not doing what I expect it to do.
What I think the above snippet does:
When the program starts, flag is false and so threads will fight to get the lock.
They all compare and exchange and if one of them could get the flag, that one will keep going while the others are waiting in that loop.
Once the work is done, the thread that got the flag will reset it and notify them all, even if it is the last one needing to loop again for it.
Once in the lambda loop, they will read if the terminate flag is set and leave accordingly.
But I know that one thread is trapped in the snippet loop above.
How can I correct it?
#Edit:
Code is working now.
I had two things wrong:

*

*the scope of the class. It was way too large and bothered the repartition of the resource among threads. Here is the proper version:
     while ( 1 ){
         //code
             {
                     // narrow scope
                     Lock_free_sync lock( flag, search_for );
                     printer( i, " >>> in loop working <<<<<<<<<<<<" );
                     ++count;
                     printer( i, " >>> flag is", flag );
                     this_thread::sleep_for( 2ms );
             }
        //code
     }

*In the class:
working code in get_lock(), replacing the problematic snippet:
bool search_for = expected_value;
const bool new_object_value = !search_for;

while ( object.compare_exchange_strong( search_for, new_object_value ) == false ){

object.wait( search_for );
// see where search_for is reset? Now it is good.
search_for = expected_value;

}

and in release_lock :
object.exchange( expected_value );
object.notify_all();

Now, after dozens of tries, it works as expected, no more deadlocks.
I learned a lot today. Thanks


text:
Q: Creating N-ary tree in java with a linked list structure I have to create an nary tree using a linked list.
I have already implemented a nary tree, but not sure how to go about changing it to a linked list structure. Please help.
public class NaryTree extends AbstractTree
{
    protected Object key;
    protected int degree;
    protected NaryTree[ ] subtree;

    public NaryTree(int degree) {
        key = null; this.degree = degree; subtree = null;
    }

    public NaryTree(int degree, Object key) {
        this.key = key;
        this.degree = degree;
        subtree = new NaryTree[degree];
        for(int i = 0; i < degree; i++)
            subtree[i] = new NaryTree(degree);
    }

That is a nary tree implementation.


text:
Q: Triggered a flask app on airflow using docker-compose, but cannot see any output outside docker container I have an ETL job that I'm testing to extract, transform and loads some data into airflow postgres db. At the end of the ETL task(ETL runs successful), I want to use a PythonOperator to trigger a flask api to display the endpoints.
I am using docker-compose to run airflow. I extended airflow docker image using the airflow documentation/recommendation to enable me install task dependencies.Extending images
Now, the Dag for this PythonOperator runs successfully inside the container and when I use curl, I get the current output from the api but nothing on postman or browser. That is, it runs inside the docker container but does not run outside the container and hence, no output.
This is the content of the Dockerfile I used in extending the airflow image
FROM apache/airflow:2.5.1-python3.10
EXPOSE 5005
COPY requirements.txt /requirements.txt
RUN pip install --user --upgrade pip
RUN pip install --no-cache-dir --user -r /requirements.txt
CMD ["flask", "run", "--host", "0.0.0.0"]

This is the docker-compose.yaml file below. I made two modifications to the docker-compose.yaml file from airflow.

*

*I added a flask-server resource which maps port 5000 to 5005 on docker

*Modified the airflow image name to be same with the Dockerfile used to extend it. The original image name is commented below.

---
version: '3'
x-airflow-common:
  &airflow-common
  # In order to add custom dependencies or upgrade provider packages you can use your extended image.
  # Comment the image line, place your Dockerfile in the directory where you placed the docker-compose.yaml
  # and uncomment the "build" line below, Then run `docker-compose build` to build the images.
  # image: ${AIRFLOW_IMAGE_NAME:-apache/airflow:2.5.1}
  image: ${AIRFLOW_IMAGE_NAME:-apache/airflow:2.5.1-python3.10}
  build: .
  environment:
    &airflow-common-env
    AIRFLOW__CORE__EXECUTOR: CeleryExecutor
    AIRFLOW__DATABASE__SQL_ALCHEMY_CONN: postgresql+psycopg2://airflow:airflow@postgres/airflow
    # For backward compatibility, with Airflow <2.3
    AIRFLOW__CORE__SQL_ALCHEMY_CONN: postgresql+psycopg2://airflow:airflow@postgres/airflow
    AIRFLOW__CELERY__RESULT_BACKEND: db+postgresql://airflow:airflow@postgres/airflow
    AIRFLOW__CELERY__BROKER_URL: redis://:@redis:6379/0
    AIRFLOW__CORE__FERNET_KEY: ''
    AIRFLOW__CORE__DAGS_ARE_PAUSED_AT_CREATION: 'true'
    AIRFLOW__CORE__LOAD_EXAMPLES: 'false'
    AIRFLOW__API__AUTH_BACKENDS: 'airflow.api.auth.backend.basic_auth,airflow.api.auth.backend.session'
    _PIP_ADDITIONAL_REQUIREMENTS: ${_PIP_ADDITIONAL_REQUIREMENTS:-}
  volumes:
    - ${AIRFLOW_PROJ_DIR:-.}/dags:/opt/airflow/dags
    - ${AIRFLOW_PROJ_DIR:-.}/logs:/opt/airflow/logs
    - ${AIRFLOW_PROJ_DIR:-.}/plugins:/opt/airflow/plugins
  user: "${AIRFLOW_UID:-50000}:0"
  depends_on:
    &airflow-common-depends-on
    redis:
      condition: service_healthy
    postgres:
      condition: service_healthy

services:
  postgres:
    image: postgres:13
    environment:
      POSTGRES_USER: airflow
      POSTGRES_PASSWORD: airflow
      POSTGRES_DB: airflow
    volumes:
      - postgres-db-volume:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD", "pg_isready", "-U", "airflow"]
      interval: 5s
      retries: 5
    restart: always

  flask:
    image: python:3.10
    container_name: flask_server
    ports:
      - 5005:5000
    healthcheck:
      test: ["CMD", "flask", "run", "--host", "0.0.0.0", "--port", "5005"]
      interval: 5s
      retries: 5

  redis:
    image: redis:latest
    expose:
      - 6379
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 5s
      timeout: 30s
      retries: 50
    restart: always

  airflow-webserver:
    <<: *airflow-common
    command: webserver
    ports:
      - 8080:8080
    healthcheck:
      test: ["CMD", "curl", "--fail", "http://localhost:8080/health"]
      interval: 10s
      timeout: 10s
      retries: 5
    restart: always
    depends_on:
      <<: *airflow-common-depends-on
      airflow-init:
        condition: service_completed_successfully

  airflow-scheduler:
    <<: *airflow-common
    command: scheduler
    healthcheck:
      test: ["CMD-SHELL", 'airflow jobs check --job-type SchedulerJob --hostname "$${HOSTNAME}"']
      interval: 10s
      timeout: 10s
      retries: 5
    restart: always
    depends_on:
      <<: *airflow-common-depends-on
      airflow-init:
        condition: service_completed_successfully

  airflow-worker:
    <<: *airflow-common
    command: celery worker
    healthcheck:
      test:
        - "CMD-SHELL"
        - 'celery --app airflow.executors.celery_executor.app inspect ping -d "celery@$${HOSTNAME}"'
      interval: 10s
      timeout: 10s
      retries: 5
    environment:
      <<: *airflow-common-env
      # Required to handle warm shutdown of the celery workers properly
      # See https://airflow.apache.org/docs/docker-stack/entrypoint.html#signal-propagation
      DUMB_INIT_SETSID: "0"
    restart: always
    depends_on:
      <<: *airflow-common-depends-on
      airflow-init:
        condition: service_completed_successfully

  airflow-triggerer:
    <<: *airflow-common
    command: triggerer
    healthcheck:
      test: ["CMD-SHELL", 'airflow jobs check --job-type TriggererJob --hostname "$${HOSTNAME}"']
      interval: 10s
      timeout: 10s
      retries: 5
    restart: always
    depends_on:
      <<: *airflow-common-depends-on
      airflow-init:
        condition: service_completed_successfully

  airflow-init:
    <<: *airflow-common
    entrypoint: /bin/bash
    # yamllint disable rule:line-length
    command:
      - -c
      - |
        function ver() {
          printf "%04d%04d%04d%04d" $${1//./ }
        }
        airflow_version=$$(AIRFLOW__LOGGING__LOGGING_LEVEL=INFO && gosu airflow airflow version)
        airflow_version_comparable=$$(ver $${airflow_version})
        min_airflow_version=2.2.0
        min_airflow_version_comparable=$$(ver $${min_airflow_version})
        if (( airflow_version_comparable < min_airflow_version_comparable )); then
          echo
          echo -e "\033[1;31mERROR!!!: Too old Airflow version $${airflow_version}!\e[0m"
          echo "The minimum Airflow version supported: $${min_airflow_version}. Only use this or higher!"
          echo
          exit 1
        fi
        if [[ -z "${AIRFLOW_UID}" ]]; then
          echo
          echo -e "\033[1;33mWARNING!!!: AIRFLOW_UID not set!\e[0m"
          echo "If you are on Linux, you SHOULD follow the instructions below to set "
          echo "AIRFLOW_UID environment variable, otherwise files will be owned by root."
          echo "For other operating systems you can get rid of the warning with manually created .env file:"
          echo "    See: https://airflow.apache.org/docs/apache-airflow/stable/howto/docker-compose/index.html#setting-the-right-airflow-user"
          echo
        fi
        one_meg=1048576
        mem_available=$$(($$(getconf _PHYS_PAGES) * $$(getconf PAGE_SIZE) / one_meg))
        cpus_available=$$(grep -cE 'cpu[0-9]+' /proc/stat)
        disk_available=$$(df / | tail -1 | awk '{print $$4}')
        warning_resources="false"
        if (( mem_available < 4000 )) ; then
          echo
          echo -e "\033[1;33mWARNING!!!: Not enough memory available for Docker.\e[0m"
          echo "At least 4GB of memory required. You have $$(numfmt --to iec $$((mem_available * one_meg)))"
          echo
          warning_resources="true"
        fi
        if (( cpus_available < 2 )); then
          echo
          echo -e "\033[1;33mWARNING!!!: Not enough CPUS available for Docker.\e[0m"
          echo "At least 2 CPUs recommended. You have $${cpus_available}"
          echo
          warning_resources="true"
        fi
        if (( disk_available < one_meg * 10 )); then
          echo
          echo -e "\033[1;33mWARNING!!!: Not enough Disk space available for Docker.\e[0m"
          echo "At least 10 GBs recommended. You have $$(numfmt --to iec $$((disk_available * 1024 )))"
          echo
          warning_resources="true"
        fi
        if [[ $${warning_resources} == "true" ]]; then
          echo
          echo -e "\033[1;33mWARNING!!!: You have not enough resources to run Airflow (see above)!\e[0m"
          echo "Please follow the instructions to increase amount of resources available:"
          echo "   https://airflow.apache.org/docs/apache-airflow/stable/howto/docker-compose/index.html#before-you-begin"
          echo
        fi
        mkdir -p /sources/logs /sources/dags /sources/plugins
        chown -R "${AIRFLOW_UID}:0" /sources/{logs,dags,plugins}
        exec /entrypoint airflow version
    # yamllint enable rule:line-length
    environment:
      <<: *airflow-common-env
      _AIRFLOW_DB_UPGRADE: 'true'
      _AIRFLOW_WWW_USER_CREATE: 'true'
      _AIRFLOW_WWW_USER_USERNAME: ${_AIRFLOW_WWW_USER_USERNAME:-airflow}
      _AIRFLOW_WWW_USER_PASSWORD: ${_AIRFLOW_WWW_USER_PASSWORD:-airflow}
      _PIP_ADDITIONAL_REQUIREMENTS: ''
    user: "0:0"
    volumes:
      - ${AIRFLOW_PROJ_DIR:-.}:/sources

  airflow-cli:
    <<: *airflow-common
    profiles:
      - debug
    environment:
      <<: *airflow-common-env
      CONNECTION_CHECK_MAX_COUNT: "0"
    # Workaround for entrypoint issue. See: https://github.com/apache/airflow/issues/16252
    command:
      - bash
      - -c
      - airflow

  # You can enable flower by adding "--profile flower" option e.g. docker-compose --profile flower up
  # or by explicitly targeted on the command line e.g. docker-compose up flower.
  # See: https://docs.docker.com/compose/profiles/
  flower:
    <<: *airflow-common
    command: celery flower
    profiles:
      - flower
    ports:
      - 5555:5555
    healthcheck:
      test: ["CMD", "curl", "--fail", "http://localhost:5555/"]
      interval: 10s
      timeout: 10s
      retries: 5
    restart: always
    depends_on:
      <<: *airflow-common-depends-on
      airflow-init:
        condition: service_completed_successfully

volumes:
  postgres-db-volume:

There is only one file in the dag folder - task.py. This is the task.py file which has the flask app and Dag that currently runs successfully within the container but not outside:
from datetime import datetime, timedelta
from flask import Flask
from airflow import DAG
from airflow.operators.python import PythonOperator
from airflow.providers.postgres.operators.postgres import PostgresOperator

#Flask
app = Flask(__name__)

@app.route('/')
def home():
    return '
Welcome to this fabulosity!
'

#DAG Functionalities
default_args = {
    'owner': 'Legend',
    'retry': 5,
    'retry_delay': timedelta(minutes=5)
}

def flask_app():
    app.run(host="0.0.0.0", port=5005)

with DAG(
    default_args=default_args,
    dag_id="dag_for_flask_V001",
    start_date=datetime(2023, 2, 6),
    schedule='@once',
    catchup=False
    ):
    call_flask = PythonOperator(
        task_id="call_flask",
        python_callable=flask_app
    )

call_flask

This is the output from the Dag when I test it on cmd using "airflow tasks test <dag_id> <task_id>". It shows the dag running and flask app running within the container.
AIRFLOW_CTX_DAG_RUN_ID=__***_temporary_run_2023-02-11T14:19:32.059234+00:00__
 * Serving Flask app 'unusual_prefix_be37952e5c0954e14de33c7cc81dd868f120aa78_tasks'
 * Debug mode: off
[2023-02-11 14:19:32,698] {_internal.py:224} INFO - WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on all addresses (0.0.0.0)
 * Running on http://127.0.0.1:5005
 * Running on http://172.21.0.7:5005
[2023-02-11 14:19:32,698] {_internal.py:224} INFO - Press CTRL+C to quit

This is the output when I curl the ip:port while the dag and flask is running on the container. It returns the expected response inside the container
airflow@963553c3a783:/opt/airflow$ curl 0.0.0.0:5005

Welcome to this fabulosity

airflow@963553c3a783:/opt/airflow$

This is the output when I stop testing the dag and flask app with CTRL+C. It shows the DagRun was successful.
[2023-02-11 14:05:00,645] {_internal.py:224} INFO - Press CTRL+C to quit
^C[2023-02-11 14:09:06,085] {python.py:177} INFO - Done. Returned value was: None
[2023-02-11 14:09:06,215] {taskinstance.py:1318} INFO - Marking task as SUCCESS. dag_id=dag_for_flask_V001, task_id=call_flask, execution_date=20230205T000000, start_date=, end_date=20230211T140906

This is the requirements.txt file
Flask==2.2.2
waitress==2.1.2

Content of .env file
AIRFLOW_UID=50000

This is the code structure I'm working with:
/etl_pipeline
│── logs
│── plugins
├── dags/
│   └── task.py
│── .env
│── docker-compose.yaml
│── Dockerfile
└── requirements.txt

Tried changing the ports, exposing the ports on both Dockerfile and docker-compose.yaml, there is no error message, does not display in browser or work outside the container.
Also, tried running a separate flask app using docker-compose and it works within and outside the container.


text:
Q: How to insert function in PDF document? Is anyone familiar with plugging a function into a PDF document (specifically, the "insert custom code" feature in Adobe Acrobat Pro)? I know it's possible to initiate a function on an event...but I'm not sure what event would best handle this. I'd assume a button press. Also, does anyone know which language is compatible with PDFs? Is Javascript the only one? I don't imagine a server-side code (like PHP or Ruby) would work. Or the use of a framework like JQuery. Maybe it's only ActionScript or some strict language like C#. I dunno :S

A: Have a look at this page on the Adobe Acrobat developer site:
http://www.adobe.com/devnet/acrobat/overview.html#JavaScript
This explains that the language you're referring to is JavaScript with a number of additional objects related to Acrobat itself exposed.
So if you want to add functionality inside a PDF file (commonly either as the result of a button press indeed, but you can also do field validation, things at document open etc...) it will have to be JavaScript. Read this page to get all details about JavaScript (including the reference):
http://www.adobe.com/devnet/acrobat/javascript.html


text:
Q: Not really a coding question, its about where "offline data" is stored on an android app and how to access it I play sports and our team uses the app "hudl" to upload recorded game film. I want to download playlists but I do not have permission to as I am not a coach or team admin. No, I'm not going to ask them. No, I'm not going to sign into one of their accounts. No, I don't feel like screen recording hours and hours worth of film. On the hudl mobile app I am able to click "offline download" film so I can watch it without having internet. It was like a 225 mb download or something. How can I access this downloaded film? No, I can't find it in my files or gallery. It's like saved into the app or some shit. Is there a way to pull this film from the app if it is stored locally in it? I am dumb and need people who know how this works. Sorry for asking an irrelevant question, though this is the first site I thought of to help me.

A: some apps save big file like video in internal storage. or external storage u can check the folder with (name of apps)  if u not find on there. try check in Android -> Data
but most of them encrypt the file so can only open via apps only.


text:
Q: Passenger on Big Sur potential privilege escalation vulnerability detected New installation of Passenger using homebrew on Big Sur.  Because of the new location (I'm coming from an El Capitan box) of homebrew installations inside /opt/homebrew, Passenger isn't happy because it's something I can see from the set permissions.  The error:
2021/03/19 09:22:16 [warn] 85#0: 1024 worker_connections exceed open file resource limit: 256
[ N 2021-03-19 09:22:16.2962 31353/T1 age/Wat/WatchdogMain.cpp:1373 ]: Starting Passenger watchdog...
[ N 2021-03-19 09:22:16.3519 31355/T1 age/Cor/CoreMain.cpp:1340 ]: Starting Passenger core...
[ N 2021-03-19 09:22:16.3521 31355/T1 age/Cor/CoreMain.cpp:256 ]: Passenger core running in multi-application mode.
[ W 2021-03-19 09:22:16.3944 31355/T1 age/Cor/CoreMain.cpp:1007 ]: WARNING: potential privilege escalation vulnerability detected. Phusion Passenger is running as root, and part(s) of the Passenger root path (/opt/homebrew/opt/passenger/libexec/src/ruby_supportlib/phusion_passenger/locations.ini) can be changed by non-root user(s):

 - /opt/homebrew/opt/passenger/libexec/src/ruby_supportlib/phusion_passenger/locations.ini is not secure: it can be modified by user rich
 - /opt/homebrew/opt/passenger/libexec/src/ruby_supportlib/phusion_passenger is not secure: it can be modified by user rich
 - /opt/homebrew/opt/passenger/libexec/src/ruby_supportlib is not secure: it can be modified by user rich
 - /opt/homebrew/opt/passenger/libexec/src is not secure: it can be modified by user rich
 - /opt/homebrew/opt/passenger/libexec is not secure: it can be modified by user rich
 - /opt/homebrew/opt/passenger is not secure: it can be modified by user rich
 - /opt/homebrew/opt is not secure: it can be modified by user rich
 - /opt/homebrew is not secure: it can be modified by user rich

It is a warming, but I'm not sure if it's limping or fully functional.
Should I worry?  Should I change anything?  Will this go away?  Seems it's been designed this way, but I see warnings.
Any insight appreciated.  Thank you.


text:
Q: Uncaught java.nio.channels.UnresolvedAddressException With Java 1.7, the following code
try
{
  sck = SocketChannel.open();
  sck.configureBlocking(false);

  sck.connect(new java.net.InetSocketAddress(**<bad remote ip address>**, remote_port));
  sel = Selector.open();

  ...
}
catch (IOException e)
{
  return false;
}

doesn't seem to catch the exception if the remote address is a bad DNS (for instance). What did I miss?

A: The UnresolvedAddressException is not a subclass of IOException, which is why you won't catch it if it's thrown.
UnresolvedAddressException is a subclass of IllegalArgumentException, as shown here, so try catching:

*

*UnresolvedAddressException itself, as it's always better practice to catch the most specific exception type first

*Exception if you don't really care about the exception you catch, as you can always halt the program or work around that

Edit: You probably missed that exception because the compiler did not force you to catch it. That is because UnresolvedAddressException is derived from RuntimeException, the type of exceptions which smack you in the head during execution. The exceptions not derived from RuntimeException, such as IOException, have to be caught, which is why your compiler probably told you to wrap your code into a try-catch block in the first place.

A: UnresolvedAddressException is not a child of IOException.
UnresolvedAddressException extends RuntimeException.
You can try to add catch closure with RuntimeException.


text:
Q: Creating a Notifications type feed in GAE Objectify I'm working on a notification feed for my mobile app and am looking for some help on an issue.
The app is a Twitter/Facebook like app where users can post statuses and other users can like, comment, or subscribe to them.
One thing I want to have in my app is to have a notifications feed where users can see who liked/comment on their post or subscribed to them.
The first part of this system I have figured out, when a user likes/comments/subscribes, a Notification entity will be written to the datastore with details about the event. To show a users Notification's all I have to do is query for all Notification's for that user, sort by date created desc and we have a nice little feed of actions other users took on a specific users account.
The issue I have is what to do when someone unlikes a post, unsubscribes or deletes a comment. Currently, if I were to query for that specific notification, it is possible that nothing would return from the datastore because of eventual consistency. We could imagine someone liking, then immediate unliking a post (b/c who hasn't done that? =P). The query to find that Notification might return null and nothing would get deleted when calling ofy().delete().entity(notification).now(); And now the user has a notification in their feed saying Sally liked his post when in reality she liked then quickly unliked it!
A wrench in this whole system is that I cannot delete by Key<Notification>, because I don't really have a way to know id of the Notification when trying to delete it.
A potential solution I am experimenting with is to not delete any Notifications. Instead I would always write Notification's and simply indicate if the notification was positive or negative. Then in my query to display notifications to a specific user, I could somehow only display the sum-positive Notification's. This would save some money on datastore too because deleting entities is expensive.

A: There are three main ways I've solved this problem before:

*

*deterministic key
for example
{user-Id}-{post-id}-{liked-by} for likes
{user-id}-{post-id}-{comment-by}-{comment-index} for comments
This will work for most basic use cases for the problem you defined, but you'll have some hairy edge cases to figure out (like managing indexes of comments as they get edited and deleted). This will allow get and delete by key

*parallel data structures

The idea here is to create more than one entity at a time in a transaction, but to make sure they have related keys. For example, when someone comments on a feed item, create a Comment entity, then create a CommentedOn entity which has the same ID, but make it have a parent key of the commenter user.
Then, you can make a strongly consistent query for the CommentedOn, and use the same id to do a get by key on the Comment. You can also just store a key, rather than having matching IDs if that's too hard. Having matching IDs in practice was easier each time I did this.
The main limitation of this approach is that you're effectively creating an index yourself out of entities, and while this can give you strongly consistent queries where you need them the throughput limitations of transactional writes can become harder to understand. You also need to manage state changes (like deletes) carefully.

*State flags on entities

Assuming the Notification object just shows the user that something happened but links to another entity for the actual data, you could store a state flag (deleted, hidden, private etc) on that entity. Then listing your notifications would be a matter of loading the entities server side and filtering in code (or possibly subsequent filtered queries).
At the end of the day, the complexity of the solution should mirror the complexity of the problem. I would start with approach 3 then migrate to approach 2 when the fuller set of requirements is understood. It is a more robust and flexible approach, but complexity of XG transaction  limitations will rear its head - but ultimately a distributed feed like this is a hard problem.

A: What I ended up doing and what worked for my specific model was that before creating a Notification Entity I would first allocate and ID for it:
 // Allocate an ID for a Notification
 final Key<Notification> notificationKey = factory().allocateId(Notification.class);
 final Long notificationId = notificationKey.getId();

Then when creating my Like or Follow Entity, I would set the property Like.notificationId = notificationId; or Follow.notificationId = notificationId;
Then I would save both Entities.
Later, when I want to delete the Like or Follow I can do so and at the same time get the Id of the Notification, load the Notification by key (which is strongly consistent to do so), and delete it too.
Just another approach that may help someone =D


text:
Q: How to prevent a bug to spread through future new features We are facing a problem implementing Git as our version control.  As soon as possible we want to implement full Git Flow.
Lets imagine this situation ( Branches: Develop & Master ):

*

*Maria is working on a new feature and at the end of the day she pushes it to Develop branch.

*Next day Bob will pull all the changes made into Develop and start to work on a NEW feature.

*At the end of the day, Bob also pushes his changes to Develop.

BUT, after that they discover that Maria's first push had a bug and they can't push it to production (Master). So Bob's code is now "infected" with Maria's Bug.
How to solve this or even prevent this kind of thing ?

A: You're thinking about version control all wrong. Nothing was "infected", a bug simply existed on develop, prior to it being shipped to production.  Bugs don't "spread through future releases", they simply exist until you fix them.
Either create a fix and merge it into develop, or create a revert for Maria's merge, and merge that into develop. Either way, the fix is to simply fix develop and move on. "Bob's code" didn't become "infected", the develop branch was just held up (hopefully briefly) by a bug.
You can't prevent this kind of thing. Bugs will appear in code, this is a fact of life. You just happened to catch the bug before it was shipped, this is a good thing, it's Git behaving as intended. You simply write a fix, add a regression test and move on.
If you're following Git Flow, this is even less of a problem: Both Maria and Bob's work would go into a release, which would undergo a round of testing and bug fixing before being shipped. If you intended to merge Bob's changes directly into master, and it's a problem that they're held up by waiting for a solid release branch, then they should have been considered a Hotfix from the very beginning.


text:
Q: Make variable accessible in all pug files Using pug-loader how can I make some vairable accessible to all pug/jade files. For example in express app I could do:
app.locals.assetPath = path.resolve('public/assets');
and the variable assetPath would be available in all jade files. But with webpack I am not able to do the same.
In my webpack.config.js I tried following but could not get work:
{
  test: /.pug$/,
  loader: 'pug',
  query: {
    root: path.join(__dirname, 'src/app'),

    /*globals: {assetPath: '/hard/coded/value'}*/ //WILL NOT WORK

    /*locals: {assetPath: '/hard/coded/value'}*/ //WILL NOT WORK

    /*locals: {assetPath: '/hard/coded/value'}, globals: ['assetPath']*/ //WILL NOT WORK
  }

A: From my experience, you have two options:

*

*use pug-html-loader instead;

*if you are using HtmlWebpackPlugin plugin, add custom properties to its config. They will be accessible through all pug templates.

Please, take a look at the detailed answer concerning the second and the first options.
Here is also the configuration example for the second option:
pug rule:
{
  test: /\.pug$/,
  loader: 'pug-loader',
  options: {
    // Use `self` namespace to hold the locals
    // Not really necessary
    self: true,
  },
}

HtmlWebpackPlugin options:
{
  filename: 'index.html',
  template: 'src/html/index.pug',
  // Your custom variables:
  production: (process.env.NODE_ENV === 'production')
}

index.pug template:
- const production = self.htmlWebpackPlugin.options.production

if production
  link( rel="stylesheet", type="text/css", href="style.css" )


text:
Q: unable to get One to Many (owner -> cars ) link from jhipster generated entities Using jhipster I have created application which is working fine then I have created 'A bi-directionnal one-to-many relationship', Owner to Car. That is also working fine but I could not able to figure out the way how all the cars will be displayed from Owner screen from the generated entities.  From Cars screen if I select 'Owner', relevant owner is getting displayed. Similarly from Owner screen if I select Owner Id, I want to display the list of his cars. But from my generated entity screens I did not find this feature. However the jhipster document says " we had a bi-directionnal relationship: from a Car instance you could find its owner, and from a Owner instance you could get all of its cars" . In  car screen I have a field for owner but in owner screen I don't have any link to display all the cars of a particular owner as stated above "from a Owner instance you could get all of its cars". How can I achieve it? From the document I feel this feature is in built from jhipster generated entities however I could not able to figure it out, can any one give sample code for Angular js and Spring Rest call to display all the cars of a particular owner from owners page (i.e., from http://localhost:8080/#/owners).
Owner.java
@Entity
@Table(name = "OWNER")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Owner implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "name")
    private String name;

    @Column(name = "age")
    private Integer age;

    @OneToMany(mappedBy = "owner")
    @JsonIgnore
    @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
    private Set<Car> cars = new HashSet<>();

}

OwnerResource.java
    @RestController
    @RequestMapping("/api")
    public class OwnerResource {
        private final Logger log = LoggerFactory.getLogger(OwnerResource.class);
        @Inject
        private OwnerRepository ownerRepository;

        @RequestMapping(value = "/owners",
                method = RequestMethod.POST,
                produces = MediaType.APPLICATION_JSON_VALUE)
        @Timed
        public ResponseEntity<Owner> create(@RequestBody Owner owner) throws URISyntaxException {
            log.debug("REST request to save Owner : {}", owner);
            if (owner.getId() != null) {
                return ResponseEntity.badRequest().header("Failure", "A new owner cannot already have an ID").body(null);
            }
            Owner result = ownerRepository.save(owner);
            return ResponseEntity.created(new URI("/api/owners/" + result.getId()))
                    .headers(HeaderUtil.createEntityCreationAlert("owner", result.getId().toString()))
                    .body(result);
        }

       @RequestMapping(value = "/owners",
            method = RequestMethod.PUT,
            produces = MediaType.APPLICATION_JSON_VALUE)
        @Timed
        public ResponseEntity<Owner> update(@RequestBody Owner owner) throws URISyntaxException {
            log.debug("REST request to update Owner : {}", owner);
            if (owner.getId() == null) {
                return create(owner);
            }
            Owner result = ownerRepository.save(owner);
            return ResponseEntity.ok()
                    .headers(HeaderUtil.createEntityUpdateAlert("owner", owner.getId().toString()))
                    .body(result);
        }

       @RequestMapping(value = "/owners",
                method = RequestMethod.GET,
                produces = MediaType.APPLICATION_JSON_VALUE)
        @Timed
        public ResponseEntity<List<Owner>> getAll(@RequestParam(value = "page" , required = false) Integer offset,
                                      @RequestParam(value = "per_page", required = false) Integer limit)
            throws URISyntaxException {
            Page<Owner> page = ownerRepository.findAll(PaginationUtil.generatePageRequest(offset, limit));
            HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/owners", offset, limit);
            return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
        }

 @RequestMapping(value = "/owners/{id}",
                method = RequestMethod.GET,
                produces = MediaType.APPLICATION_JSON_VALUE)
        @Timed
        public ResponseEntity<Owner> get(@PathVariable Long id) {
            log.debug("REST request to get Owner : {}", id);
            return Optional.ofNullable(ownerRepository.findOne(id))
                .map(owner -> new ResponseEntity<>(
                    owner,
                    HttpStatus.OK))
                .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
        }

    }

OwnerRepository.java
/**
 * Spring Data JPA repository for the Owner entity.
 */
public interface OwnerRepository extends JpaRepository<Owner,Long> {

}

The basic crud operation is working fine for Owner. But now I need to get all cars of a particular owner for that I need to add one rest call entry in OwnerResource.java and a method entry in OwneRepository.java. I tried different ways but getting many errors and is not working. The following is what I tried.
In OwnerRepository.java
Owner findAllByOwnerId(Long id);//But eclipse shows error here for this method

In OwnerResource.java
//Get All Cars
    @RequestMapping(value = "/{id}/cars",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE)
    @Timed
    public ResponseEntity<Owner> getAll(@PathVariable Long id) {
        log.debug("REST request to get All Cars of the Owner : {}", id);
        return Optional.ofNullable(ownerRepository.findAllByOwnerId(id))
            .map(owner -> new ResponseEntity<>(
                owner,
                HttpStatus.OK))
            .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

I need fix for this.

A: You could try this
In owner.java change
@OneToMany(mappedBy = "owner")
@JsonIgnore
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<Car> cars = new HashSet<>();

to
@OneToMany(mappedBy = "owner", fetch = FetchType.EAGER)
@JsonIgnoreProperties({"owner"})
private Set<Car> cars = new HashSet<>();

and similary in car.java
@ManyToOne
@JoinColumn(name = "owner_id")
@JsonIgnoreProperties({"cars"})
private Owner owner;

I'm new to spring as well but this helped me when I had a similar problem.


text:
Q: Restrict autocomplete to an array of polygons I have a map in which I want to use autocomplete, but only within some areas. I have managed to create bounds as a recangle with two coordinates:
const southWest = new google.maps.LatLng( 55.25877294, 12.45849609 );
const northEast = new google.maps.LatLng( 56.30282487, 14.28497314 );
const defaultBounds = new google.maps.LatLngBounds( southWest, northEast );

But what I actually need is to have an array of coordinates as bounds, so that I can't search outside of the areas.
Here is my current solution: JS-FIDDLE
(I have some example coordinates in there on line 47 and below, if needed)


text:
Q: Issue Loading MapView Anotations from a plist array - Xcode 4.2 I'm working on an iPhone application that displays a list of galleries on a Map.  The list of galleries comes from a plist which is downloaded from the web. The location coordinates are loading into the map correctly as well as the title and subtitle for each of the locations.
I am also able to load an image for the annotation view image from the plist.
The issue I'm having is that both the annotation view image and a detail view page load the information of the last location in the plist array rather than loading the information that corresponds to the correct location information.
I believe that the problem has to do with this integer:
for(int i=0; i < [galleries count]; i++)
but I'm honestly not sure.
Any help would be greatly appreciated!
Here is the code:
MapAnnotation.h
#import <Foundation/Foundation.h>
#import <MapKit/MKAnnotation.h>

@interface MapAnnotation : NSObject <MKAnnotation>{

CLLocationCoordinate2D coordinate;
NSString *title;
NSString *subTitle;

}

@property (nonatomic, assign) CLLocationCoordinate2D coordinate;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *subtitle;

@end

MapAnnotation.m
#import "MapAnnotation.h"

@implementation MapAnnotation
@synthesize coordinate, title, subtitle;

@end

MapViewViewController.h
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>

@interface MapViewViewController : UIViewController <MKMapViewDelegate, CLLocationManagerDelegate>{

NSMutableArray *galleries;
MKMapView *_MapView;
MKAnnotationView *Ann;

}

@property (nonatomic, retain) IBOutlet MKMapView *_MapView;

@property (nonatomic, retain) IBOutlet MKAnnotationView *Ann;

@property (nonatomic, retain) NSArray *addressArray;

@property (nonatomic, retain) NSMutableArray *galleries;

@property (nonatomic, retain) NSString *imageUrl;

@property (nonatomic, retain) NSData *imagedata;

-(IBAction)getlocation;

- (void)loadAnnotations;

@end

MapViewViewController.m
#import "MapViewViewController.h"
#import "MapAnnotation.h"
#import "MoredetailViewController.h"

@implementation MapViewViewController
@synthesize _MapView, Ann;
@synthesize galleries, addressArray;
@synthesize imagedata, imageUrl;

- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];

[galleries removeAllObjects];

addressArray=[[NSMutableArray alloc]initWithContentsOfURL:[NSURL URLWithString:@"http://www.jimirobinson.com/plist/MapInformation.plist"]];

galleries = [[NSMutableArray alloc] initWithArray:addressArray];

[self loadAnnotations];

}

- (void)viewDidLoad
{
[super viewDidLoad];

MKCoordinateRegion region;
region.center.latitude = 39.952133;
region.center.longitude = -75.144264;
region.span.longitudeDelta = 0.005;
region.span.latitudeDelta = 0.001;

[_MapView setRegion:region animated:YES];
}

-(IBAction)getlocation {
_MapView.showsUserLocation = YES;
}

- (void)loadAnnotations {

CLLocationCoordinate2D pinCoordinates;

for (int i = 0; i < [galleries count]; i++)
{

    MapAnnotation *myAnnotations = [[MapAnnotation alloc] init];

    pinCoordinates.latitude = [[[galleries objectAtIndex:i] objectForKey:@"latitude"] floatValue];
    pinCoordinates.longitude = [[[galleries objectAtIndex:i] objectForKey:@"longitude"] floatValue];
    [myAnnotations setTitle:[[galleries objectAtIndex:i] objectForKey:@"annotation_title"]];
    [myAnnotations setSubtitle:[[galleries objectAtIndex:i] objectForKey:@"annotation_subtitle"]];

    imageUrl = [[galleries objectAtIndex:i] objectForKey:@"map_pin_image_url"];
    imagedata = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrl]];

    [myAnnotations setCoordinate:pinCoordinates];
    [_MapView addAnnotation:myAnnotations];

}

                    }

- (MKAnnotationView *)mapView :(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{

MKAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:@"AddrAnnot"];

annotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"AddrAnnot"];

    if (_MapView.userLocation == annotation)
            {
            return nil;
            }

annotationView.image = [UIImage imageWithData:imagedata];
annotationView.canShowCallout = YES;
[annotationView setBackgroundColor:[UIColor clearColor]];
[annotationView setFrame:CGRectMake(0, 0, 30, 30)];
annotationView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
annotationView.leftCalloutAccessoryView =  [[UIImageView  alloc] initWithImage:[UIImage imageNamed:@"flag1.png"]];

[_MapView addAnnotation:annotation];
return annotationView;

NSLog(@"%s: annotationView=%@", __func__, annotationView);

}

- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{

MoredetailViewController *moredetail = [self.storyboard instantiateViewControllerWithIdentifier:@"TextPage"];
[self.navigationController pushViewController:moredetail animated:YES];

for(int i=0; i < [galleries count]; i++)
{
    moredetail.MoredetailTitle.text = [[galleries objectAtIndex:i] objectForKey:@"annotation_title"];

    moredetail.MoredetailDescription.text = [[galleries objectAtIndex:i] objectForKey:@"annotation_subtitle"];
    NSLog(@"%d", i);

    NSString *image = [[galleries objectAtIndex:i] objectForKey:@"map_pin_image_url"];
    NSData *dataz = [NSData dataWithContentsOfURL:[NSURL URLWithString:image]];
    moredetail.detailImage.image = [UIImage imageWithData:dataz];
}

NSLog(@"I've been tapped");

}

- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views {

NSLog(@"%s: galleries=%@", __func__, galleries);

}

- (void)viewDidUnload
{
    [super viewDidUnload];
}

@end

MapInformation.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
<dict>
    <key>title</key>
    <string>Gallery One</string>
    <key>annotation_title</key>
    <string>Gallery One Title</string>
    <key>annotation_subtitle</key>
    <string>Gallery One Subtitle</string>
    <key>map_pin_image_url</key>
    <string>http://www.jimirobinson.com/plist/flag1.png</string>
    <key>latitude</key>
    <real>39.952827</real>
    <key>longitude</key>
    <real>-75.145203</real>
</dict>
<dict>
    <key>title</key>
    <string>Gallery Two</string>
    <key>annotation_title</key>
    <string>Gallery Two Title</string>
    <key>annotation_subtitle</key>
    <string>Gallery Two Subtitle</string>
    <key>map_pin_image_url</key>
    <string>http://www.jimirobinson.com/plist/flag2.png</string>
    <key>latitude</key>
    <real>39.952184</real>
    <key>longitude</key>
    <real>-75.145368</real>
</dict>
<dict>
    <key>title</key>
    <string>Gallery Three</string>
    <key>annotation_title</key>
    <string>Gallery Three Title</string>
    <key>annotation_subtitle</key>
    <string>Gallery Three Subtitle</string>
    <key>map_pin_image_url</key>
    <string>http://www.jimirobinson.com/plist/flag3.png</string>
    <key>latitude</key>
    <real>39.951135</real>
    <key>longitude</key>
    <real>-75.143368</real>
</dict>
</array>
</plist>

A: I'm afraid to say but this code needs lots of work in order to work as you expect.
Firstly, imagedata is an instance variable, and you are setting it to be the image data of the last annotation (in loadAnnotations).  viewForAnnotation then uses imagedata for the image, so it will always be set to the image for the last annotation.
Secondly, in calloutAccessoryControlTapped you are iterating over all the galleries, and setting properties on the moredetail view controller, so that the view controller will always show detail for the last gallery.
I suggest that you add more properties to your MapAnnotation class, such as imageUrl. You can then set this property when creating the annotations. In viewForAnnotation you can then do this:
if ([annotation isKindOfClass:[MapAnnotation class]])
{
      MapAnnotation *mapAnnotation = (MapAnnotation *)annotation;
      annotationView.image = [NSData dataWithContentsOfURL:[NSURL URLWithString:[mapAnnotation imageURL]];

And in the calloutAccessoryControlTapped method you can do this:
MapAnnotation *mapAnnotationPressed = (MapAnnotation *)view.annotation;
moredetail.MoredetailTitle.text = [mapAnnotationPressed title];

I hope this gives you some idea of how to get your code working.


text:
Q: Occurrences of reäl with diæresis? It just occurred to me that writing reäl with a diæresis is useful for indicating the pronunciation /rɪəl/ rather than /ri(ə)l/ (or /riːl/?).  Are there any occurrences of this in literature?  (Is there a freely available corpus of English lit. that will settle this?)

A: There seems to be at least one text where a dieresis occurs over the "e" in "real", but I think that in practice, this is no longer an option in normal English writing.
From Google Books:

*

*

And they have indeed a great influënce, when preſented in his Spirit, as aforeſaid, to work in our hearts true and reäl repentance from all our ſins

(The Way to the City of God Described, Etc, 1678)


text:
Q: How to detect more than one intent with IBM Watson Assistant? Can the IBM Watson Conversation / Assistant service detect more than one intention in a single sentence?
Example of input:

play music and turn on the light

*

*Intent 1 is #Turn_on

*Intent 2 is #Play

==> the answer must be simultaneous for both intents: Music played and light turned on
If so, how can I do that?

A: Yes, Watson Assistant returns all detected intents with their associated confidence. See here for the API definition. In the response returned by Watson Assistant is n array of intents recognized in the user input, sorted in descending order of confidence.
The documents have an example on how to deal with multiple intents and their confidence. Be also aware of a setting alternate_intents to allow even more intents with lower confidence to be returned.

A: While @data_henrik is correct in how to get the other intents, it doesn't mean that the second question is related.
Take the following example graph, where we map the intents versus confidence that comes back:

Here you can clearly see that there are two intents in the persons question.
Now look at this one:

You can clearly see that there is only one intent.
So how do you solve this? There are a couple of ways.

*

*You can check if the first and second intent fall within a certain percentage of each other. This is the easiest to detect, but tricker to code to select two different intents. It can get messy, and you will sometimes get false positives.

*At the application layer you can do a K-Means on the intent result. K-Means will allow you to group intents by buckets, so you create two buckets (K=2), and if there is more than one in the first bucket, you have a compound question. I wrote about this and a sample on my site.

*There is a new feature you can play with in Beta called "Disambiguation". This allows you to flag intent nodes with a question to ask to get it. Then if two questions are found it will say "Did you mean? ...." and the user can select.

A: IS this disambiguation feature available in non production environments, on Beta?


text:
Q: Declaring a binary integer constant So, I am implementing a DES (Data Encryption Standard) in Java and need to declare the key as a binary value of 64 bits and do not know how to do this. Could anyone help me?
I would like to say something like this: int = K 000100110011010001010111011110011001101110111100110111111110001;
However, the IDE always beeps error saying that it is a very large integer.

A: If you are using Java 7 or higher, you can specify binary constants by prepending "0b" to your value, e.g.:
long value = 0b000100110011010001010111011110011001101110111100110111111110001L;

If that language feature is not available to you, you can use decimal, octal, or hexadecimal notation, however. If you're just declaring constants, you can use an online tool such as http://www.mathsisfun.com/binary-decimal-hexadecimal-converter.html, or perhaps your favorite calculator, to convert to a radix that Java recognizes.
For example:
long value = 691913582662545393L;

Or:
long value = 0x99A2BBCCDDE6FF1L;

You may want to clarify by describing what that value means in a comment:
// binary: 000100110011010001010111011110011001101110111100110111111110001
long value = 0x99A2BBCCDDE6FF1L;

As you may have noticed from the above examples, you will need to use a long and add the L suffix to your constant. In Java, int is 32-bit and long is 64-bit. The L suffix specifies a long literal, without it, it is an int and the value would be too large.
P.S. Integer literals starting with "0" (but not "0x" or "0b") are interpreted as octal. The constant you originally attempted to specify was interpreted as a very large octal number.

A: Put 0b in front of your number to tell Java it's in binary (only for Java 7 and up). Otherwise, convert to hex.


text:
Q: Download attachment from Outlook using Python I am trying to download attachments from Outlook using Python, as of now am able to download the attachments by subject line but in my case I want to download multiple attachments from multiple emails where subject line starts with some string, For Ex:
Subjects are: Query 123654, Query 56975, Query 5698 like this and I want to download all of them where subject name starts with "Query".
My current code is below:
from win32com.client import Dispatch
outlook = Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder("6")
all_inbox = inbox.Items
val_date = datetime.date.today()

sub_today = 'Query 123654'
att_today = ''
for msg in all_inbox:
    if msg.Subject == sub_today and msg.Senton.date() == val_date:
        break

for att in msg.Attachments:
    if att.FileName == att_today:
        break

try:
    att.SaveAsFile('C:\\Offline Feeds\\Attachments' + '\\'+ att.FileName)
    messagebox.showinfo("SUCCESSFUL","Attachments Downloaded")
except:
    messagebox.showerror("ERROR","Attachment Download Failed")

A: You could use find() to search  specific data.
sub_today = 'Query'

if msg.Subject.find(sub_today) != -1 break

If subject not include "Query", it will return "-1".
This is the complete code:
from win32com.client import Dispatch
outlook = Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder("6")
all_inbox = inbox.Items
val_date = datetime.date.today()

sub_today = 'Query'
att_today = ''
for msg in all_inbox:
    if msg.Subject.find(sub_today) != -1 and msg.Senton.date() == val_date:
        break

for att in msg.Attachments:
    if att.FileName == att_today:
        break

try:
    att.SaveAsFile('C:\\Offline Feeds\\Attachments' + '\\'+ att.FileName)
    messagebox.showinfo("SUCCESSFUL","Attachments Downloaded")
except:
    messagebox.showerror("ERROR","Attachment Download Failed")

For more information, please refer to this link:
Python String find() Method


text:
Q: How to Switch Widgets after certain time in Flutter? I am facing problems with this tematic, I would like to change a widget after certain time. e.g
I have this animatedFlutter Screen (screen 1) and then after the animation end I would like to change the screen to any screen that I have, for example. Login();
Any tips? Thanks.
import 'package:flutter/material.dart';
import 'dart:async';

void main() => runApp(AnimatedFlutterLogo());

class AnimatedFlutterLogo extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => new _AnimatedFlutterLogoState();

}

class _AnimatedFlutterLogoState extends State<AnimatedFlutterLogo> {
  Timer _timer;
  FlutterLogoStyle _logoStyle = FlutterLogoStyle.markOnly;

  _AnimatedFlutterLogoState() {
    _timer = new Timer(const Duration(milliseconds: 800), () {
      setState(() {
        _logoStyle = FlutterLogoStyle.horizontal;
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    _timer.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return new FlutterLogo(
      size: 200.0,
      textColor: Colors.white,
      style: _logoStyle,

    );
  }
}

A: try this,
_Act_NotificationScreenState() {
_timer = new Timer(const Duration(milliseconds: 800), () {
  setState(() {
    _logoStyle = FlutterLogoStyle.horizontal;
  });
  _timer = new Timer(const Duration(seconds: 1), () {
      Navigator.push(context, MaterialPageRoute(builder: (context) => Act_Login()));
  });
});
}

A: You need to write code of navigating to another screen (Widget in case of Flutter)
Navigator.push(
    context,
    MaterialPageRoute(builder: (context) => Login()),
  );

You need to import Login in your current screen.

A: Wrap your AnimatedFlutterLogo with MaterialApp and in the callback function of Timer use Navigator to navigate to respective Page
Example:
import 'package:flutter/material.dart';
import 'dart:async';

void main() => runApp(MaterialApp(home:AnimatedFlutterLogo()));

class AnimatedFlutterLogo extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => new _AnimatedFlutterLogoState();

}

class _AnimatedFlutterLogoState extends State<AnimatedFlutterLogo> {
  Timer _timer;
  FlutterLogoStyle _logoStyle = FlutterLogoStyle.markOnly;

  _AnimatedFlutterLogoState() {
    _timer = new Timer(const Duration(milliseconds: 800), () {
       setState(() {
        _logoStyle = FlutterLogoStyle.horizontal;
      });
    Navigator.push(                      //<-- Navigate to loginPage on Timeout
    context,
    MaterialPageRoute(builder: (context) => LoginPage()),
  );
    });
  }

  @override
  void dispose() {
    super.dispose();
    _timer.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return new FlutterLogo(
      size: 200.0,
      textColor: Colors.white,
      style: _logoStyle,

    );
  }
}

class LoginPage extends StatelessWidget{
  @override
  Widget build(BuildContext context){
    return Container(alignment: Alignment.center,child: Text("LOG IN PAGE"));
  }
}


text:
Q: My laptop, and only my laptop, keeps disconnecting from wifi signal booster I have a signal booster (or router, I don't really know the difference) and my android, other laptops connect and keep connected to this signal booster without a problem. The thing is, with my new laptop I get periodically  disconnected from the internet, but still connected to the wifi network. While all the other laptops and devices don't have this problem whatsoever. It's worth to mention that my laptop's wifi works flawlessly with other wifi netoworks, it's only with this one that I have this problem. Maybe it has something to do with the fact that my laptop is new and this signal booster is old?
Thanks