text:
Q: Cloud Anchor delegate methods not called Hey guys I am trying to retrieve and display a cloud anchor from my IOS app and never receive a delegate callback from resolve cloud anchor here is my view controller :
class ShowBooViewController: UIViewController,GARSessionDelegate, ARSessionDelegate  {

var garSession : GARSession? = nil
var arScene : SCNScene? = nil

@IBOutlet weak var arSceneView: ARSCNView!
@IBAction func showBoo(_ sender: UIButton) {

    let ac = UIAlertController(title: "Enter answer", message: nil, preferredStyle: .alert)
    ac.addTextField()

    let submitAction = UIAlertAction(title: "Submit", style: .default) { [unowned ac] _ in
        //let answer = ac.textFields![0]
        // do something interesting with "answer" here

    }

    ac.addAction(submitAction)
    present(ac, animated: true)
}

override func viewDidLoad() {
    super.viewDidLoad()

    do {
        try self.garSession = GARSession.init(apiKey: "RedactedCuzSuperSecret",bundleIdentifier: nil)
        self.garSession?.delegate = self

        do {
            try self.garSession!.resolveCloudAnchor(withIdentifier: "bgfbgfbgf")
        } catch {
            print("Failed")
        }
    } catch {
        print("Failed")
        print(error)
    }
}

func session(_ session: GARSession, didResolve anchor: GARAnchor) {
    print("session")

}

func session(_ session: GARSession, didFailToResolve anchor: GARAnchor) {

    print("Session")
}

func session(_ session: GARSession, didHostAnchor anchor: GARAnchor) {
    print("Session")

}

func session(_ session: GARSession, didFailToHostAnchor anchor: GARAnchor) {
    print("Session")

}

}
The api key was changed to not post here but I have the actual api key in view controller, when using Xcode inspector I see that the delegate is assigned to the view controller I just do not get the session callbacks.


text:
Q: Importing Pandas Terminates Eclipse PyDev Debugger when I add PyInstaller I'm getting an odd termination in the PyDev debugger in Eclipse.  Running the following works fine.
import pandas as pd

def main():
    print('hello')
    pd.Series([])

if __name__ == '__main__':
    main()

When I debug the same code with a breakpoint on line 1 it works so far.

If I step over one step (F6 or pressing the button) however it terminates itself with an ugly exit value (-1073741819), but no error in the console.

This happens when I debug almost any of the code I have except for the most basic things.  I tried running "eclipse.exe -clean" but it didn't seem to clear the problem.
Edit:
It is clearly installing pyinstaller that is the issue
conda install -c conda-forge pyinstaller

if I revert to a previous revision the debugger works again.  Oddly I don't even need to restart eclipse for it to fix itself.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to do block indentation in kate? Question is pretty self-explanatory.
How to do block indentation in kate (KDE Advanced Text Editor)?

A: Ctrl+I does it as commented by @DavidPostill
For removing indentation, Ctrl+Shift+I does the job.


text:
Q: \multicolumn in array not showing column separator I'm trying to write three columns of equations separated by vertical lines in an array, but when I use the multicolumn command it doesn't show the column separator. I've tried using the multicols package but it messes up the formatting.
\[
\begin{array}{>{\displaystyle}r>{\displaystyle}l|>{\displaystyle}r>{\displaystyle}l|>{\displaystyle}r>{\displaystyle}l}
\frac{\delta^2\psi_L}{\delta x^2}& = -k^2Ce^{ikx}-k^2Re^{-ikx}&\frac{\delta^2\psi_C}{\delta x^2}& = A\kappa^2e^{\kappa x}+B\kappa^2e^{-\kappa x}&\frac{\delta^2\psi_R}{\delta x^2}& = -Tk^2e^{ikx}\\
&&&&&\\
&=-k^2\psi_L&&=\kappa^2\psi_C&&=-k^2\psi_R\\
&&&&&\\
&=-\frac{2mE}{\hbar^2}\psi_L&&=\frac{2m(V-E)}{\hbar^2}\psi_C&&=-\frac{2mE}{\hbar^2}\psi_R\\
&&&&&\\
\multicolumn{2}{l}{\mbox{Substitute into (1), }V=0}&\multicolumn{2}{c}{\mbox{Substitute into (1)}}&\multicolumn{2}{c}{\mbox{Substitute into (1), }V=0}\\
&&&&&\\
E\psi_L&=E\psi_L&(E-V)\psi_C&=(E-V)\psi_C&E\psi_R&=\psi_R\\
\end{array}
\]

A: You can use
\multicolumn{2}{l|}{\mbox{Substitute into (1), }V=0}

to give you a vertical rule at the end of your multicolumn. Here's a complete MWE:
% arara: pdflatex
% !arara: indent: {overwrite: yes}
\documentclass{article}
\usepackage{array}

\begin{document}

\[
    \begin{array}{>{\displaystyle}r>{\displaystyle}l|>{\displaystyle}r>{\displaystyle}l|>{\displaystyle}r>{\displaystyle}l}
        \frac{\delta^2\psi_L}{\delta x^2} & = -k^2Ce^{ikx}-k^2Re^{-ikx} & \frac{\delta^2\psi_C}{\delta x^2} & = A\kappa^2e^{\kappa x}+B\kappa^2e^{-\kappa x} & \frac{\delta^2\psi_R}{\delta x^2} & = -Tk^2e^{ikx}              \\
                                          &                             &                                   &                                                &                                   &                             \\
                                          & =-k^2\psi_L                 &                                   & =\kappa^2\psi_C                                &                                   & =-k^2\psi_R                 \\
                                          &                             &                                   &                                                &                                   &                             \\
                                          & =-\frac{2mE}{\hbar^2}\psi_L &                                   & =\frac{2m(V-E)}{\hbar^2}\psi_C                 &                                   & =-\frac{2mE}{\hbar^2}\psi_R \\
                                          &                             &                                   &                                                &                                   &                             \\
        \multicolumn{2}{l|}{\mbox{Substitute into (1), }V=0}&\multicolumn{2}{c|}{\mbox{Substitute into (1)}}&\multicolumn{2}{c}{\mbox{Substitute into (1), }V=0}\\
                                          &                             &                                   &                                                &                                   &                             \\
        E\psi_L                           & =E\psi_L                    & (E-V)\psi_C                       & =(E-V)\psi_C                                   & E\psi_R                           & =\psi_R                     \\
    \end{array}
\]
\end{document}

As a note: it looks you are hard coding a reference using (1); it's best to avoid this kind of thing, and use \ref, \eqref and friends.
You can get better spacing around your = symbols by using
    \begin{array}{>{\displaystyle}r@{}>{\displaystyle}l|>{\displaystyle}r@{}>{\displaystyle}l|>{\displaystyle}r@{}>{\displaystyle}l}

which removes the column separation; furthermore, you can use, for example
    \renewcommand{\arraystretch}{3}

and remove the empty rows to set the row spacing.

% arara: pdflatex
% !arara: indent: {overwrite: yes}
\documentclass{article}
\usepackage{array}

\begin{document}

\[
    \renewcommand{\arraystretch}{3}
    \begin{array}{>{\displaystyle}r@{}>{\displaystyle}l|>{\displaystyle}r@{}>{\displaystyle}l|>{\displaystyle}r@{}>{\displaystyle}l}
        \frac{\delta^2\psi_L}{\delta x^2} & {}= -k^2Ce^{ikx}-k^2Re^{-ikx} & \frac{\delta^2\psi_C}{\delta x^2} & {}= A\kappa^2e^{\kappa x}+B\kappa^2e^{-\kappa x} & \frac{\delta^2\psi_R}{\delta x^2} & {}= -Tk^2e^{ikx}              \\
                                          & {} =-k^2\psi_L                &                                   & {}=\kappa^2\psi_C                                &                                   & {} =-k^2\psi_R                \\
                                          & {}=-\frac{2mE}{\hbar^2}\psi_L &                                   & {} =\frac{2m(V-E)}{\hbar^2}\psi_C                &                                   & {}=-\frac{2mE}{\hbar^2}\psi_R \\
        \multicolumn{2}{l|}{\mbox{Substitute into (1), }V=0}&\multicolumn{2}{c|}{\mbox{Substitute into (1)}}&\multicolumn{2}{c}{\mbox{Substitute into (1), }V=0}\\
        E\psi_L                           & {} =E\psi_L                   & (E-V)\psi_C                       & {} =(E-V)\psi_C                                  & E\psi_R                           & {} =\psi_R                    \\
    \end{array}
\]

\end{document}

Following egreg's suggestion, you can also use a new column type:
\newcolumntype{M}{>{\displaystyle}r@{}>{\displaystyle}l}

which allows you to write
\begin{array}{M|M|M}

You might also like to center the entries on the last row:
    \multicolumn{2}{c|}{E\psi_L=E\psi_L}                   & \multicolumn{2}{c|}{(E-V)\psi_C=(E-V)\psi_C}                                  & \multicolumn{2}{c}{E\psi_R=\psi_R}                    \\


text:
Q: PHP - Echo array value foreach array count I have the following PHP code
$businessWebsite = 'http://www.times.hello.com.uk/articles/view/20.141013/local/police-killer.gets-10-more-months-over-drugs.539550';
$host = parse_url($businessWebsite, PHP_URL_HOST );
$parts = explode( '.', $host);
//$parts = array_reverse( $parts );

$domain = $parts[1].'.'.$parts[2].'.'.$parts[3].'.'.$parts[4];

print_r($parts);

echo $domain;

This echo's times.hello.com.uk this is made up of four parts
Array
(
    [0] => www
    [1] => times
    [2] => hello
    [3] => com
    [4] => uk
)

Let us say my domain is     $businessWebsite = 'http://www.times.com.uk/articles/view/20.141013/local/police-killer.gets-10-more-months-over-drugs.539550';
It would echo times.hello.com.. I would end up with two dots at the end.
If the domain is $businessWebsite = 'http://www.times.com/articles/view/20.141013/local/police-killer.gets-10-more-months-over-drugs.539550';
It would echo times.com... I would end up with three dots at the end.
How do I go solving the problem?
I want to remove the double and triple dots at the end.

A: Use PHP's trim and implode.
As you said you want to remove double and triple dots at the end of the string:
$domain = implode('.',$parts);

$domain = trim($domain, '.');

print $domain;

A: Take a look at phps implode() function.
This allows to do something like this:
echo implode('.', $parts);

A: PHP has an implode method:
$domain = implode('.',$parts);

You can remove the first item of parts prior to imploding:
array_shift($parts);


text:
Q: Two tuples as one element in python list I am now getting used to python lists. But I encountered a complicated list and I have troubles parsing it.
prediction=[('__label__inflation_today', 0.8),('__label__economic_outlook', 0.2)]

I am trying to present this prediction in a better way, something like excel.
predicted label              probability
Inflation_today              0.8
Economic_outlook             0.2

A: You can try
for x in prediction:
   string=x[0].replace('__label__','')
   print(string,":",x[1])

inflation_today : 0.8
economic_outlook : 0.2

If you want to access it using those names, you can also create a dictionary
d={}
for x in prediction:
   string=x[0].replace('__label__','')
   d[string]=x[1]

d
{'economic_outlook': 0.2, 'inflation_today': 0.8}

d['economic_outlook']
0.2

A: One possible solution is pandas DataFrame,
then use Series.str.replace:
import pandas as pd
prediction=[('__label__inflation_today', 0.8), ('__label__economic_outlook', 0.2)]
df = pd.DataFrame(prediction, columns=['predicted label',' probability'])

df['predicted label'] = df['predicted label'].str.replace('__label__', '')

print (df)
    predicted label   probability
0   inflation_today           0.8
1  economic_outlook           0.2

If need only data use DataFrame.to_string:
print (df.to_string(index=False, header=None))
inflation_today  0.8
economic_outlook  0.2


text:
Q: Show that the map $P:\Bbb R^3\to\Bbb R,\;(x,y,z)\mapsto z$ is surjective. I need help to show that the map $P:\Bbb R^3\to\Bbb R,\;(x,y,z)\mapsto z$ is surjective.
It seems easy, but I dont know how to prove it. I can show easily it is not injective, just take an example of $P(1,1,0) = 0$, thus not only $(0,0,0)$ is zero, thus it is not injective. That is the easy part.
The question is: how do I show there exist only one image of the function?
Because I have to show the kernel is only two dimensions, while the image is one. That is my problem. Please guide me on how to do it.
Thanks.
(I mean, what should I think of doing here for this )
Edit:
$\mathbb{R}^3\to\mathbb{R}$
Which is the reason I am having trouble. Linear is easy, this is calculus 3, which is why I am having trouble.

A: Let $\varphi:F \mapsto K$ be a function from $F$ to $K$, the definition of $\varphi$ being surjective is that $\forall k \in K, \exists f \in F$ such that $\varphi(f) = k$.
With your example, this is very simple. Take $z \in \mathbb{R}$ then take $(0,0,z) \in \mathbb{R}^3$ and we have $P(0,0,z) = z$ as needed.
If you want to use kernal then $\ker(\varphi) = \{(a,b,c) \in \mathbb{R}^3 : \varphi(a,b,c) = 0\} = \{(a,b,0) : a,b \in \mathbb{R}\}$ so we can see that the kernel has dimension 2


text:
Q: How to select highly variable genes in bulk RNA seq data? As a pre-processing step, I need to select the top 1000 highly variable genes (rows) from a bulk RNA-seq data which contains about 60k genes across 100 different samples(columns). The column value already contains the mean of the triplicates. The table contains normalized value in FPKM (Note: I don't have access to raw counts and am not able to use common R packages as these packages takes raw counts as input.)
In this case, what is the best way to select the top 1000 variable genes ?
I have tried to filter out the genes using rowSums() function (to remove the genes with lower rowsums values) and narrowed it down from 60k genes to 10K genes but I am not sure if it the right way to select highly variable genes. Any input is appreciated.

A: row sum is first filtration step. after this your data will discarded by log2fold change cutoff and padjst value (0.05 or o.o1 depend on your goal). you can repeat this pathway with different row sum cutoff to see results. I personal discard row sums zero


text:
Q: Signaling PLC with Raspberry Pi I want to give signal via PLC to Raspberry Pi and when the raspberry pi gets that signal, it should run the python script and when the python script execute properly and cycle is completed, it should wait for the other signal from PLC to again run the same script and same cycle should go on.
Please provide some suggestions.

A: Via Network:
Depending on your PLC, you could use UDP or TCP, where a Python program on Raspberry listens and sends commands. Depending on the command received, different scripts ou actions could be executed. There are many Python examples for using this on the internet.
For the PLC it can be a little more complicated to find and it will depend on the model and manufacturer, I recommend that you check your supplier's documentation.
Discrete Inputs:
I don't recommend it, but if it's impossible to use a network, you could use discrete digital inputs (like buttons do) to trigger the scripts on the Raspberry, but it must have an interface with relays or optocouplers between the PLC and the Raspberry due to differences in types of electrical signals. In this mode, scripty in pyton keeps checking the status of a digital input and triggers the action when the status of the input changes.
Note:

*

*Note that in both cases the program remains running (in an infinite loop), waiting for the command.

*Additional care must be taken when using the Raspberry in an industrial environment due to possible interference by EMC. If using digital inputs, consider applying filters to the signal and shilded cables.


text:
Q: Retrieve iframe values to client side page How can I retrieve values from the iframe form id, and call it to my client side html.
(client side html)
sample.html
<head>
    <script>
        function alertThis(){
            alert(parent.myframe.formsubmit.a_token.value);
        }
    </script>
</head>

<body>

    <iframe name = "myframe" src="http://domain.com/sample/index.php">
    <button onClick = "alertThis();">Click Here</button>

</body>

(server side php)
index.php
<form name = "formsubmit">
      <input id = "a_token"  value="<?php echo $_SESSION['user'] ?>"/>
</form>

but it does not return any.

A: Try this codepeace
<iframe name="myframe" id="myframe" src="http://domain.com/sample/index.php">

function alertThis(){
   var content = window.frames['myframe'].document.forms['formsubmit'].elements['a_token'].value;
   alert(content);
}

EDIT
Same issue has sorted using jQuery
Get radio value inside iframe
$('#myframe').contents().find('a_token').val()

A: var doc = window.frames['myframe'].document.getElementById('a_token').value;
alert(doc);
try this.


text:
Q: A polite substitution for "lamer" Is there a polite word that can be used to designate someone who didn't really understand what he or she was doing? Or, in general, someone who is intentionally ignorant of how things work. A "lamer" doesn't fit for being impolite, and seemingly harming some people's ears too much.
Edit: Another good definition is

It distinguishes between people who
  are ignorant by chance from those who
  are ignorant by choice.

And it makes me think that there is no polite substitution just because the meaning itself being impolite and abusive. Right?

A: Novice?  Unaware of [whatever]?  Edit: A self-appointed expert?
The problem is that implying that someone intentionally ignorant of something is inherently discourteous.  All of the polite variants you'll find will be implying that the ignorance is unintentional.

A: Shamelessly copied and pasted from NOAD:

Someone who knows nothing about growing things might be called ignorant by a farmer who never went to high school but has spent his life in the fields. Although all of these adjectives refer to a lack of knowledge, ignorant refers to a lack of knowledge in general (: a foolish, ignorant person) or to a lack of knowledge of some particular subject (: ignorant of the fine points of financial management).
A professor of art history might refer to someone who doesn't know how to look at a painting as uneducated or untutored, both of which refer to a lack of formal education in schools (: she was very bright but basically uneducated, and completely untutored in the fine arts).
Someone who cannot read or write is illiterate, a term that may also denote a failure to display civility or cultivated behavior (: the professor routinely referred to his students as illiterate louts).
Someone who is unlettered lacks a knowledge of fine literature (: a scientist who was highly trained but unlettered); it also implies being able to read and write, but with no skill in either of these areas.
Unlearned is similar to ignorant in that it refers to a lack of learning in general or in a specific subject (: an unlearned man who managed to become a millionaire), but it does not carry the same negative connotations.
Uninformed refers to a lack of definite information or data. For example, one can be highly intelligent and well educated but still uninformed about the latest developments in earthquake prediction.

A: If you want to be nice, you can say the person is a neophyte. Less polite would be philistine, which MW defines as "one uninformed in a special area of knowledge." If this is a technology-related field, luddite might work (though it's not very nice, either). A more neutral way of saying "intentionally ignorant" might be

exhibits a deliberate lack of sophistication about _.

EDIT: Understanding the question better now, I offer another option to describe someone who is arrogantly and intentionally ignorant yet insists on trying to instruct others.

insists on [spreading or infecting others with] his deliberate lack of sophistication about _.

This assumes you're just looking for a polite way to describe the problem to third parties. You wouldn't say this to the person's face -- at least not if you expect to get along with him afterward. :)
Sorry so many words. I don't think there's a way to say this that is both concise and diplomatic.

A: A polite way to say that a  person doesn't know something:

[Person] is not familiar with [something].

For example,

Mark is not familiar with Java programming.

A: A few words that can mean "ignorant by choice" (with mixed amounts of tactfulness):

*

*unenthusiastic

*unmotivated

*lackadaisical

*bored

*resistant

*rebellious

*apathetic

*uninterested

*ennui

*listless

*passionless

*indifference

A: my favorite is from "Shawshank Redemption" in which Andy accuses the warden of being obtuse.

A: How about a "specialist"?
It's a long shot, but I myself try to avoid learning anything of certain areas, like music and politics. It's not an inherently negative practice (Although perhaps I shouldn't speak being an open practitioner ^.^). At least, it's not if you've read, or admire, your Sherlock Holmes.
If you don't remember, this was one of the features Watson found most remarkable about Mr. Holmes in A Study in Scarlet, in the second chapter, if you're interested. Despite his astonishing knowledge in several eclectic and esoteric areas, he remained ignorant of the primacy of the heliocentric theory in astronomy, and would have liked to remain so.
As I said, "specialist" is a long shot, but it's not insulting...I admit, that's mainly because it emphasises a hypothetical counterpoint for whatever intentional ignorance. Still, it seems to me that, sometimes, that is exactly what being polite is, ignoring the negative and hyping the positive.

A: Although remaining judgmental and by no means polite, dispatching a lamer as an  ignoramus superficially imparts authority in doing so.


text:
Q: SSH Brute Force Protection I currently have my raspberry pi port forwarded for SSH connection, so i can access it at work.
Whilst looking at 'journalctl -xe' i have seen tons of failed SSH login requests.
I have changed my raspberry pi to key logins rather than password based. Is there anything else i can do to stop this guy from trying to break in? Or better security to stop him accessing it?
Dec 20 19:46:36 raspberrypi sshd[1929]: Received disconnect from 106.250.183.218 port 20371:11: Bye Bye [preauth]
Dec 20 19:46:36 raspberrypi sshd[1929]: Disconnected from 106.250.183.218 port 20371 [preauth]
Dec 20 19:47:58 raspberrypi sshd[1931]: Received disconnect from 221.194.47.245 port 37247:11:  [preauth]
Dec 20 19:47:58 raspberrypi sshd[1931]: Disconnected from 221.194.47.245 port 37247 [preauth]
Dec 20 19:48:50 raspberrypi sshd[1934]: Did not receive identification string from 23.254.161.114 port 51435
Dec 20 19:50:15 raspberrypi sshd[1935]: Did not receive identification string from 195.154.60.109 port 64642
Dec 20 19:50:15 raspberrypi sshd[1936]: Invalid user user from 195.154.60.109 port 64943
Dec 20 19:50:15 raspberrypi sshd[1936]: input_userauth_request: invalid user user [preauth]
Dec 20 19:50:15 raspberrypi sshd[1936]: error: Received disconnect from 195.154.60.109 port 64943:3: com.jcraft.jsch.JSchException: Auth fail [preauth]
Dec 20 19:50:15 raspberrypi sshd[1936]: Disconnected from 195.154.60.109 port 64943 [preauth]
Dec 20 20:02:05 raspberrypi sshd[1997]: Did not receive identification string from 195.154.60.109 port 51264
Dec 20 20:02:06 raspberrypi sshd[1998]: Invalid user user from 195.154.60.109 port 51418
Dec 20 20:02:06 raspberrypi sshd[1998]: input_userauth_request: invalid user user [preauth]
Dec 20 20:02:06 raspberrypi sshd[1998]: error: Received disconnect from 195.154.60.109 port 51418:3: com.jcraft.jsch.JSchException: Auth fail [preauth]
Dec 20 20:02:06 raspberrypi sshd[1998]: Disconnected from 195.154.60.109 port 51418 [preauth]
Dec 20 20:02:31 raspberrypi sshd[2002]: Did not receive identification string from 91.227.47.234 port 53975
Dec 20 20:02:32 raspberrypi sshd[2003]: Invalid user user from 91.227.47.234 port 53982
Dec 20 20:02:32 raspberrypi sshd[2003]: input_userauth_request: invalid user user [preauth]
Dec 20 20:02:32 raspberrypi sshd[2003]: Received disconnect from 91.227.47.234 port 53982:11: Bye Bye [preauth]
Dec 20 20:02:32 raspberrypi sshd[2003]: Disconnected from 91.227.47.234 port 53982 [preauth]
Dec 20 20:03:05 raspberrypi sshd[2023]: Did not receive identification string from 103.79.142.58 port 50841
Dec 20 20:03:08 raspberrypi sshd[2024]: Invalid user user from 103.79.142.58 port 52943
Dec 20 20:03:08 raspberrypi sshd[2024]: input_userauth_request: invalid user user [preauth]
Dec 20 20:03:08 raspberrypi sshd[2024]: error: Received disconnect from 103.79.142.58 port 52943:3: com.jcraft.jsch.JSchException: Auth fail [preauth]

A: You can also limit the number of attemps with fail2ban.
The default config is fine for ssh server.
sudo apt-get update
sudo apt-get install fail2ban

A: If you're not looking to disable password access to all accounts, disabling the root login via your sshd_config file (as mentioned by @ramrunner) would definitely cut down on the vast majority of SSH brute force attempts. Nevertheless, this can still leave your other login accounts vulnerable.
One way to mitigate this would be to configure iptables to only allow external SSH attempts from certain IP addresses or IP blocks. If your external work IP address does not change, you could configure iptables to block all external SSH attempts except from your work IP.

A: SSH brute force attacks can suck the resources from low powered servers with a minimal amount of processors (CPU) and memory (RAM). This could be the case with your raspberry pi.
We developed a solution named am-deny-hosts that helps to block these attacks. It downloads IP address black lists of known SSH attackers and adds them to the /etc/hosts.deny file.
It is released as an open source project on GitHub. You get a set of shell scripts that protects your raspberry PI without taking up a lot of time, CPU, or memory. Whats more we made it very simple to install.

A: This question might be better migrated to serverfault or security.stackexchange.
As @larsks said, these automated attacks are in vain if you have disabled password logins. Make sure you also have
PermitRootLogin no

in your sshd_config .If you don't want to limit it yourself from iptables as per @larsks link you can install fail2ban.
Finally i have found that running sshd on a non standard port helps with the automated scans too.


text:
Q: CMake : Include subdirectories I have currently, in my CMake lists :
FIND_PATH(BOINC_INCLUDE_DIR NAMES boinc_api.h
      PATH_SUFFIXES boinc
      DOC "The Boinc include directory (where boinc_api.h is)")

This command find the directory /usr/include/boinc.
But I want to add all the subdirectories in the boinc directory.
How to do that ?
Thank you very much.

A: Try the following code. It iterates through all files and directories in BOINC_INCLUDE_DIR and appends directories to include directories list:
FILE(GLOB _ALL_FILES ${BOINC_INCLUDE_DIR} ${BOINC_INCLUDE_DIR}/*)
FOREACH(_FILE ${_ALL_FILES})
  IF(IS_DIRECTORY ${_FILE})
    INCLUDE_DIRECTORIES(${_FILE})
  ENDIF()
ENDFOREACH()


text:
Q: Get whether Sharepoint ListItem can be updated I'm having an issue trying to figure out programmatically if a user can modify a Sharepoint list item that uses the approval workflow.
Suppose I have two users - UserA and UserB.  UserA makes a change to a list item. That list item is then marked as 'Pending' for UserA and UserB only sees the unmodified list item. Now if UserB tries to modify the same list item, the update will fail because the list item has not yet been approved (if you try this online in 365, you will get a error message at the top).
Is there a way for me to know when I get the list item that it is effectively read-only for UserB? I've tried looking at the ListItem.ApprovalStatus, but for UserB that is still the unmodified list item. I've tried looking at the ListItem.Versions, but that yields the same results. I've also tried using a ChangeQuery and looking at the change history of the list item, but I don't see anything useful there.
Any ideas?


text:
Q: Entity Framework New GUID database initializer I want to initialize new GUID with my model class. I can not initialize GUID, Last Login IP adress.
Initializer doesn't create Kullanici table's row on database. Why ? I don't understand.
How can I add new row with GUID, IP Adress, DateTime.Now and more? Can you help me for that, please?
I'm using Entity Framework 6, MVC 5, SQL Server 2012, and ASP.NET 4.
Kullanici.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace agiEmlak.Entities
{
    public class Kullanici
    {
        //public Kullanici()
        //{
        //    GID = Guid.NewGuid();
        //}
        [Key]
        public int ID { get; set; }

        public Guid GID { get; set; }
        public string KullaniciAdi { get; set; }
        public string Ad { get; set; }
        public string Soyad { get; set; }
        public string Sifre { get; set; }
        public string Eposta { get; set; }
        public DateTime KayitTarihi { get; set; }
        public string SonIPAdres { get; set; }
        public DateTime SonLoginTarihi { get; set; }
        public string AktivasyonKodu { get; set; }
        public string CepTelefonu { get; set; }
        public string IsTelefonu { get; set; }
        public bool? Aktif { get; set; }
        public bool? Silinmis { get; set; }

        public string AdSoyad
        {
            get
            {
                return Ad + " " + Soyad;
            }
        }

        public virtual ICollection<Emlak> Emlaks { get; set; }
    }
}

ilanInitializer.cs:
using agiEmlak.Entities;
using System;
using System.Collections.Generic;
using System.Data.Entity;

namespace agiEmlak.Dal.Concrete.EntityFramework
{
    public class ilanInitializer : DropCreateDatabaseIfModelChanges<ilanDBContext>
    {
        protected override void Seed(ilanDBContext context)
        {
            var kullanicilar = new List<Kullanici>
            {
            new Kullanici{ GID=Guid.NewGuid(), KullaniciAdi="halilkoca", Ad="Halil", Soyad="Koca", Eposta="halilkoca@outlook.com", Sifre="12551255", CepTelefonu="05415013031", IsTelefonu="02526133428", KayitTarihi=DateTime.Parse("25/10/2015"), AktivasyonKodu="5", SonIPAdres=Dns.GetHostName().ToString(), SonLoginTarihi= DateTime.Now},
            new Kullanici{ GID=Guid.NewGuid(), KullaniciAdi="halil", Ad="Halil", Soyad="Koca", Eposta="halilkoca.ilan@gmail.com", Sifre="12551255", CepTelefonu="05415013031", IsTelefonu="02526133428", KayitTarihi=DateTime.Parse("26/10/2015"), AktivasyonKodu="10", SonIPAdres=Dns.GetHostName().ToString(), SonLoginTarihi= DateTime.Now}
            };

            kullanicilar.ForEach(s => context.Kullanicis.Add(s));
            context.SaveChanges();

        }
    }
}

ilanDbContext.cs:
using System.Data.Entity;
using agiEmlak.Entities;
using System.Data.Entity.ModelConfiguration.Conventions;

namespace agiEmlak.Dal.Concrete.EntityFramework
{
    public class ilanDBContext:DbContext
    {
        public ilanDBContext(): base("ilanDBContext")
        {

        }

        public DbSet<Adres> Adress { get; set; }
        public DbSet<Ayar> Ayars { get; set; }
        public DbSet<Detay> Detays { get; set; }
        public DbSet<DetayTaksonomi> DetayTaksonomis { get; set; }
        public DbSet<Emlak> Emlaks { get; set; }
        public DbSet<EmlakKonutTuruMapping> EmlakKonutTuruMappings { get; set; }
        public DbSet<EmlakTipi> EmlakTipis { get; set; }
        public DbSet<EmlakTuru> EmlakTurus { get; set; }
        public DbSet<Il> Ils { get; set; }
        public DbSet<Ilce> Ilces { get; set; }
        public DbSet<KonutTipi> KonutTipis { get; set; }
        public DbSet<Kullanici> Kullanicis { get; set; }
        public DbSet<Mahalle> Mahalles { get; set; }
        public DbSet<Ozellik> Ozelliks { get; set; }
        public DbSet<OzellikMapping> OzellikMappings { get; set; }
        public DbSet<OzellikTaksonomi> OzellikTaksonomis { get; set; }
        public DbSet<Ulke> Ulkes { get; set; }

        /// <summary>
        /// Database üzerine Tablo isimleri tekil olarak kaydedilir.
        /// </summary>
        /// <param name="modelBuilder"></param>
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        }
    }
}

Solution:
Add Seed method execute to Global.asax.cs:
Database.SetInitializer<ilanDBContext>(new ilanInitializer());

Thanks.


text:
Q: including header files from prebuilt library Android.mk I have included a prebuilt library into my library creation using
include $(PREBUILT_SHARED_LIBRARY)

and verified weather library is included or not by using
$(modules-get-list)

When i try to include a header file present within prebuilt library, i face error header not found. Below is my exact Android.mk file
LOCAL_PATH := $(call my-dir)

# import prebuilt-library
include $(CLEAR_VARS)
LOCAL_MODULE    := prebuilt-library
LOCAL_SRC_FILES := ../../../target/dependency/libs/$(TARGET_ARCH_ABI)/libprebuilt.so
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/include
include $(PREBUILT_SHARED_LIBRARY)

# building provider interface library for communication
include $(CLEAR_VARS)
LOCAL_MODULE := library-interface
LOCAL_SRC_FILES := LibraryComminicator.cpp
LOCAL_SHARED_LIBRARIES := prebuilt-library

include $(BUILD_SHARED_LIBRARY)

$(warning Existing modules: "$(modules-get-list)")

# Include the Android Maven plugin generated makefile
# Important: Must be the last import in order for Android Maven Plugins paths to work
include $(ANDROID_MAVEN_PLUGIN_MAKEFILE)

A: Try the Android.mk below:
LOCAL_PATH := $(call my-dir)
EXT_LIB_ROOT := $(LOCAL_PATH)/../../../target/dependency # or whatever

# building provider interface library for communication
include $(CLEAR_VARS)
LOCAL_MODULE := library-interface
LOCAL_SRC_FILES := LibraryComminicator.cpp
LOCAL_SHARED_LIBRARIES := prebuilt-library

include $(BUILD_SHARED_LIBRARY)

# import prebuilt-library
LOCAL_PATH := $(EXT_LIB_ROOT)
include $(CLEAR_VARS)
LOCAL_MODULE    := prebuilt-library
LOCAL_SRC_FILES := libs/$(TARGET_ARCH_ABI)/libprebuilt.so
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/include
include $(PREBUILT_SHARED_LIBRARY)

$(warning Existing modules: "$(modules-get-list)")

The basic rules are: xxx_INCLUDE_FILES should be relative to 'current dir', while LOCAL_SRC_FILES are relative to $(LOCAL_PATH), not to the 'current dir'. With NDK, typically the 'current dir' is $(LOCAL_PATH)/.. but this could change, especially if Android.mk files are linked, i.e. one includes another.
And you really don't need LOCAL_PATH for PREBUILT_SHARED_LIBRARY modules, but I prefer to keep LOCAL_SRC_FILES as short as possible.


text:
Q: C: Why I am getting a Segmentation Fault when trying to create a new folder/directory? I am trying to create a new folder using two command line arguments, one being the destination folder and the other the source, but I am getting a "Segmentation fault (core dumped)" error.  Could you please help me figure out what is causing this error. The code is below.
int main(int argc, char **argv){

    char *src = argv[1];
    char *dest = argv[2];

    DIR *srcdir;
    DIR *destdir;

    struct stat srcfile;
    struct stat destfile;
    struct dirent* directory;

    if ((stat(argv[1], &srcfile) == -1) || (stat(argv[2], &src) == -1)){
        exit(-1); //TODO: Change to proper error code
    }

    srcdir = opendir(src);
    destdir = opendir(dest);

    if ((srcdir == NULL)||(destdir == NULL)) {
        printf("No such file or directory exist.\n");
        exit(1);
    }

    char new_path[1024];

    new_path[0] = '\0';
    strcat(new_path, dest);
    strcat(new_path, "/");

    strcat(new_path, src);

    if (stat(new_path, &destfile) == -1) {
        if(mkdir(new_path, 0700) != -1){
            mkdir(new_path, 0700);
        }else{
            perror("mkdir: ");
        }

    }
}

A: I have tried and the following code is working correctly as:
#include<stdio.h>
#include <dirent.h>
#include <stdlib.h>
#include <sys/stat.h>
#include<string.h>

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

    char *src = argv[1];
    char *dest = argv[2];

    DIR *srcdir;
    DIR *destdir;

    struct stat srcfile;
    struct stat destfile;
    //struct dirent* directory;

    if ((stat(src, &srcfile) == -1) || (stat(dest, &destfile) == -1)){
        exit(0); //TODO: Change to proper error code
    }

    srcdir = opendir(src);
    destdir = opendir(dest);

    if ((srcdir == NULL)||(destdir == NULL)) {
        printf("No such file or directory exist.\n");
        exit(1);
    }

    char new_path[1024];

    new_path[0] = '\0';
    strcat(new_path, dest);
    strcat(new_path, "/");

    strcat(new_path, src);

    if (stat(new_path, &destfile) == -1) {
        if(mkdir(new_path, 0700) != -1){
            mkdir(new_path, 0700);
        }else{
            perror("mkdir: ");
        }
    }
    return 0;
}

compiling command
gcc -Wall xxx.c


text:
Q: OpenGL Rotation Skewed Issues I am having a bit of an issue with any rotation around the x-axis inside of OpenGL. What I have is a basic cube that is being rendered inside of a shader, with normals for lighting calculations. The transformation of the cube is the projection matrix multiplied by the model matrix. This concatenation is done inside the shader, while the rotation and translation calculations are done inside a Matrix class I wrote. When any rotations are done around the y-axis, everything rotates as expected as shown by these pictures:

The problems start when any rotations occur around the x-axis as shown here:

Apparently the x-axis rotations skew the scene and cause everything to be shown out of proportion. Here is the code the calculates the matrices and passes is to the shader every time this is rendered:
glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);

viewMatrix.setIdentity();
viewMatrix.translate(new Vector4(translation));
viewMatrix.rotate(1, 0, 0, -rotateX);
viewMatrix.rotate(0, 1, 0, rotateY);
Matrix4 mvMatrix = new Matrix4(viewMatrix);

Matrix4 pMatrix = new Matrix4(projectionMatrix);

lightShader.useShader();
lightShader.setUniformVector("vColor", new Vector4(.4f,0,0,1f));
lightShader.setUniformMatrix("mvMatrix", mvMatrix);
lightShader.setUniformMatrix("pMatrix", pMatrix);
triangleBatch.draw(lightShader.getAttributes());

Display.update();

The shader code is as follows:
uniform mat4 mvMatrix;
uniform mat4 pMatrix;
uniform vec4 vColor;
varying vec4 outFragColor;
attribute vec4 inVertex;
attribute vec4 inNormal;
void main(void) {
    vec3 newNorm = vec3(inNormal);
    mat3 mNormalMatrix;
    mNormalMatrix[0] = mvMatrix[0].xyz;
    mNormalMatrix[1] = mvMatrix[1].xyz;
    mNormalMatrix[2] = mvMatrix[2].xyz;
    vec3 vNorm = normalize(mNormalMatrix * newNorm);
    vec3 vLightDir = vec3(0.0, 0.0, 1.0);
    float fDot = max(0.0, dot(vNorm, vLightDir));
    outFragColor.rgb = vColor.rgb * fDot;
    outFragColor.a = vColor.a;
    mat4 mvpMatrix;
    mvpMatrix = pMatrix * mvMatrix;
    gl_Position = mvpMatrix * inVertex;
}

Finally the matrix math code for rotations is as follows:
public Matrix4 rotate(Vector4 a, float radians){
    Matrix4 temp = new Matrix4().setToRotate(a, radians);
    this.multiply(temp);
    return this;
}

public Matrix4 setToRotate(Vector4 a, float radians){
    a = new Vector4(a).normalise();
    float c = GameMath.cos(radians);
    float s = GameMath.sin(radians);
    float t = 1-c;
    float x = a.x;
    float y = a.y;
    float z = a.z;
    float x2 = a.x*a.x;
    float y2 = a.y*a.y;
    float z2 = a.z*a.z;
    this.setIdentity();
    this.matrix[0] = c + t*x2;
    this.matrix[1] = t*x*y + s*z;
    this.matrix[2] = t*x*z - s*y;
    this.matrix[4] = t*x*y - s*z;
    this.matrix[5] = c + t*y2;
    this.matrix[6] = t*y*z + s*x;
    this.matrix[8] = t*x*z + s*y;
    this.matrix[9] = t*y*z + s*x;
    this.matrix[10] = c + t*z2;
    return this;
}

The matrices are stored in column major.

A: I found out what the issue was. apparently one of the operations in setToRotate() need to be changed from addition to subtraction. It works as expected now.


text:
Q: CALayer, NSTextView and scaling In my app I want to provide text scaling in layer backed NSTextView like Apple's TextEdit. I use analogue of it's ScalingScrollView. Also I need to create some CALayer overlays on self.window.contentView. All is ok until I make [self.window.contentView setWantsLayer:YES].
Before [setWantsLayer:YES]

After [setWantsLayer:YES]

I haven't any ideas how to fix this problem.

A: I've been searching for the solution to the similar issue, too. Finally, I discovered that layer-backed views must be positioned on integral pixels and must not be positioned on subpixels.
E.g. if you dynamically calculate frame of layer-backed view
 NSMakeRect((self.frame.size.width - 350)/2, (self.frame.size.height - 150)/2, 350, 150)

you may encounter non-integral values, so you should do something like
 NSMakeRect(floor((self.frame.size.width - 350)/2), floor((self.frame.size.height - 150)/2), 350, 150)


text:
Q: Real Analysis (derivative) I am completely stuck in this question.
If  $r > 0$  is a rational number, let $f : \mathbb{R} \to \mathbb{R} $ be defined by $f (x)=x^r\sin (1/x)$ for $x \ne 0$, and $f (0)=0$. Determine those values of $r$ for which $f'(0)$
exists.

A: We look at the behaviour of the difference quotient as $h\to 0$ :
For $r>1$ $$-h^{r-1}\leq \frac{h^r  \sin(1/h)-0}{h} \leq h^{r-1}$$ goes to $ 0$ as $h\to 0 $ .
So, $f'(0)=0$ .
For $ r= 1 $ , the difference quotient oscillates between $-1$ and $1$.
And lastly for $0<r<1$ ,the difference quotient oscillates unboundedly as $h\to 0$ .

A: hint:-
$f'(x)=rx^{r-1}\sin \frac{1}{x}+x^{r-2} \cos\frac{1}{x}$
now $f'(0)$ exists when $\lim _{x \to 0}x^{r-2} \cos\frac{1}{x}$ exist


text:
Q: Как соединить несколько точек прямой и добавить подписи для каждой точки Есть 3 координаты
[1,2] P
[3,4] Q
[-3,-2] R

Как нарисовать прямую через три точки, и чтобы аннотации были у каждой координаты

вот такая например для точки P

A: Принципиально, это можно сделать так:
P = [1,2]
Q = [3,4]
R = [-3,-2]
coords = list(zip(P, Q, R))

plt.ylim(-4, 6)
plt.xlim(-4, 6)
plt.plot(coords[0], coords[1], marker='o', markersize=35, markerfacecolor='orange', markeredgecolor='orange')

plt.annotate('P', (coords[0][0]-.15, coords[1][0]-.2), size=15)
plt.annotate('Q', (coords[0][1]-.15, coords[1][1]-.2), size=15)
plt.annotate('R', (coords[0][2]-.15, coords[1][2]-.2), size=15)

plt.show()

Однако, советую оптимизировать данные так, чтобы аннотации можно было писать циклом автоматически вне зависимости от количества данных.
Разумеется, с позиционированием аннотаций надо будет попадать.


text:
Q: File download does not work with IE7 I have an asp.net page which sends content of a file to the client, so the browser shows the save as dialog to download the file. This page is displayed in a popup and when the user clicks the save button, it closes automatically and the download starts.
On windows server 2003, it works fine. On vista with other browsers, also works fine. But when I try with IE7 & Vista, the popup opens, and closes after about a second without displaying the file download dialog. How can I solve this?
The code I use for response generation is:
FileStream fileStream = new FileStream(filePath, FileMode.Open);
int fileSize = (int)fileStream.Length;

byte[] buffer = new byte[fileSize];
fileStream.Read(buffer, 0, (int)fileSize);
fileStream.Close();

Response.Clear();

Response.Buffer = true;
Response.BufferOutput = true;
Response.ContentType = "application / octet - stream";

Response.AddHeader("Content-Length", buffer.Length.ToString());
Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
Response.AddHeader("Extension", Path.GetExtension(filename));
Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1254");
Response.BinaryWrite(buffer);
Response.Flush();
Response.End();

And I am opening the popup with this javascript:
window.open ('Download.aspx?filename=somefile.ext','downloadWindow','location=0,status=0,scrollbars=0,width=1,height=1');

EDIT: I corrected the spaces but unfortunately they are not the problem.
EDIT 2:: Seems that this problem is not related to Vista but IE only. I also discovered that it works fine when the project is run on the development server locally but when working as connected to publish server, it fails to download the file.

A: Try removing the spaces in your ContentType. The standard is application/octet-stream.

A: Two things.

*

*As mentioned before you will want to remove the spaces in the type

*Is there any particular reason that you are not using Response.TransmitFile() rather than reading the file in yourself?

A: I'd also suggest you add quotes around the file name, otherwise, if it contains spaces, it will get truncated in Firefox.

A: I can't point to a specific problem in your code (except possibly for that content type, which looks badly-formed; not sure if that makes a difference). Here's the code I use for this, which works in both IE7 and Firefox:
Response.ContentType = "application/x-download";
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.CacheControl = "public";
Response.OutputStream.Write(byteArr, 0, byteArr.Length);
Response.End();

A: I think your problem could be with IIS 7 . There is a problem with "addHeader" in the new Internet information Server with the integration pipeline mode.
Try to use Response.AppendHeader .

A: I also had the same problem...and I used this solution (I'm using it on a button.click):
Response.ContentType = "text/txt";
Response.AppendHeader("Content-Disposition", "attachment; filename="+DownloadFileName);
Response.Write(MyFileContent_Text_);
Response.End();

...it just worked!!

A: I came across this post because I was having a similar problem if not the same one.  I am running IE8 on Windows 7.
When debugging on my local machine I could get the File Download prompt to display, but when clicking "Save" or "Open" the Download Progress window would display for about a half second and then close suddenly without downloading anything.
I have an add-on installed for Internet Explorer called IE7Pro.  It comes with a Download Manager which I had enabled.  When I disabled it, my problems went away and I could Open or Save my files.
Hope this proves helpful to someone else out there.


text:
Q: VIM go back (CTRL-O) to already opened tab When I do gf then file under the cursor is opened in current tab. That's fine. When I do CTRL-W gf file under the cursor is opened in new tab - that's fine, but when I do CTRL-O newly opened tab is filled with the file that I have already open in my first tab resulting in editing the same file in multiple tabs.
Is there any way I can go back to the "first" tab using CTRL-O?

A: When you follow :help CTRL-O, you'll notice that the command is listed under Jumps; these are within a single window.
I fully agree with you that this is an inconsistency: Though there are commands (prefixed with CTRL-W) that open in a split window or new tab page (to let you keep the current context, which is helpful, especially as today screen real estate is much more abundant), you're leaving the "current window" navigation with this, and have to rely on window / tab management mappings (like CTRL-W j, k / gt).
Unfortunately, there's no "window movement history" command built-in like CTRL-O and CTRL-I do for (single-window) jumps. Such could be provided by a plugin, though; and this might already exist. For me personally, I can manage window and tab movements pretty well with some customized mappings, and don't miss a window movement history command. As I frequently move between windows and tabs, such history probably would become too cluttered to be useful, anyway.


text:
Q: Authorize WebAPI's on multiple machines using a SSO via Code I have a Web API project which provides the access to only Authorized users based on roles. We plan to scale to multiple such API projects in the near future which will use the same Authorization token. What I am doing is using a separate project which authenticates the user (using Facebook, Google or ActiveDirectory or any other authentication provider), and then generate an Authorization token which is consumed by all the API servers. To enable decryption of the token, I am sharing the machine key via web.config among all the application. This works fine. Now I would like to change the MachineKey every once in a while and share it among all the applications that utilize the Authorization token.

*

*How do I update the machineKey at run time among all the
applications?

*Is there a programmatic way to achieve the same?

*I have read in a blog that updating machineKey's is not a good practice. If so, how do I avoid using the machine key altogether and create a system where the key's are not static?

My idea is to separate out the Authorization project from my WebAPI projects so that I don't implement and authentication system within all the WebAPI projects. Any pointers would be very helpful.

A: Extended the implementation shown on the following stackoverflow answer to meet your requirements. I will update the code in a couple of days on how you can achieve this.

A: You could let the APIs request the Authorization-Service to confirm the token from the Client and in that same request get the ID-data from the Service to the API. To reduce the traffic to the Auth-Service, it could hand out short-lived access-Tokens to the APIs with an expiration date, which need to be refreshed after a few minutes, or if they are critical, could be revoked directly from the Auth-Service calling out to the APIs.
Your system sounds a lot like an OAuth-scheme to me. I would not suggest trying to go fully compliant unless you plan for other use cases like mobile devices etc. accessing your services, but you can read up on how they do it and implement what seems relevant for your needs.

A: As suggested by Rajesh, I believe what I am looking for is a trivial enhancement of his link.
Essentially I need to create a function that sets my key in the Protect method.
private IDataProtector protector;

public string Protect(AuthenticationTicket ticket)
{
    protector = new AesDataProtectorProvider(functionGenerateKey());
    //functionGenerateKey is a function that generates a new key and informs
    //the subscribers to avail new key
    var ticketData = this.serializer.Serialize(ticket);
    var protectedData = this.protector.Protect(ticketData);
    var protectedString = this.encoder.Encode(protectedData);
    return protectedString;
}

public SecureTokenFormatter(string key)
{
    this.serializer = new TicketSerializer();
    //this.protector = new AesDataProtectorProvider(key); -> Remove the initialization of this protector as I am doing it in the above function.
    this.encoder = TextEncodings.Base64Url;
}

The rest of the implementation is pretty standard in the code written by Barguast


text:
Q: SQL query to return users with no active group memberships I've got this schema, which has the ability to soft-delete/archive a group:
create table users (id int, name varchar(255));
create table groups (id int, name varchar(255), archived_at datetime);
create table memberships (group_id int, user_id int);

insert into users (id, name) values
  (1, 'no groups'),
  (2, 'only active groups'),
  (3, 'only archived groups'),
  (4, 'active and archived groups');

insert into groups (id, name, archived_at) values
  (1, 'active group', null),
  (2, 'archived group', '2021-04-13');

insert into memberships (user_id, group_id) values
  (2, 1),
  (3, 2),
  (4, 1),
  (4, 2);

And I want to query users that have "no groups": exactly zero Active (non-archived) groups, plus zero or more Archived groups.
-- How do I get this to return only users 1 and 3?
select *
from users u
left join memberships m on m.user_id = u.id
left join groups g on g.id = m.group_id
where
  m.group_id is null
  or
  g.archived_at is not null

Is this possible with the current schema?
https://www.db-fiddle.com/f/h1szvQmQHp1g84Ex9WvRHy/1

A: This sounds like not exists:
select u.*
from users u
where not exists (select 1
                  from memberships m join
                       groups g
                       on m.group_id = g.id
                  where m.user_id = u.id and g.archived_at is null
                 );

Presumably, an active group is one that has not been archived.


text:
Q: 50% percent accuracy issue with liblinear I am quite new in Liblinear/Libsvm and i'm with a good problem here.
I have very big data for training (2.883.584 samples highly unbalanced, each of them 21-dimensional) and also big data for testing (262.144 samples also with 21 dimensions). I'm using the linear kernel implementation of LIBSVM (or LibLinear) because the big data nature of my data. The literature warns me the issues of using RBF kernels with these data.
My problem is: no matter what i do, the classifier only predicts one class (the class with more samples, or the negative class in my experiments).
I tried so far:
1- Train balanced and imbalanced data, do not scale the data and no parameter selection.
2- Train balanced and imbalanced data, scale the data with different ranges ([-1,1] and [0,1]) but no parameter selection.
3- Train balanced and imbalanced data, scale the data with different ranges ([-1,1] and [0,1]) with parameter selection.
All of these experiments result an 81% of accuracy, but these right predictions are all from the negative class. All the positive classes are misclassified by the linear svm.
The .model file is very weird as you can see below:
solver_type L2R_L2LOSS_SVC_DUAL
nr_class 2
label 1 -1
nr_feature 21
bias -1
w
0
0
nan
nan
0
0
0
0
0
nan
nan
0
0
0
0
0
nan
nan
0
0
0

When I do the parameter selection via grid search the best C always gives me a 5-fold cross validation best accuracy of 50%. That's how I do the grid search in Matlab:
for log2c = 1:100,
    cmd = ['-v 5 -c ', num2str(2^log2c)];
    cv = train(label, inst, cmd);
    if (cv >= bestcv),
        bestcv = cv; bestc = 2^log2c;
    end
    fprintf('%g %g (best c=%g, rate=%g)\n', log2c, cv, bestc, bestcv);
end

EDIT: Here is one positive and negative sample of my training data:
 1  1:4.896000e+01 2:3.374349e+01 3:2.519652e-01 4:1.289031e+00 5:48 6:4.021792e-01 7:136 8:4.069388e+01 9:2.669129e+01 10:-3.017949e-02 11:3.096163e+00 12:36 13:3.322866e-01 14:136 15:4.003704e+01 16:2.168262e+01 17:1.101631e+00 18:3.496498e+00 19:36 20:2.285381e-01 21:136
-1  1:5.040000e+01 2:3.251025e+01 3:2.260981e-01 4:2.523418e+00 5:48 6:4.021792e-01 7:136 8:4.122449e+01 9:2.680350e+01 10:5.681589e-01 11:3.273471e+00 12:36 13:3.322866e-01 14:136 15:4.027160e+01 16:2.245051e+01 17:6.281671e-01 18:2.977574e+00 19:36 20:2.285381e-01 21:136

And here is one positive and negative sample of my testing data:
 1  1:71 2:2.562365e+01 3:3.154359e-01 4:1.728250e+00 5:76 6:0 7:121 8:7.067857e+01 9:3.185273e+01 10:-8.272995e-01 11:2.193058e+00 12:74 13:0 14:121 15:6.675556e+01 16:3.624485e+01 17:-1.863971e-01 18:1.382679e+00 19:76 20:3.533593e-01 21:128
-1  1:5.606667e+01 2:2.480630e+01 3:1.291811e-01 4:1.477127e+00 5:65 6:0 7:76 8:5.610714e+01 9:3.602092e+01 10:-9.018124e-01 11:2.236301e+00 12:67 13:4.912373e-01 14:128 15:5.886667e+01 16:3.891050e+01 17:-5.167622e-01 18:1.527146e+00 19:69 20:3.533593e-01 21:128

Is there something wrong with my data? should I increase the C range in grid-search? or should I use another classifier?

A: For unbalanced case, the costs of false-positive and false-negative errors are not the same, so the penalty for positive and negative class should be different. You may need to choose the weight C+ and C- for each class. If you have more negative patterns than positive patterns then you probably want to make C+ larger than C−
model = svmtrain(trainLabels, trainFeatures, '-h 0 -b 1 -s 0 -t 0 -c 10 -w1 C+ -w-1 C-');
Usually C+ * N+ = C- * N- where N+ and N- are the sample numbers of positive and negative class respectively.
Also make sure you choose the correct options. For your case that training sample number is much larger than feature numbers, linear kernel is the best option as you said in your post.


text:
Q: Solving an Exponential Equation I'm having a hard time with this exponential equation, I'm sure I'm doing some kind of a "minor" mistake again somewhere along the way. Your help is very much appreciated.
$$4\cdot4^{2x}-9\cdot 4^x+2=0$$
*Answers given are: $0,5; -1$.

A: Let $y=4^x$. The equation
$$4\cdot4^{2x}-9\cdot 4^x+2=0$$
$$4\cdot(4^x)^2-9\cdot 4^x+2=0$$
becomes a quadratic
$$4y^2-9y+2=0,$$
which we can solve with the quadratic formula. Then, once you've found the two values for $y$, solve for $x$ using $y=4^x$.


text:
Q: I am developing website using php and mysql.my each page file extension end with .php extension how do i avoid that? I am developing website using php and mysql.my each page file extension end with .php extension how do i avoid that?what I have to do for that?
I don't have any framework language.I want to learn the mvc pattern. I want to know which framework is easy level because I always benefited by stack team.According to me stack team will give easy way for me.
For ex:http://academy.in/services.php I have change to http://www.academy.in/services

A: You need to create a .htaccess file
A bit like this....
Options +FollowSymLinks
Options +Indexes
RewriteEngine on
RewriteBase /

RewriteRule ^/?services/$ services.php [NC,L]


text:
Q: Finding exact word in a column of strings from a list of words having spaces in between I want to create a new column with 1 or 0, if any of the words in a list is matched exaclty with the dataframe string column.
The words in the list can have multiple spaces in between, so I am not able to use str.split() for exact match.
list_provided=["mul the","a b c"]
#how my dataframe looks
id  text
a    simultaneous there the
b    simultaneous there
c    mul why the
d    mul the
e    simul a b c
f    a c b

Expected Output
id  text                      found
a    simultaneous there the    0
b    simultaneous there        0
c    mul why the               0
d    mul the                   1
e    simul a b c               1
f    a c b                     0

Ordering of the words in the list element also matters!!
Code tried till now
data=pd.DataFrame({"id":("a","b","c","d","e","f"), "text":("simultaneous there the","simultaneous there","mul why the","mul the","simul a b c","a c b")})
list_of_word=["mul the","a b c"]
pattern = '|'.join(list_of_word)
data['found'] = data['text'].apply(lambda x: sum(i in list_of_test_2 for i in x.split()))
data['found']=np.where(data['found']>0,1,0)
data
###Output generated###
id  text                   found
a   simultaneous there the  0
b   simultaneous there      0
c   mul why the             0
d   mul the                 0
e   simul a b c             0
f   a c b                   0

How to obtain the expected output where I have to search for exact match of words from a list against a dataframe string column, having multiple spaces in between?

A: You were nearly there, you've done all the ground work, now all that's left is to call the right function, in this case, str.contains.
data['found'] = data.text.str.contains(pattern).astype(int)
data

  id                    text  found
0  a  simultaneous there the      0
1  b      simultaneous there      0
2  c             mul why the      0
3  d                 mul the      1
4  e             simul a b c      1
5  f                   a c b      0

If your patterns themselves contain the regex OR pipe, try escaping them first:
import re
pattern = '|'.join([re.escape(i) for i in list_of_word])

A: You can achieve this with the help of str.contains. This can take up regex too!
data['found'] = np.where(data['text'].str.contains(pattern),1,0)


text:
Q: Insert trigger for invoice table I have an Invoice table with columns [customer no.], amount and [invoice no.].
I have to create a separate numbering of invoices per client, i.e. for client 1 we have invoices 1/1, 1/2, 1/3, 1/4 ... 1 / n and for each subsequent client k/n.
For example, for query
INSERT INTO [dbo].[Invoice] ([customer no.], [amount])
VALUES (1, 123.23), (1, 323.23), (2, 123.23), (3, 123.23), (4, 123.23)

the [invoice no.] column should get values 1/1, 1/2, 2/1, 3/1, 4/1.
Do you have any idea how to do this?


text:
Q: How to implement cylindrical panorama in react native How can I implement cylindrical panorama in react native that works for android and iOS both?
I found following libraries but none fulfills my requirement fully.

*

*Pano (This supports spherical panorama).

*react-native-google-vr-panorama (this only available for android).

*React-VR (This is separate VR project. I  just need to implement one thing).

*react-native-360 (This is available for iOS only.)


text:
Q: how to get the snowflake value of a string that is a valid user id discord.js I am trying to turn a string into a snowflake user.id to edit its permissions on a specific channel. In the below code, only user ids fetched in this way: interaction.user.id or client.user.id work. However, using this way: const user2 = await client.users.fetch(u2id) (u2id is a string of a valid user id value) doesn't work.
Here is my entire code:
var u2id = found.slice(0, 18)
const user2 = await client.users.fetch(u2id);
console.log(u2id)
interaction.guild.channels.create({
            name: interaction.user.id + u2id,
            type: ChannelType.GuildText,
            permissionOverwrites: [
              {
                id: interaction.guild.roles.everyone,
                deny: [PermissionFlagsBits.ViewChannel],
              },
              {
                id: interaction.user.id,
                allow: [PermissionFlagsBits.ViewChannel],
              },
              {
                id: client.user.id,
                allow: [PermissionFlagsBits.ViewChannel],
              },
              {
                id: user2,
                allow: [PermissionFlagsBits.ViewChannel],
              },
            ],
});

When I remove this part (which edits channel permissions for the user2 id)
{
  id: user2,
  allow: [PermissionFlagsBits.ViewChannel],
},

the code fully works. Any ideas on why its not working?


text:
Q: Update User's lastLogin property after login my user-domain has a field called 'lastLogin' which i want to update after login (self-exaplantoy).
after restarting tomcat (dev env) i get the following exception:
groovy.lang.MissingMethodException: No signature of method: static photoo.user.User.findById() is applicable for argument types: (java.lang.Long) values: [2] Possible solutions: findAll(groovy.lang.Closure), find(groovy.lang.Closure)
i use the following code in my Config.groovy:
// callback event, after a successful login
grails.plugins.springsecurity.onInteractiveAuthenticationSuccessEvent = { e, appCtx ->
    def user = User.findById(appCtx.springSecurityService.principal.id)
    User.withTransaction {
        if(!user.isAttached())
            user.attach()
        user.lastLogin = new Date()
        user.save(flush: true)
    }
}

How can avoid the exception and why is it occuring??
thx

A: finally i found the mistake. loading the user in the withTransaction-block is the solution.
// dont load before
// def user = User.findById(appCtx.springSecurityService.principal.id)
User.withTransaction {
        def user = User.findById(appCtx.springSecurityService.principal.id)
        if(!user.isAttached())
            user.attach()
        user.lastLogin = new Date()
        user.save(flush: true, failOnError: true)
    }

A: You might just need to use User.get(). This is what I have:
onInteractiveAuthenticationSuccessEvent = { e, appCtx ->

    // handle AuthenticationSuccessEvent
    def autservice = appCtx.authenticateService
    def user = autservice.userDomain()
    println "user: ${user.id}:${user}}"
    def request = org.codehaus.groovy.grails.plugins.springsecurity.SecurityRequestHolder.getRequest()
    def session = request.getSession(false)
    if (user) {

        def person = Person.get(user.id)

        def lang = person.preferredLanguage
        if (session) {
            session.lang = lang
        }
    }
}


text:
Q: How to execute a command during war creation? My environment:  Grails v2.1.1
I need to run a small utility app during the war process.  This app generates files that I want included in my war file.  I've tried putting code in BuildConfig.groovy's grails.war.resources, but I'm not seeing an error, or the files I am expecting to be created.
Does anyone know how I can execute this utility app so that its output is in my war?
This is the command as run inside a terminal instance:
sencha app build -e production -d $stagingDir/production

Here's my attempt to run it via grails.war.resources in BuildConfig.groovy:
grails.war.resources = { stagingDir ->

//calling echo() does nothing.  I don't see the comment in the build output
echo(message:'executing grails.war.resources')
def outputDir =  new File("${stagingDir.getParentFile().getPath()}/target/ranForReal")

def command = """sencha app build -e testing -d ${outputDir.getPath()}"""

def executionDir = new File("${stagingDir.getParentFile().getPath()}/web-app")

def proc = command.execute(null,executionDir)

proc.waitFor()

//my desperate attempt to see if anything is happening.  I'd expect an error here
def x = 1/0

// Obtain status and output
println "return code: ${ proc.exitValue()}"
println "stderr: ${proc.err.text}"
println "stdout: ${proc.in.text}" // *out* from the external program is *in* for groovy

//this for loop does work and does remove servlet jars, so I know this closure is called.
for (name in ['servlet']) {
    delete {
        fileset dir: "$stagingDir/WEB-INF/lib/",
                includes: "$name*.jar"
    }
}

}

Is grails.war.resources the way to go?
Update
For posterity, here is my somewhat complex example, using the answer below.
from _Events.groovy file
/**
 * Generate an optimized version of the sencha app.
 */
eventCreateWarStart = {warName, stagingDir ->
    //argsMap contains params from command line, e.g 'war --sencha.env=production'
def senchaEnvironment = argsMap["sencha.env"] ?: 'testing'

    //println is the only way I've found to write to the console.
println "running sencha optimizer code for $senchaEnvironment environment..."

ant.exec(outputproperty: "cmdOut", executable:'sencha',
        dir:"$stagingDir",failOnError:true){
    arg(value:'app')
    arg(value:'build')
    arg(value:"-e $senchaEnvironment" )
}

println "${ant.project.properties.cmdOut}"

println'completed sencha optimization process.'

}

A: You can put an eventCreateWarStart in your scripts/_Events.groovy.  This event receives two parameters, the name of the WAR and the stagingDir
eventCreateWarStart = { warName, stagingDir ->
  // ..
}

You have access to the ant variable giving you an AntBuilder so you can do stuff like
ant.exec(executable:'sencha') {
  arg(value:'app')
  arg(value:'build')
  // ...
}


text:
Q: UICollectionViewCompositionalLayout equal item height using autolayout I'm using a UICollectionViewCompositionalLayout to create a grid. Each cell contains a multi-line label. My goal is that, when 1 item in a group/row grows, all others in that group/row grow to the same height e.g. in the attached pic, I would like the cells in column 2 and 3, row 2, to match the height of the first cell that contains ("1000\ndetail").

I have tried various things like setting the height of the items to fractional(1) but that then prevented multi line. Other attempts such as changing the dimensions of the group did not help either. How can I set up my UICollectionViewCompositionalLayout to achieve my goal please?
Collection View:
NSCollectionLayoutSize *itemSize = [NSCollectionLayoutSize sizeWithWidthDimension:[NSCollectionLayoutDimension fractionalWidthDimension:0.333] heightDimension:[NSCollectionLayoutDimension fractionalHeightDimension:1]];
NSCollectionLayoutItem *item = [NSCollectionLayoutItem itemWithLayoutSize:itemSize];

NSCollectionLayoutSize *groupSize = [NSCollectionLayoutSize sizeWithWidthDimension:[NSCollectionLayoutDimension fractionalWidthDimension:1] heightDimension:[NSCollectionLayoutDimension estimatedDimension:40]];
NSCollectionLayoutGroup *group = [NSCollectionLayoutGroup horizontalGroupWithLayoutSize:groupSize subitem:item count:3];

NSCollectionLayoutSection *section = [NSCollectionLayoutSection sectionWithGroup:group];
UICollectionViewCompositionalLayout *compositionalLayout = [[UICollectionViewCompositionalLayout alloc] initWithSection:section];

UICollectionView *cv = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:compositionalLayout];
cv.translatesAutoresizingMaskIntoConstraints = NO;
cv.dataSource = self;
cv.delegate = self;
[self.view addSubview:cv];

[cv registerClass:[GridCVCell class] forCellWithReuseIdentifier:@"Cell"];

[cv.topAnchor constraintEqualToAnchor:self.view.topAnchor constant:100].active = YES;
[cv.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor constant:0].active = YES;
[cv.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor constant:0].active = YES;
[cv.heightAnchor constraintEqualToConstant:300].active = YES;

CollectionViewCell
- (instancetype)initWithFrame:(CGRect)frame {

    if ([super initWithFrame:frame]) {

        UILabel *titleL = [UIlabel new];
        titleL.translatesAutoresizingMaskIntoConstraints = NO;
        [self.contentView addSubview:titleL];

        [titleL.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:10].active = YES;
        [titleL.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-10].active = YES;
        [titleL.centerYAnchor constraintEqualToAnchor:self.contentView.centerYAnchor constant:-2].active = YES;

        [self.contentView.heightAnchor constraintEqualToAnchor:titleL.heightAnchor constant:10].active = YES;
    }

    return self;
}


text:
Q: Android using Splash Screen to load heavy Main data I have a very heavy Main Acitivty class which the first time you install the app , freezes until all the data is loaded , I want to show my Splash Screen activity while all the data is loading in the Main Activity and show my activity ONLY when the Main Activity has loaded everything :
Here is my current splash screen activity , currently it only does this:
public class SplashActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Intent intent = new Intent(this, MainActivity.class);
    startActivity(intent);
    finish();
}
}

How can I achieve this?

A: Regarding the comments on your question, it seems you're trying to update the UI of your MainActivity with the data you're loading. You can query/load your data on the splash activity, pass it on to the intent so you can gather it in onCreate of your MainActivity, or save all your data to SharedPreferences and access it from the MainActivity.
In SplashActivity:
Intent intent = new Intent(this, MainActivity.class);
// inside data loading completion callback or after synchronous data gathering methods
intent.putExtra("key","value");
startActivity(intent);

In MainActivity onCreate method
Bundle extras = intent.getExtras();
String value = extras.getString("key");

You can pass models as json formatted strings if you need.

A: if your splash screen named: spalsh.java
and your main activity named: MainActivity.java
first you create this class:
public class SliderPrefManager {
private Context context;
private SharedPreferences pref;
private static final String Pref_Name="slider-pref";
private static final String Key_Start="startslider";
public SliderPrefManager(Context context){
    this.context = context;
    pref = context.getSharedPreferences(Pref_Name,Context.MODE_PRIVATE);
}
public Boolean startSlider(){
    return pref.getBoolean(Key_Start,true);
}
public void setStartSlider(Boolean start){
    pref.edit().putBoolean(Key_Start,start).apply();
}

}
and in your splash screen add this code:
sliderPrefManager = new SliderPrefManager(login_Activity.this);
            sliderPrefManager.setStartSlider(false);

and you checked boolean of view slash screen, add this code in your mainActivity:
if (sliderPrefManager.startSlider()) {
        Intent intent = new Intent(choise_way_sec.this, login_Activity.class);
        startActivity(intent);

        finish();

    }


text:
Q: How to improve the run time for this code regarding formula updating? I am having difficulty with the run time of this code, it takes about 7 minutes to complete all the formulas for over 20,000 rows...is there any alterations to make this run faster?
 With Sheets("Rec")
 .Range("A6:A" & Cells(Rows.Count, "B").End(xlUp).Row + 5).FormulaR1C1 = "=CONCATENATE(RC[1],RC[2],RC[3],RC[4],RC[5],RC[6],RC[7],RC[8])"
 .Range("J6:J" & Cells(Rows.Count, "B").End(xlUp).Row + 5).FormulaR1C1 = "=SUMIF(CDGL!C[-9],Rec!RC[-9],CDGL!C[29])"
 .Range("K6:K" & Cells(Rows.Count, "B").End(xlUp).Row + 5).FormulaR1C1 = "=SUMIF(STS!C[-9],Rec!RC[-10],STS!C[28])"
 .Range("L6:L" & Cells(Rows.Count, "B").End(xlUp).Row + 5).FormulaR1C1 = "=RC[-2]-RC[-1]"
 .Range("M6:M" & Cells(Rows.Count, "B").End(xlUp).Row + 5).FormulaR1C1 = "=SUMIF(CDGL!C[-12],Rec!RC[-12],CDGL!C[30])"
 .Range("N6:N" & Cells(Rows.Count, "B").End(xlUp).Row + 5).FormulaR1C1 = "=SUMIF(STS!C[-12],Rec!RC[-13],STS!C[26])"
 .Range("O6:O" & Cells(Rows.Count, "B").End(xlUp).Row + 5).FormulaR1C1 = "=RC[-2]-RC[-1]"
 End With

A: My suggestion is to turn automatic calculation Off, then turn it back on (once the codes completes). I would also set the screenupdating to false... something like this, but at the beginning of your code.
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

With Sheets("Rec")
 .Range("A6:A" & Cells(Rows.Count, "B").End(xlUp).Row + 5).FormulaR1C1 = "=CONCATENATE(RC[1],RC[2],RC[3],RC[4],RC[5],RC[6],RC[7],RC[8])"
 .Range("J6:J" & Cells(Rows.Count, "B").End(xlUp).Row + 5).FormulaR1C1 = "=SUMIF(CDGL!C[-9],Rec!RC[-9],CDGL!C[29])"
 .Range("K6:K" & Cells(Rows.Count, "B").End(xlUp).Row + 5).FormulaR1C1 = "=SUMIF(STS!C[-9],Rec!RC[-10],STS!C[28])"
 .Range("L6:L" & Cells(Rows.Count, "B").End(xlUp).Row + 5).FormulaR1C1 = "=RC[-2]-RC[-1]"
 .Range("M6:M" & Cells(Rows.Count, "B").End(xlUp).Row + 5).FormulaR1C1 = "=SUMIF(CDGL!C[-12],Rec!RC[-12],CDGL!C[30])"
 .Range("N6:N" & Cells(Rows.Count, "B").End(xlUp).Row + 5).FormulaR1C1 = "=SUMIF(STS!C[-12],Rec!RC[-13],STS!C[26])"
 .Range("O6:O" & Cells(Rows.Count, "B").End(xlUp).Row + 5).FormulaR1C1 = "=RC[-2]-RC[-1]"
 End With

Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True


text:
Q: Operador condicional ?: não esta funcionando Não estou conseguindo utilizar o ?:
 #include <stdio.h>

 int main()
 {
 int num1 = 10;
 int num2 = 20;
 int resposta;

 num1 < num2 ? printf("sim\n") : printf("nao\n");

 // O erro acontece aqui ao compilar

 num1 < num2 ? resposta = 10 : resposta = -10;

 printf("%i\n", resposta);

 return 0;
 }

A: O operador condicional só aceita expressões e não statements, por isso não funciona. Ambos podem ser melhor escritos usando operador condicional apenas na parte que realmente varia, e que é uma expressão.
#include <stdio.h>

int main() {
    int num1 = 10;
    int num2 = 20;
    printf(num1 < num2 ? "sim\n" : "nao\n");
    int resposta = num1 < num2 ? 10 : -10;
    printf("%i\n", resposta);
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.

A: Use o if else normal
if(num1 < num2)
    resposta = 10;
else
    resposta = -10;


text:
Q: Cake 3 Blog Tutorial Error While using newEntity here is the error happened :
Unable to find table class for current entity
here is add method of Articles Controller
public function add()
{
    $article = $this->Articles->newEntity();
    if ($this->request->is('post')) {
        $article = $this->Articles->patchEntity($article, $this->request->data);
        if ($this->Articles->save($article)) {
            $this->Flash->success(__('Your article has been saved.'));
            return $this->redirect(['action' => 'index']);
        }
        $this->Flash->error(__('Unable to add your article.'));
    }
    $this->set('article', $article);
}

And Here is add.ctp

Add Article

<?php
    echo $this->Form->create($article);
    echo $this->Form->input('title');
    echo $this->Form->input('body', ['rows' => '3']);
    echo $this->Form->button(__('Save Article'));
    echo $this->Form->end();
?>

A: You need to upgrade your installation of CakePHP 3. What you are experiencing was a bug that appeared early after releasing the first Releseas Candidate. To update your installation run:
composer update

In the root directory of your app where the composer.json file is.

A: the problem was because of Entity ! , i jsut created a Entity file like this :
<?php
namespace App\Model\Entity;

use Cake\ORM\Entity;

/**
 * User Entity.
 */
class Article extends Entity
{

}


text:
Q: $injector:modulerr Injecting Custom Module Into Angular App I have this main application called dashboard and I want to inject a custom made module called core.
I keep getting this injection error and I have no idea why. I am following a template that my co-worker has and it is pretty much word for word so I do not know why it is not working for me.
app.js
(function(){

    'use strict';

    var dependencies = [
        'ngRoute',
        'core'

    ]; // all our modules

    angular.module('dashboard', dependencies).config(Config); //.config(Config);

    Config.$inject = ['$locationProvider'];

    function Config($locationProvider){
        $locationProvider.hashPrefix('!');

    }

    angular.element(document).ready(function(){

        angular.bootstrap(document, ['dashboard']);

    });

})();

layout.hbs
<!DOCTYPE html>
<html>
  <head>
    <title>{{title}}</title>
    <link rel='stylesheet' href='/javascripts/bootstrap/dist/css/bootstrap.css' />
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    <div class="flud-container">
            {{{body}}}
    </div>
  </body>

    <!-- JS  Libraries -->
  <script type='text/javascript' src='/lib/jquery/dist/jquery.min.js'></script>
  <script type='text/javascript' src='/lib/bootstrap/dist/js/bootstrap.min.js'></script>
  <script type='text/javascript' src='/lib/angular/angular.min.js'></script>
  <script type='text/javascript' src='/lib/angular-route/angular-route.min.js'></script>

  <script type='text/javascript' src='/modules/core/core.client.module.js'></script>
  <script type='text/javascript' src='/modules/core/config/core.client.routes.js'></script>
  <script type='text/javascript' src='/app.js'></script>
</html>

core.client.module.js
(function(){

    'use strict';

//  var dependencies = [

//  ];

    angular.module('core', []);

    angular.module('core').run(intialize);

    initialize.$inject = ['$rootScope', '$location'];

    function intitialize($rootScope, $location){

        //initialize module's variables here

    }

});

console error:
angular.js:38 Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.5.3/$injector/modulerr?p0=dashboard&p1=Error%…(http%3A%2F%2Flocalhost%3A3000%2Flib%2Fangular%2Fangular.min.js%3A20%3A463)

A: As you were using IIFE pattern for restricting the scope of code, you should invoke function of core.client.module.js immediately to core module get available.
core.client.module.js
(function(){

   //---- code here-----//

})(); //<---invoke the function


text:
Q: Dynamic List is duplicated on DataGrid using MVVM So the problem is next:
I have a table in SQL in which I have the amount of columns that are not predefined (May be different amount and different columns in different DBs). That is why I can NOT predefine all the values. i am using the dynamic list.
non duplicated example
This is my View
    <DataGrid.RowDetailsTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Vertical">
                                <Label Content="Attributes" />
                                <DataGrid AutoGenerateColumns="True" ItemsSource="{Binding DataContext.TestCollection, ElementName=DataGridWO}" />
                            </StackPanel>
                        </DataTemplate>
    </DataGrid.RowDetailsTemplate>

This is my ViewModel
                    // SELECT top 1 'GB40' AS[STORAGEPLANT], 'W' AS[PARTSORIGIN], 'Zelena Street 12' AS[STREET]
                    dynamic d =await  _workOrderAttributesService.GetWorkOrderAttributesDynamic(jobNumber);
                    List<dynamic> dynamicList2 = new List<dynamic>();
                     dynamicList2.Add( new {
                         STORAGEPLANT = "StorPlant2",
                         PARTSORIGIN = "D",
                         STREET = "Shevchenka Street 1"
                          });
                    dynamicList2.Add(d); // if I add this before adding predefined - duplication is happening
                    TestCollection = new ObservableCollection<dynamic>(dynamicList2);

duplicated example
Here are the outputs on the DataGrid on the first if I add dynamic object after the predefined one - it is NOT duplicated. But I need actually to add only this not predefined object - and if I do that - it is duplicated in One row I get all the parameters twice.
More information about the problem: I can not use predefined columns because it may differ, I need something that is super flex. I have added an SQL example in comments: So my SQL, for example returns:
 NAME AGE POSITION and the values are
 "Peter" , "21" , "Boss".
Why would it show on data grid as
  NAME AGE POSITION NAME AGE POSITION and the values are
 "Peter" , "21" , "Boss" , "Peter" , "21" , "Boss"?

  Why it duplicates columns But if I add some predefined object and then get from await - the result is only 3 columns with no duplication?


text:
Q: String Class Methods Most Commonly Used Any programming language. I'm interested in knowing what top 5 methods in a string class are used on data manipulations. Or what top 5 methods does one need to know to be able to handle data manipulation. I know probably all the methods together should be used, but I'm interested to see the 5 most common methods people use.
Thanks for your time.

A: I'd say

*

*String.Format()

*String.Split()

*String.IndexOf()

*String.Substring()

*String.ToUpper()

A: Adam's top 5 are pretty much mine. I might replace IndexOf() with Trim(); I use this EVERY TIME I get a value from the user. String.Compare() using the IgnoreCase values of the StringComparison enumeration would replace most of the uses I've seen for ToUpper().
Format, HEAVILY used in logs and other user messages (far more efficient for templated messages than a bunch of += statements or a StringBuilder()). Split and Substring, ditto, especially in file processing.

A: Adam's + KeithS. But don't forget the under the hood calls to
String.hashCode(),
String.equals(String rhs)
and its ilk.


text:
Q: Make last few lines of UILabel or UITextView fade out in swift. Please check the attached image
How to make control like this?

A: Here is what I have done:

*

*I created a UIView with a height of my choice, trailing, leading and bottom constraints to the textView.  This is my gradientView which I also use to add additional controls like the 'Read more' button, for example.

*In viewDidLayoutSubviews() I create a gradient layer for the gradientView.  (Note that you need to either remove the layer before creating it or ensure that it is added only once, otherwise your gradient will get darker every time viewDidLayoutSubviews is called)

*When my text change, I determine if the gradientView should be displayed or not by examining textView.contentSize.height > textView.frame.height
Herewith a Playground example
import UIKit
import PlaygroundSupport

class MyViewController : UIViewController {

var gradientView: UIView?
var gradient:CAGradientLayer?

override func loadView() {
    let view = UIView()
    view.backgroundColor = .gray

    let textView = UITextView()
    textView.frame = CGRect(x: 20, y: 20, width: 200, height: 300)
    textView.text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse eu gravida ligula, vitae venenatis felis. Suspendisse volutpat posuere pretium. Pellentesque quis quam ac velit tincidunt egestas. Phasellus sed scelerisque augue, interdum luctus eros. Praesent non augue eu enim dignissim convallis. Nunc commodo eros quis quam euismod, a malesuada ipsum mattis. Sed sit amet ipsum in justo dictum rutrum a sit amet sem. Sed sit amet mi vel nulla ornare congue. Nam elit ante, aliquam id consequat ac, pretium vel augue. Vivamus hendrerit commodo lectus, vel feugiat mi tempus non. Donec porta, ipsum id porttitor sodales, tortor lectus porta lacus, quis blandit turpis enim at libero. Donec ante est, rutrum quis malesuada a, accumsan at tortor. Nam molestie commodo nulla non suscipit. Nullam pellentesque nunc quam, vitae tempus turpis sollicitudin id. Integer vel varius urna, eleifend eleifend diam."
    textView.textColor = .black
    view.addSubview(textView)

    let gradientViewFrame = CGRect(x:textView.frame.origin.x, y: textView.frame.origin.y + textView.frame.height - 100, width: textView.frame.width, height: 100)
    gradientView = UIView(frame:gradientViewFrame)
        view.addSubview(gradientView!)
    self.view = view
}

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        gradient?.removeFromSuperlayer()
        gradient = gradientView?.gradientBackground(from:.white, to: UIColor.white.withAlphaComponent(0), direction: .bottomToTop)
    }
}

enum GradientDirection {
    case leftToRight
    case rightToLeft
    case topToBottom
    case bottomToTop
}

extension UIView {
    func gradientBackground(from color1: UIColor, to color2: UIColor, direction: GradientDirection) -> CAGradientLayer {
        let gradient = CAGradientLayer()
        gradient.frame = self.bounds
        gradient.colors = [color1.cgColor, color2.cgColor]

        switch direction {
        case .leftToRight:
            gradient.startPoint = CGPoint(x: 0.0, y: 0.5)
            gradient.endPoint = CGPoint(x: 1.0, y: 0.5)
        case .rightToLeft:
            gradient.startPoint = CGPoint(x: 1.0, y: 0.5)
            gradient.endPoint = CGPoint(x: 0.0, y: 0.5)
        case .bottomToTop:
            gradient.startPoint = CGPoint(x: 0.5, y: 1.0)
            gradient.endPoint = CGPoint(x: 0.5, y: 0.0)
        case .topToBottom:
            gradient.startPoint = CGPoint(x: 0.5, y: 0.0)
            gradient.endPoint = CGPoint(x: 0.5, y: 1.0)
        default:
            break
        }

        self.layer.insertSublayer(gradient, at: 0)
        return gradient
    }
}

// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()


text:
Q: Combinational meaning of $\sum\limits_{k=r}^{n} {k \choose r }={{n+1} \choose r+1}$ What's the combinational interpretation of the identity $\sum\limits_{k=r}^{n} {k \choose r }={{n+1} \choose r+1}$?

A: we want choose r+1 persons from n+1 persons
let A(1), A(2),..., A(n+1) are that n+1 persons
first we count the numbers of choices that A(1) is choosed that equals to (r,n)
second we count the numbers of choices that A(1) is not choosed but A(2) is choosed that equals to (r,n-1)
third...
and sum of these is equal to (r+1,n+1)


text:
Q: PhotoImage not shown when passed into a tk.Label() So I'm developing a GUI where a label, that will contain an Image, will only be shown after clicking the option onMenuUpToDown.
Other functions with the same code and same image format work properly but when it comes to this function, it just doesn't.
The following should be seen.
 and this is the output instead .
As for the image being passed to the label,  Image.show(), demonstrates that it arrives correctly to the variable .
This is part of my code:
def onMenuUpToDown():
    global OriginalImRight
    UpperImageHolder.grid(column=0,row=0)
    LowerImageHolder.grid(column=0,row=1)
    auxIm=ImageTk.getimage(OriginalImRight).resize((960,500))
    auxIm.show()
    print(str(type(auxIm)))
    UpperImageHolder['image']=ImageTk.PhotoImage(auxIm)
    LowerImageHolder['image']=ImageTk.PhotoImage(auxIm)
    AnaglyphImageHolder.grid_remove()
    LeftImageHolder.grid_remove()
    RightImageHolder.grid_remove()

# create the main window
root = tk.Tk()
root.attributes('-fullscreen', True)
root.title("Augmented Reality Glasses")
root.iconbitmap("ImagesAndIcons/Glasses.ico")

root.config(bg="darkgray")

# General Use Variables Definition
leftImage=tk.PhotoImage(file="ImagesAndIcons/Missing.png")
rightImage=leftImage
RedIm=leftImage
CyanIm=leftImage
Merged=leftImage
OriginalImLeft=leftImage
OriginalImRight=leftImage
UpperImage=ImageTk.PhotoImage(Image.open("ImagesAndIcons/Missing.png").resize((960,500)))
LowerImage=ImageTk.PhotoImage(Image.open("ImagesAndIcons/Missing.png").resize((960,500)))
# Frames definition
ImagesFrame=tk.Frame(width=1080,height=700, bg='darkgray')
ImagesFrame.grid(column=0,row=0)

    #Image display
        #ParallelView
LeftImageHolder=tk.Label(ImagesFrame,image=leftImage)
LeftImageHolder.grid(column=0,row=0)
RightImageHolder=tk.Label(ImagesFrame,image=leftImage)
RightImageHolder.grid(column=3,row=0)

        #Anaglyph View
AnaglyphImageHolder=tk.Label(ImagesFrame,image=Merged)
AnaglyphImageHolder.grid(column=1,row=0)
AnaglyphImageHolder.grid_remove()
        #UptoDown View
UpperImageHolder=tk.Label(ImagesFrame,image=UpperImage)
UpperImageHolder.grid(column=0,row=0)
UpperImageHolder.grid_remove() # here are the labels used and shown when called from menu
LowerImageHolder=tk.Label(ImagesFrame,image=LowerImage)
LowerImageHolder.grid(column=0,row=1)
LowerImageHolder.grid_remove()

# Menus Definition
MenuBar= tk.Menu(root)
fileMenu=tk.Menu(MenuBar, tearoff=0)

leftRightMenu=tk.Menu(fileMenu,tearoff=0)
leftRightMenu.add_command(label="Import left Image", command=onMenuImportLeft)
leftRightMenu.add_command(label="Import right Image", command=onMenuImportRight)

fileMenu.add_cascade(label='Import Images',menu=leftRightMenu)

EditMenu= tk.Menu(MenuBar, tearoff=0)
EditMenu.add_command(label="Anaglyph", command=onMenuAnaglyph)
EditMenu.add_command(label="Crossed sight", command=onMenuCrossed)
EditMenu.add_command(label="Parallel sight (Default view)", command=onMenuParallel)
EditMenu.add_command(label="Up to down sight", command=onMenuUpToDown) #Here's the command to the error

MenuBar.add_cascade(label='Import', menu=fileMenu)
MenuBar.add_cascade(label='Edit', menu=EditMenu)

root.config(menu=MenuBar)
# create a label and pack it into the main window

# run the GUI
root.mainloop()

I changed to tk.photoImage yet it throws and error
TypeError: __str__ returned non-string (type Image)

I also tried to diagnose the type of the image but is just a regular PIL.image.image and as said, when using show() the image is correct.
A similar post suggested its a matter of garbage collecting or global variables, yet it doesn't apply here (I think) because I made sure to use an local auxiliar variable to show the image, and basically it works.
similar post


text:
Q: Perforce recovery from version files Is there a way to recover a perforce depot where you only have the version files? The server where perforce was running on has crashed and is not currently running. Can I recovery from this?
Thanks in Advance

A: This is extremely hard and generally impossible, because critical information is stored in the Perforce server's database tables, which are separate from the version files.
But why not restart the Perforce server? Why did it crash, and why is it not currently running?
It sounds like you need to get in touch with Perforce Technical Support.


text:
Q: Vlookup using path in cell I want to create a tool that makes changes to a file that is selected as File1 in a workbook:

When I click "run past dues" the macro runs that makes changes in File1. In this macro, I want to use a vlookup that looks up files in File2 of which the path is in the tool workbook.
Everything works fine up untill this Vlookup. I cannot seem to get the macro use the path of File2 to lookup a value and paste in in File1.
Can someone help me with this? See the VBA code below:
Sub Past_dues_button12345()
'Macro to create past due list daily
Dim wb1 As Excel.Workbook
Dim File As String
Dim File2 As String

File = Sheets("Tool").Range("B2")
File2 = Sheets("Tool").Range("B3")

Set wb1 = Workbooks.Open(File)

remove_repair
add_columns_with_comments
add_data_new_column
vlookup
pastevalues
Sharewb

End Sub

Sub add_columns_with_comments()

    Columns("F:F").Select
    Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
    Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
    Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
    Range("Table1[[#Headers],[Column3]]").Select
    ActiveCell.FormulaR1C1 = "PN"
    Range("Table1[[#Headers],[Column2]]").Select
    ActiveCell.FormulaR1C1 = "MRPc"
    Range("Table1[[#Headers],[Column1]]").Select
    ActiveCell.FormulaR1C1 = "Comment"

End Sub

Sub vlookup()

    Range("H2").Select
'%%%%%%%%%%%%%%%%%%%%%% Do not know how to get the macro to lookup values of File2 here %%%%%%%%%%%%%%%%%%%%%%%
    ActiveCell.FormulaR1C1 = _
        "=VLOOKUP([File2]Sheet1!R2:R1000,8,0)
    Selection.AutoFill Destination:=Range("H2:H538")
    Range("H2:H538").Select

End Sub

A: First, try to use clear references for both workbooks, and avoid using select statement, it will make your sub a lot easier to understand and faster.
Then try Application.WorksheetFunction.VLookup
Something like that:
Sub test()

Dim wb As Workbook
Dim ws As worsheet
Dim wb2 As Workbook
Dim ws2 As worsheet
Dim my_range As Range

'create reference to the original workbook
Set wb = ThisWorkbook
Set ws = wb.Worksheets("Sheet_to_paste")

'create reference to the opem workbook
Set wb2 = Workbooks.Open(File)
set ws2 = wb2.Worksheets("Sheet1")

'set your vlookup range
Set my_range = ws2.Range("R2:R1000")

'vlookup your value
my_value = Application.WorksheetFunction.VLookup(value_to_lookup, myRange, 8, 0)
'paste your value
ws1.Range("H2") = my_value

End Sub


text:
Q: Smart way to update all documents in mongodb using python function I execute some_python_function on all elements of collection.
This function returns different values for each document.
I developed the following function, but it's very slow.
for doc in db.collection.find(query, projection):
    result = db.collection.update_one(
        {"_id": doc["_id"]},
        {"$set": {"field": some_python_function(doc["field"])}}
    )

I am looking any smarter way to do it, rather than updating documents one-by-one.
What would you recommend?
EDIT:
I have just found bulk operations in the API:
https://pymongo.readthedocs.io/en/stable/examples/bulk.html
from pymongo import UpdateOne

updates = []
for doc in db.collection.find(filter, projection):
    if doc.get("titles"):
        updated_field = some_python_function(doc["field"])
        if doc["field"] != updated_field:
            updates.append(
                UpdateOne(
                    {"_id": doc["_id"]},
                    {"$set": {"field": updated_field)}}
                )
            )
if updates:
    result = collection.bulk_write(updates)

A: Use bulkWrite to write multiples document at once.
Here is an answer for a similar question.