text:
Q: preg_replace when not inside double quotes Basically I want to replace certain words (e.g. the word "tree" with the word "pizza") in sentences. Restriction: When the word that should be replaced is between double quotes, the replace should not be performed.
Example:
The tree is green. -> REPLACE tree WITH pizza
"The" tree is "green". -> REPLACE tree WITH pizza
"The tree" is green. -> DONT REPLACE
"The tree is" green. -> DONT REPLACE
The ""tree is green. -> REPLACE tree WITH pizza

Is it possible to do this with regular expressions? I would count the number of double quotes before the word and check if it is odd or even. But is this possible using preg_replace in php?
Thanks!
//EDIT:
At the moment my code looks like the following:
preg_replace("/tree/", "pizza", $sentence)

But the problem here is to implement the logic with the double quotes. I tried things like:
preg_replace("/[^"]tree/", "pizza", $sentence)

But this does not work, because it checks only if a double quote is in front of the word. But there are examples above where this check fails.
Import is that I want to solve that problem with regex only.

A: Regular expression is not a tool that will do what you need for every job. You can use regular expression for this to a certain extent, but for all cases amongst nested quotes, it continues to get more complicated.
You could use a Negative Lookahead here.
$text = preg_replace('/\btree\b(?![^"]*"(?:(?:[^"]*"){2})*[^"]*$)/i', 'pizza', $text);

See Working demo
Regular expression:
\b               the boundary between a word char (\w) and not a word char
 tree            'tree'
\b               the boundary between a word char (\w) and not a word char
(?!              look ahead to see if there is not:
 [^"]*           any character except: '"' (0 or more times)
  "              '"'
 (?:             group, but do not capture (0 or more times)
  (?:            group, but do not capture (2 times):
   [^"]*         any character except: '"' (0 or more times)
    "            '"'
  ){2}           end of grouping
 )*              end of grouping
 [^"]*           any character except: '"' (0 or more times)
 $               before an optional \n, and the end of the string
)                end of look-ahead

Another option is to use controlled backtracking since your able to do this in php
$text = preg_replace('/"[^"]*"(*SKIP)(*FAIL)|\btree\b/i', 'pizza', $text);

See Working demo
The idea is to skip content in quotations. I first match the quotation followed by any character except " followed by a quotation and then make the subpattern fail and force the regular expression engine to not retry the substring with an other alternative with (*SKIP) and (*FAIL) backtracking control verbs.

A: There is a handy trick using some hidden regex powers :
~".*?"(*SKIP)(*FAIL)|\btree\b~s
Explanation:
~                   # start delimiter (we could have used /, #, @ etc...)
"                   # match a double quote
.*?                 # match anything ungreedy until ...
"                   # match a double quote
(*SKIP)(*FAIL)      # make it fail
|                   # or
\btree\b            # match a tree with wordboundaries
~                   # end delimiter
s                   # setting the s modifier to match newlines with dots .

In actual PHP code, you would want to use preg_quote() to escape regex characters. Here's a little snippet:
$search = 'tree';
$replace = 'plant';
$input = 'The tree is green.
"The" tree is "green".
"The tree" is green.
"The tree is" green.
The ""tree is green.';

$regex = '~".*?"(*SKIP)(*FAIL)|\b' . preg_quote($search, '~') . '\b~s';
$output = preg_replace($regex, $replace, $input);
echo $output;

Online regex demo     Online PHP demo

A: This one matches tree using a lookahead:
$pattern = '~\btree\b(?=([^"]|("[^"]*"))*$)~im';

$str = '
The tree is green. -> REPLACE tree WITH pizza
"The" tree is "green". -> REPLACE tree WITH pizza
"The tree" is green. -> DONT REPLACE
"The tree is" green. -> DONT REPLACE
The ""tree is green. -> REPLACE tree WITH pizza';

echo "<pre>".preg_replace($pattern,"pizza",$str)."</pre>";

It looks for tree, if found, matches it only, if followed by characters, that are not double-quotes [^"] or quoted groups "[^"]*" until end of line using modifiers i (PCRE_CASELESS) and m (PCRE_MULTILINE).
I don't want a green pizza! Merry Xmas :-)

A: use this pattern tree(?=(?:(?:[^"]*"){2})*[^"]*$) with gm options Demo
this is how it is constructed from the ground up:
tree(?=[^"]*")  "tree" that sees any amount of non-quote characters followed by a quote
tree(?=([^"]*"){2})  ~ twice
tree(?=(([^"]*"){2})*)  ~ as many times as possible
tree(?=(([^"]*"){2})*[^"]*)  ~ then optional non-quote characters
tree(?=(([^"]*"){2})*[^"]*$)  ~ to the end
tree(?=(?:(?:[^"]*"){2})*[^"]*$)   add non-capturing groups
php demo

A: I'm building a JS minimizer and this page helped me a lot with getting to the right regular expressions for it. But what this page has not answered sofar is what to do when a quoted string contains escaped quotes. I bookmarked this page for when I found the recipe.
/*
Regular expression group 'NotBetween'.
*/
function rgxgNotBetween($chars, $sep="|")
{
    $chars = explode($sep, $chars);

    $NB = [];

    foreach($chars as $CHR){
        //(*PRUNE) steps over $CHR when it is escaped; that is, preceded by a backslash.
        $NB[] = "(?:$CHR(?:\\\\$CHR(*PRUNE)|.)*?$CHR)";
    }

    $NB = join("|", $NB);

    return "(?:(?:$NB)(*SKIP)(*FAIL))";
}

function jsIdReplace($search, $replace, $source)
{
    $search = ""

    //SKIP further matching when between...
    //double or single qoutes or js regular expression slashes
    .rgxgNotBetween("\x22|\x27|\/")

    //match when NO preceding '.' and no ending ':' (object properties)
    ."|(?:(?<!\.)\b$search\b(?!:))"

    //but do match when preceding '?' or ':' AND ending ':' (ternary statements)
    ."|(?:(?<=\?|:)\b$search\b(?=:))";

    return preg_replace($search, $replace, $source);
}

function jsNoComments($source)
{
    //js comment markers NOT between quotes
    $NBQ = rgxgNotBetween("\x22|\x27");

    //block comments
    $source = preg_replace("#$NBQ|/\*.*?\*/#s", "", $source);

    //line comments; not preceded by backslash
    $source = preg_replace("#$NBQ|\h*(?<!\\\\)//.*\n?#", "", $source);

    return $source;
}


text:
Q: how to setup a socks 5 proxy server on centos I need a socks 5 proxy server that can run on centos. This would use a block of IP's so that client X with IP Address zzz connects tomy proxy server with ip xxx and then to remote host with ip yyy.

What is the best server software that I should install?

A: Consider installing dante Socks 5 server: yum install dante-server
You should enable a 3rd party repository to install it, I use RPMForge.

A: ss5. its not perfect, but its at least good, and free.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Some SBT dependencies are ignored I use SBT to include dependencies in my project, but I couldn't find the reason why some dependencies are ignored randomly. Even if they exist in .ivy2/cache directory, I tried to delete the content of it and retry but I still have the same problem.
The version of my SBT is 0.13.15 here is an example:
import org.scalatra.sbt._
import org.scalatra.sbt.PluginKeys._
import ScalateKeys._

val ScalatraVersion = "2.4.1"

ScalatraPlugin.scalatraSettings

scalateSettings

organization := "com.*****"

name := "****"

version := "0.1.0-SNAPSHOT"

scalaVersion := "2.10.5"

val sparkVersion = "1.6.0"

resolvers += Classpaths.typesafeReleases

libraryDependencies ++= Seq(
  "org.scalatra" %% "scalatra-json" % ScalatraVersion,
  "org.json4s"   %% "json4s-jackson" % "3.2.11",
  "org.scalatra" %% "scalatra" % ScalatraVersion,
  "org.scalatra" %% "scalatra-scalate" % ScalatraVersion,
  "org.scalatra" %% "scalatra-specs2" % ScalatraVersion % "test",
  "ch.qos.logback" % "logback-classic" % "1.1.5" % "runtime",
  "org.eclipse.jetty" % "jetty-webapp" % "9.2.15.v20160210" % "container",
  "javax.servlet" % "javax.servlet-api" % "3.1.0" % "provided"
)
libraryDependencies += "org.apache.spark" %% "spark-core" % sparkVersion
libraryDependencies += "org.apache.spark" %% "spark-sql" % sparkVersion
libraryDependencies += "org.scalaz" %% "scalaz-core" % "7.2.14"

scalateTemplateConfig in Compile := {
  val base = (sourceDirectory in Compile).value
  Seq(
    TemplateConfig(
      base / "webapp" / "WEB-INF" / "templates",
      Seq.empty,  /* default imports should be added here */
      Seq(
        Binding("context", "_root_.org.scalatra.scalate.ScalatraRenderContext", importMembers = true, isImplicit = true)
      ),  /* add extra bindings here */
      Some("templates")
    )
  )
}

enablePlugins(JettyPlugin)

In my example, sometimes the scalatra jsonis ignored and when I retried to create a new project the sparkdependencies was ignored

A: I finally found the solution of my issues, my project had to be converted to eclipse project through SBT with sbt eclipse command.
 Initially the Scalatra project was created via SBT with this command:
sbt new scalatra/scalatra-sbt.g8
The trick is to eclipsify the project before beginning to import dependencies.


text:
Q: Cocoapods headers not found when building application For the past few days I've been attempting to build an application, which keeps failing and gives the message "file not found". My friend is able to build the application on his computer, but I've tried on 3 computers and all 3 have been giving me the same error. I've tried uninstalling & reinstalling the cocoapods gem, deleting the pods and podfile.lock and reinstalling & upgrading pods without any luck. When I go into the pods folder, I see all the files, and it even autocompletes the file name in the prefix.pch file (Where the issue occurs). I'm using the same cocoapods as my friend (v0.34.4) & Xcode v6.1.
Also worth noting - the XCTest.framework, Tests.xctest and the libpods (but not the expanded pods folders) are all red.
Here's the error I get when compiling:
ProcessPCH /Users/name/Library/Developer/Xcode/DerivedData/app-dojnoizofbzbmmeascbukgzbsthh/Build/Intermediates/PrecompiledHeaders/app-Prefix-ahotoqoympyvtcaartebeekroqoj/app-Prefix.pch.pch app/app-Prefix.pch normal x86_64 objective-c com.apple.compilers.llvm.clang.1_0.compiler
cd /Users/name/app
export LANG=en_US.US-ASCII
export PATH="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -x objective-c-header -arch x86_64 -fmessage-length=0 -fdiagnostics-show-note-include-stack -fmacro-backtrace-limit=0 -std=gnu99 -fobjc-arc -fmodules -fmodules-cache-path=/Users/name/Library/Developer/Xcode/DerivedData/ModuleCache -fmodules-prune-interval=86400 -fmodules-prune-after=345600 -Wnon-modular-include-in-framework-module -Werror=non-modular-include-in-framework-module -Wno-trigraphs -fpascal-strings -O0 -Wno-missing-field-initializers -Wno-missing-prototypes -Werror=return-type -Wno-implicit-atomic-properties -Werror=deprecated-objc-isa-usage -Werror=objc-root-class -Wno-receiver-is-weak -Wno-arc-repeated-use-of-weak -Wduplicate-method-match -Wno-missing-braces -Wparentheses -Wswitch -Wunused-function -Wno-unused-label -Wno-unused-parameter -Wunused-variable -Wunused-value -Wempty-body -Wconditional-uninitialized -Wno-unknown-pragmas -Wno-shadow -Wno-four-char-constants -Wno-conversion -Wconstant-conversion -Wint-conversion -Wbool-conversion -Wenum-conversion -Wshorten-64-to-32 -Wpointer-sign -Wno-newline-eof -Wno-selector -Wno-strict-selector-match -Wundeclared-selector -Wno-deprecated-implementations -DDEBUG=1 -DDEBUG=1 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator8.1.sdk -fexceptions -fasm-blocks -fstrict-aliasing -Wprotocol -Wdeprecated-declarations -g -Wno-sign-conversion -fobjc-abi-version=2 -fobjc-legacy-dispatch -mios-simulator-version-min=7.1 -iquote /Users/name/Library/Developer/Xcode/DerivedData/app-dojnoizofbzbmmeascbukgzbsthh/Build/Intermediates/app.build/Debug-iphonesimulator/appTests.build/appTests-generated-files.hmap -I/Users/name/Library/Developer/Xcode/DerivedData/app-dojnoizofbzbmmeascbukgzbsthh/Build/Intermediates/app.build/Debug-iphonesimulator/appTests.build/appTests-own-target-headers.hmap -I/Users/name/Library/Developer/Xcode/DerivedData/app-dojnoizofbzbmmeascbukgzbsthh/Build/Intermediates/app.build/Debug-iphonesimulator/appTests.build/appTests-all-target-headers.hmap -iquote /Users/name/Library/Developer/Xcode/DerivedData/app-dojnoizofbzbmmeascbukgzbsthh/Build/Intermediates/app.build/Debug-iphonesimulator/appTests.build/appTests-project-headers.hmap -I/Users/name/Library/Developer/Xcode/DerivedData/app-dojnoizofbzbmmeascbukgzbsthh/Build/Products/Debug-iphonesimulator/include -I/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include -I/Users/name/Library/Developer/Xcode/DerivedData/app-dojnoizofbzbmmeascbukgzbsthh/Build/Intermediates/app.build/Debug-iphonesimulator/appTests.build/DerivedSources/x86_64 -I/Users/name/Library/Developer/Xcode/DerivedData/app-dojnoizofbzbmmeascbukgzbsthh/Build/Intermediates/app.build/Debug-iphonesimulator/appTests.build/DerivedSources -F/Users/name/Library/Developer/Xcode/DerivedData/app-dojnoizofbzbmmeascbukgzbsthh/Build/Products/Debug-iphonesimulator -F/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator8.1.sdk/Developer/Library/Frameworks -F/Applications/Xcode.app/Contents/Developer/Library/Frameworks -F/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks -F/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator8.1.sdk/Developer/Library/Frameworks -MD -MT dependencies -MF /Users/name/Library/Developer/Xcode/DerivedData/app-dojnoizofbzbmmeascbukgzbsthh/Build/Intermediates/PrecompiledHeaders/app-Prefix-ahotoqoympyvtcaartebeekroqoj/app-Prefix.pch.d -c /Users/name/app/app/app-Prefix.pch -o /Users/name/Library/Developer/Xcode/DerivedData/app-dojnoizofbzbmmeascbukgzbsthh/Build/Intermediates/PrecompiledHeaders/app-Prefix-ahotoqoympyvtcaartebeekroqoj/app-Prefix.pch.pch --serialize-diagnostics /Users/name/Library/Developer/Xcode/DerivedData/app-dojnoizofbzbmmeascbukgzbsthh/Build/Intermediates/PrecompiledHeaders/app-Prefix-ahotoqoympyvtcaartebeekroqoj/app-Prefix.pch.dia
/Users/name/app/app/app-Prefix.pch:17:13: fatal error: 'Parse/Parse.h' file not found
#import <Parse/Parse.h>
        ^1 error generated.

A: I finally managed to get the app to build.
Here's what I did:
I went to Product -> Scheme -> Edit Schemes
I subsequently unchecked the box under the Target -> Tests for "Analyze".

As the build had been previously failing at that point, so by unchecking it I was able to run it with no issues. Having spent time using it over the last few hours, I find it to be working normally, and can vouch that the issues mentioned previously by xCode have had no impact on real world usage (product is on market with many users).
Thanks for the folks that previously helped out.


text:
Q: DBeaver tunnel connection says ssh-keygen permission denied I tried connecting to my remote DB on DBeaver through a tunnel configuration.
I added the required details and tried connecting with my ssh private key, but it is throwing an error saying permission denied to run ssh-keygen.

Does anybody know the fix for this?
P.S: the tunnel connection to DB works fine when connecting through my terminal using commands.

A: You can switch from Jshc to SSHJ in the SSH connection advanced settings.
Like on this screenshot.


text:
Q: How does binary file should look like? I'm beginner in programming and I have a problem.
I want to write a structure to my binary file. And I'm not sure with the result. Here's the structure:
struct clientData
{
    unsigned int id;
    char name[25];
    char post[15];
    char degree[10];

    clientData(unsigned int, char*, char*, char*);
};

As you can see, my structure contains some char strings.
Here's the main question:
Should my strings be reconverted in final binary file (so they unreadable for applications like notepad etc)?
Because my result looks like that (I can't add the images, so I'll just paste it):

Miles Edgecombe МММММММММdocent ММММММММpew1 МММММММ

And this is how I write to the binary file:
ofstream binary_1st("binary_input.dat", ios::out | ios::binary);
...
binary_1st.write((char*) &cl, sizeof(clientData));
...
binary_1st.close();

A: You're writing structure to the files as-is, without any serialization or packing. So the structure will be written as it is, strings will be readable (if they are readable in the code), numbers will be numbers, etc.
BTW, this M's in
Miles Edgecombe МММММММММdocent ММММММММpew1 МММММММ

means that character arrays in your structure are not zeroed before writing strings to them, so there are no trailing zeros at the end and thus 'thrash' will be written at the end.

A:
Should my strings be reconverted in final binary file (so they
  unreadable for applications like notepad etc)? Because my result looks
  like that (I can't add the images, so I'll just paste it):

Don't worry about this.  Your strings probably don't contain newlines. Anyone code that converts the binary into text format should worry about Notepad &c.
You probably shouldn't be inventing your own binary format.  But if you really must, then watch out for the following.

*

*Make sure it contains version information.

*Be clear about data sizes, probably replace that int with something with a fixed 32- or 64- bit size.

*Store your integers byte-for-byte so that it has a fixed endiannes.  See http://linux.die.net/man/3/htons.

*Use a fixed string encoded.  UTF-8.

*Make sure you know how your strings terminate.  Either stick a size in front of them, or write out a NUL byte after the string (you example code does neither).

update: I just noticed my answer was probably not very clear for beginners, but I don't want to make it into an essay.  The main point is that storing the struct verbatim is probably not a good idea.  If you need more details on the rest, please ask.


text:
Q: How can I install the standalone ember router? I'm having trouble installing this -> https://github.com/tildeio/router.js in my MVC project.
I first just loaded these two scripts:
vendor/deps/route-recognizer.js
dist/router.js

Added the line:
var router = new Router();

I ended up with the following console errors:
Uncaught ReferenceError: define is not defined ***route-recognizer.js:1***
Uncaught TypeError: Cannot read property 'Promise' of undefined ***router.js:2084***
Uncaught ReferenceError: Router is not defined

I then loaded these scripts:
vendor/loader.js
vendor/deps/backburner.js
vendor/deps/rsvp.js
vendor/deps/route-recognizer.js
dist/router.js

I get these errors:
Uncaught TypeError: Cannot read property 'Promise' of undefined ***router.js:2084***
Uncaught ReferenceError: Router is not defined

This is code where the 'Promise' error occurs:
   define("route-recognizer", [], function() { return {"default": RouteRecognizer}; });
   define("rsvp", [], function() { return RSVP;});
-->define("rsvp/promise", [], function() { return {"default": RSVP.Promise}; });

Is there a promise.js I need as well? I found a promise.js in the RSVP.js package but loading gives me another error.

A: Was having the same problem.
There seem to be a code change according to this post for router.js to work as a standalone.
Grab the laters rsvp, route-recognizer and router and create a router object like so
<script src="routerjs/rsvp-latest.js"></script>
<script src="routerjs/route-recognizer.js"></script>
<script src="routerjs/router.min.js"></script>
<script>
  var router = new Router["default"]();
</script>


text:
Q: Should I use Python or Ruby for creating a cross-platform, compiled application? I'm a fan of Ruby but I don't oppose Python.  ( I have 2+ years of Ruby experience and maybe 2 months of Python ).
Anyway, I need to create a service for both the Mac and Windows (and Linux, actually) that takes certain files from different directories and sends them to S3.  I could use .NET on Windows but I don't want to use Objective-C and I would love to keep my code-base the same on all platforms.
So after digging around a little, it looks like I should be able to compile either Ruby or Python to byte-code and distribute an interpreter to run the code.
But, am I wrong in assuming that Python has better support for compiling code? As in .pyc byte code?
Also, I would prefer the end user not be able to read my source code but I'm not going to the end of the world to try and stop them.
Thanks!

A: You can indeed distribute Python bytecode (.pyc files) to avoid distributing your Python source code.
According to this answer, some Ruby implementations also support compiling to bytecode.
So it sounds like, depending on which Ruby implementation you pick, you may find very little difference between using Python and Ruby.
Keep in mind that bytecode isn't hard to disassemble, so a motivated user would still be able to find out quite a bit about your program's internals.  Using an obfuscator can make it harder (but still not impossible) to reverse engineer your bytecode.  This is discussed more in this Python question and this Ruby question.

A: Use whatever language you know well, I know python and use that to develop windows desktop applications and end user can't distinguish it with say a C# or C++ app


text:
Q: What is the Maximum character limit for nvarchar(Max) in LocalDB? While saving my record form C# to LocalDB, my strings get truncated although I am using NVarChar(Max) as column type.
Any Suggestions to fix this?


text:
Q: Finding all subgroups of $Z^*_{11} = \left\langle 2 \right\rangle $? Being given $Z^*_{11} = \left\langle 2 \right\rangle$, find all its subgroups.
I know from a theorem that $\left\langle n/k\right\rangle$ is a unique subgroup for all $k|n$, but 2 doesn't fit, yet still generates the entire group. What is a method that I can use to find all subgroups of a certain group?


text:
Q: Change scroll interval/unit/pixels Is there a way to change the size of each scroll with php code.
Explanation: When I scroll down it goes down x (50~) pixels, I wanna change the x to 20.
EDIT: This is my code...

  <link rel="icon" href="Images/Excel.png"><title>Excel</title>
  <?php
    print"<input src='Images\\0.png' type='image'>";
    $i=1;
    while($i<=26){
      print"<input src='Images\\".chr(64+$i).".png' type='image'>";
      $i++;
    }
    $i=1;
    while($i<=26){
      print"<input src='Images\\A".chr(64+$i).".png' type='image'>";
      $i++;
    }
    $i=1;
    $j=1;
    while($i<=100){
      print "<input src='Images\\".$i.".png' type='image'>";
      while($j<=52){
        print"<input src='Images\\Cell.png' type='image'>";
        $j++;
      }
      $j=1;
      $i++;
    }
  ?>


text:
Q: Scikit-learn : roc_auc_score I am using the roc_auc_score function from scikit-learn to evaluate my model performances.
Howver, I get differents values whether I use predict() or predict_proba()
p_pred = forest.predict_proba(x_test)
y_test_predicted= forest.predict(x_test)
fpr, tpr, _ = roc_curve(y_test, p_pred[:, 1])
roc_auc = auc(fpr, tpr)

roc_auc_score(y_test,y_test_predicted) # = 0.68
roc_auc_score(y_test, p_pred[:, 1])    # = 0.93

Could advise on that please ?
Thanks in advance

A: First look at the difference between predict and predict_proba.  The former predicts the class for the feature set where as the latter predicts the probabilities of various classes.
You are seeing the effect of rounding error that is implicit in the binary format of y_test_predicted. y_test_predicted is comprised of 1's and 0's where as p_pred is comprised of floating point values between 0 and 1.  The roc_auc_score routine varies the threshold value and generates the true positive rate and false positive rate, so the score looks quite different.
Consider the case where:
y_test           = [ 1, 0, 0, 1, 0, 1, 1]
p_pred           = [.6,.4,.6,.9,.2,.7,.4]
y_test_predicted = [ 1, 0, 1, 1, 0, 1, 0]

Note that the ROC curve is generated by considering all cutoff thresholds.  Now consider a threshold of 0.65...
The p_pred case gives:
TPR=0.5, FPR=0,

and the y_test_predicted case gives:
TPR=.75 FPR=.25.

You can probably see that if these two points are different, then the area under the two curves will be quite different too.
But to really understand it, I suggest looking at the ROC curves themselves to help understand this difference.
Hope this helps!


text:
Q: hasOne does not deliver users and profiles When I want retrieve my users, I have no profiles.
I setted up my database along the convention.
I got the following code in my model (UserTable):
<?php
// src/Model/Table/UsersTable.php
namespace App\Model\Table;

use Cake\ORM\Table;

class UsersTable extends Table
{
    public function initialize(array $config)
    {
        $this->addBehavior('Timestamp');
        $this->hasOne('Profiles')
          ->setDependent(true);
    }
}

My Controller is this:
<?php
// src/Controller/UsersController.php

namespace App\Controller;

class UsersController extends AppController
{
    public function initialize()
    {
        parent::initialize();
        $this->loadComponent('Paginator');
        $this->loadComponent('Flash'); // Include the FlashComponent
    }

    public function index()
    {
        $query = $this->Users->find();
        $results = $query->all();
        $this->set(compact('results'));
    }
}

After call index, I get all my users, which is a good thing. But there are no profiles.
I think, I missed a line of code somewhere. Any help is appreciated.

A: I missed the contain thing. In cakephp 2, it was not needed.
The controller code is now this (it's working):
$query = $this->Users->find();
$query->contain(['Profiles']);
$results = $query->all();

thanks anyway.


text:
Q: Component Number Metric for Dimension Reduction using UMAP I'm planning on using UMAP to do some dimension reduction for clustering and ran into an issue where I didn't know how to determine/calculate how many components to use to best represent my data. With methods like PCA, one can use the explained variance to identify the best number of components, however I was not able to find something similar for UMAP.
Is there a metric I should be using with UMAP in order to determine this or will determining the optimal component number be a guess and check process?


text:
Q: $\Vert x_{n} - y_{n} \Vert $is a cauchy sequence in $\mathbb{F}$ Given $X$ is a normed linear space over the field $\mathbb{F}$ and $(x_{n}), (y_{n})$ be Cauchy seuqences in $X$ then $\Vert x_n - y_n \Vert$ is a Cauchy sequence in $\mathbb{F}$ and consequently the $\lim_{n\rightarrow \infty} \Vert x_n -y_n\Vert$ exists
I know that this can be stated using the triangle inequality but I am not able to see how to use it here

A: For every $c>0$, there exists $N_1$ such that $n,m>N_1$ implies that $\|x_n-x_m\|<c/2$, there exists $N_2$ such that $n,m>N_2$ implies that $\|y_n-y_m\|<c/2$, take $N=\max(N_1,N_2)$ if $n,m>N$,  $\|(x_n-y_n)-(x_m-y_m)\|=\|(x_n-x_m)+(y_m-y_n)\|\leq \|x_n-x_m\|+\|y_n-y_m\|<c$.


text:
Q: What is mean by Differential Daisy Chain UART? What is mean by differential daisy chain UART? And what is the difference between UART and differential daisy chain UART?
While reading datasheet I come across this concept if anybody knows then I would like to know it.

A: It most likely means that the output (TX) of one UART is fed to the input (RX) on another one. The benefit is that from the host/microcontroller side you need just one UART to communicate with many slave devices in a chain. This is similar to a daisy chain SPI (for example: like chain of shift registers).
This of course has to be supported by the protocol, so for example when you send message to the third device in the chain the other devices must be somehow bypassed.
In this particular case the functionality is explained in "7.3.10 Stacked Daisy-Chain Communications" of the datasheet. Basically your MCU talks via a standard UART to a "master" chip that is connected with differential lines to the other chips in the chain and uses a proprietary protocol.

A: differential is where two wires carry the signal in opposite sense - one goes high when the other goes low and vice versa.
daisy-chain is several devices connect in a directed chain-like structure each connected to it neighbours, see figure 17 on page 32.
But the comm connectors seem to use a biphase code, not NRZ like a normal UART
(page 33) and the document does not seem to call these connectors a UART anywhere
RX and TX OTOH are for connection to an ordinary UART.


text:
Q: Django command not noticing newly added data I'm running from the interactive shell (via ./manage.py shell_plus)
c = MyModel.objects.count()
while True
    assert MyModel.objects.count() == c
    sleep(1)

and then I go to the admin and add a new MyModel object. I would assume the assertion will fail, but it keeps getting the old count (not noticing the new record).
Do you know what is causing this?
My first suspect is the cache system, but I don't know how to test it.
Do you know how to overcome this and allow the queries to notice the new records?
thanks in advance...

A: This sounds like an issue with transactions. You probably want to set your script to commit manually after each call to process_records.
See the transaction docs.


text:
Q: Using Unsigned Primitive Types Most of time we represent concepts which can never be less than 0. For example to declare length, we write:
int length;

The name expresses its purpose well but you can assign negative values to it. It seems that for some situations, you can represent your intent more clearly by writing it this way instead:
uint length;

Some disadvantages that I can think of:

*

*unsigned types (uint, ulong, ushort) are not CLS compliant so you can't use it with other languages that don't support this

*.Net classes use signed types most of the time so you have to cast

Thoughts?

A: If you decrement a signed number with a value of 0, it becomes negative and you can easily test for this. If you decrement an unsigned number with a value of 0, it underflows and becomes the maximum value for the type - somewhat more difficult to check for.

A: Your second point is the most important. Generally you should just use int since that's a pretty good "catch-all" for integer values. I would only use uint if you absolutely need the ability to count higher than int, but without using the extra memory long requires (it's not much more memory, so don't be cheap :-p).

A: "When in Rome, do as the Romans do."
While there is theoretically an advantage in using unsigned values where applicable because it makes the code more expressive, this is simply not done in C#. I'm not sure why the developers initially didn't design the interfaces to handle uints and make the type CLS compliant but now the train has left the station.
Since consistency is generally important I'd advise taking the C# road and using ints.

A: I think the subtle use of uint vs. int will cause confusing with developers unless it was written into developer guidelines for the company.
If the length, for example, can't be less than zero then it should be expressed clearly in the business logic so future developers can read the code and know the true intent.
Just my 2 cents.

A: I will point out that in C# you can turn on /checked to check for arithmetic overflow / underflow, which isn't a bad idea anyways. If performance matters in a critical section, you can still use unchecked to avoid this.
For internal code (ie code that won't be referenced in any interop manor with other languages) I vote for using unsigned when the situation warrants it, such as length variables as mentioned earlier. This - along with checked arithmetic - provides one more net for developers, catching subtle bugs earlier.
Another point in the signed vs unsigned debate is that some programmers use values such as -1 to indicate errors, when they wouldn't otherwise have meaning. I subscribe to the view that each variable should have only one purpose, but if you - or colleagues you code with - like to indicate errors in this way, leaving variables signed gives you the flexibility to add error states later.

A: Your two points are good. The primary reason to avoid it is casting, though. Casting makes them incredibly annoying to use. I tried using unisigned variables once but I had to sprinkle casts absolutely everywhere because the framework methods all use signed integers. Therefore, whenever you call a framework method, you have to cast.


text:
Q: Lifetime Issue with Associated Types I've been pulling my hair out over the last week due to this incredibly annoying issue with lifetimes.
The problem occurs when I try to put a reference to a Buffer inside a DataSource, which is then referenced to a DrawCommand. I'm getting the error: vertex_data_source does not live long enough.
src/main.rs:65:23: 65:41 error:
src/main.rs:65         data_source: &vertex_data_source
                                     ^~~~~~~~~~~~~~~~~~
src/main.rs:60:51: 67:2 note: reference must be valid for the block suffix following statement 3 at 60:50...
src/main.rs:60     let vertices = VertexAttributes::new(&buffer);
src/main.rs:61
src/main.rs:62     let vertex_data_source = factory.create_data_source(vertices);
src/main.rs:63
src/main.rs:64     let command: DrawCommand<ResourcesImpl> = DrawCommand {
src/main.rs:65         data_source: &vertex_data_source
               ...
src/main.rs:62:67: 67:2 note: ...but borrowed value is only valid for the block suffix following statement 4 at 62:66
src/main.rs:62     let vertex_data_source = factory.create_data_source(vertices);
src/main.rs:63
src/main.rs:64     let command: DrawCommand<ResourcesImpl> = DrawCommand {
src/main.rs:65         data_source: &vertex_data_source
src/main.rs:66     };
src/main.rs:67 }

It says vertex_data_source has to be valid for the block suffix following statement 3 at line 60. My interpretation of that error is that vertex_data_source should be defined before line 60. But to create the vertex_data_source in the first place I need access to those VertexAttributes on line 60, so I can't just swap the order around.
I feel like all the 'a lifetimes sprinkled over my code need to be split into 2 or maybe just removed, however I've tried every combination that seemed sensible and I'm not out of ideas.
Below is a greatly simplified example of my code that demonstrates the problem. I would really appreciate a sanity check and hopefully a fresh mind might be able to spot the issue. (every time before a few days of fiddling has produced a fix but this time I'm stumped).
use std::cell::RefCell;
use std::marker::PhantomData;

pub struct DrawCommand<'a, R: Resources<'a>> {
    pub data_source: &'a R::DataSource
}

pub trait Resources<'a> {
    type DataSource: 'a;
    type Buffer: 'a;
}

pub struct DataSource<'a> {
    id: u32,
    attributes: Vec<VertexAttributes<'a, ResourcesImpl<'a>>>,
    current_element_array_buffer_binding: RefCell<Option<Buffer<'a>>>
}

pub struct Buffer<'a> {
    context: &'a GraphicsContextImpl
}

pub struct GraphicsContextImpl;

pub struct ResourcesImpl<'a> {
    phantom: PhantomData<&'a u32> // 'a is the lifetime of the context reference
}

impl<'a> Resources<'a> for ResourcesImpl<'a> {
    type Buffer = Buffer<'a>;
    type DataSource = DataSource<'a>;
}

struct Factory<'a> {
    context: &'a GraphicsContextImpl
}

impl<'a> Factory<'a> {
    /// Creates a buffer
    fn create_buffer<T>(&self) -> Buffer<'a> {
        Buffer {
            context: self.context
        }
    }

    fn create_data_source(&self, attributes: Vec<VertexAttributes<'a, ResourcesImpl<'a>>>) -> DataSource<'a> {
        DataSource {
            id: 0,
            attributes: attributes,
            current_element_array_buffer_binding: RefCell::new(None)
        }
    }
}

fn main() {
    let context = GraphicsContextImpl;
    let factory = Factory {
        context: &context
    };
    let buffer = factory.create_buffer::<u32>();

    let vertices = VertexAttributes::new(&buffer);

    let vertex_data_source = factory.create_data_source(vec!(vertices));

    let command: DrawCommand<ResourcesImpl> = DrawCommand {
        data_source: &vertex_data_source
    };
}

pub struct VertexAttributes<'a, R: Resources<'a>> {
    pub buffer: &'a R::Buffer,
}

impl<'a, R: Resources<'a>> VertexAttributes<'a, R> {
    pub fn new(buffer: &'a R::Buffer) -> VertexAttributes<'a, R> {
        VertexAttributes {
            buffer: buffer
        }
    }
}

Thanks very much in advance.
EDIT:
I've updated the code to better reflect my actual implementation.
By the way - replacing this:
let vertex_data_source = factory.create_data_source(vec!(vertices));

With this:
let vertex_data_source = DataSource {
    id: 0,
    attributes: vec!(vertices),
    current_element_array_buffer_binding: RefCell::new(None)
};

Doesn't solve the issue.

A: This allows your example to compile:
pub struct DrawCommand<'a : 'b, 'b, R: Resources<'a>> {
    pub data_source: &'b R::DataSource
}

However, I'm finding it extremely difficult to create a more minimal example. As best I can determine, you have an issue because you are declaring that you will hold a reference to an item that itself has a reference, and that those two references need to have a common lifetime ('a). Through some combination of the other lifetimes, this is actually impossible.
Adding a second lifetime allows the reference to the DataSource to differ from the reference of the DataSource itself.
I'm still going to try to create a more minified example.


text:
Q: Inputting string into PostgreSQL results in syntax error at single quote I am running through a very large data set with a json object for each row. And after passing through almost 1 billion rows I am suddenly getting an error with my transaction.
I am using Python 3.x and psycopg2 to perform my transactions.
The json object I am trying to write is as follows:
{"message": "ConfigManager: Config if valid JSON but doesn't seem to have the correct schema. Adopting new config aborted."}

and psycopg2 is reporting the following:
syntax error at or near "t"
LINE 3: ...": "ConfigManager: Config if valid JSON but doesn't seem to ...

I am aware that the problem is the single quote, however I have no idea of how to escape this problem so that the json object can be passed to my database.
My json column is of type jsonb and is named first_row
So if I try:
INSERT INTO "356002062376054" (first_row) VALUES {"message": "ConfigManager: Config if valid JSON but doesn't seem to have the correct schema. Adopting new config aborted."}

I still get an error. And nothing I seem to do will fix this problem. I have tried escaping the t with a \ and changing the double quotes to single qoutes, and removing the curly brackets as well. Nothing works.
I believe it's quite important that I am remembering to do
`json.dumps({"message": "ConfigManager: Config if valid JSON but doesn't seem to have the correct schema. Adopting new config aborted."})` in my python code and yet I am getting this problem.

A: You have to double a single quote to escape it in SQL.
But the fact that you have this problem means that your code is vulnerable to SQL injection. You should use parameterized statements and feed the string as parameter when executing the statement. If you do this, the problem will go away.
The psycopg2 documentation has this dire, but well warranted warning:

Warning: Never, never, NEVER use Python string concatenation (+) or string parameters interpolation (%) to pass variables to a SQL query string. Not even at gunpoint.

A: You can use dollar sign constraints or C style escape for this. Eg per docs:

An escape string constant is specified by writing the letter E (upper
  or lower case) just before the opening single quote, e.g., E'foo'

So then:
INSERT INTO "356002062376054" (first_row) SELECT e'{"message": "ConfigManager: Config if valid JSON but doesn\'t seem to have the correct schema. Adopting new config aborted."}'

or
INSERT INTO "356002062376054" (first_row) values (E'{"message": "ConfigManager: Config if valid JSON but doesn\'t seem to have the correct schema. Adopting new config aborted."}');

should work for you


text:
Q: Does MongoDB Scala driver have any equivalent to the explain() function in the JavaScript interface? Does MongoDB Scala driver have any equivalent to the explain() function in the JavaScript interface?
I'm wondering what the MongoDB Scala driver does with a query like this:
collection.find(
  and(geoWithinBox("geometry", bbox.swLon, bbox.swLat, bbox.neLon, bbox.neLat),
    equal("properties.foo", "abc"),
    exists("properties.bar")))
  .limit(100)

MongoDB does not seem to be using the geospatial index I created and I'm trying to figure out why.  Rather, it seems to be scanning every document.  At least that's what I noticed when I tried explain with this JS query in MongoShell:
{$and: [{"geometry": {$geoWithin: {$box: [ [-78,40],[-76,41] ] }}},
        {$and: [{"properties.foo": {$eq: "abc"}},
                {"properties.bar": {$exists: 1}}
               ]
        }
       ]
}

(I didn't have nested-ands in the first version of the JS immediately above.  I was just trying different things to see if they triggered use of the geospatial index.)

A: This answer is based on current MongoDB Scala driver v1.1.0 and current MongoDB v3.2.
Currently there is no cursor explain() function via the Scala driver. This is because explain has been determined to be not a normal use-case for a driver. I would recommend to use the Mongo Shell for debugging query index usages. See MongoDB driver spec for more info.
However you can still use runCommand to get explain output. For example of $geoWithin query in Mongo Shell :
db.collection.find({
    "geometries":{
        $geoWithin:{
            $box:[[-78,40], [-76, 41]]
        }
    }
}).explain()

You can do the same using command in Scala like below:
val command = Document("explain" -> Document("find"->"collection",
                        "filter"->Document("geometries"->Document(
                                "$geoWithin"->Document(
                                     "$box"->Seq(Seq(-78, 40), Seq(-76, 41))
                                  )
                            )
                        )
                    )
               )
val observable = db.runCommand(command).printHeadResult()

Or for aggregation queries
  db.runCommand(
    Document(
      "aggregate" -> "collection",
      "pipeline" -> List[Document]( ... ),
      "explain" -> true
    )
  )

Worth mentioning that only 2d geospatial index supports $box operator. Make sure that you have the right index for field geometries.
Also, by default queries are constructed implicitly with AND, so you don't have to specify $and explicitly. Your example can be shorten to :
db.collection.find({"geometry": {$geoWithin: {$box: [[-78,40],[-76,41]] }},
                    "properties.foo" : "abc",
                    "properties.bar": {$exists:true}
                   })


text:
Q: new command with cases? This has been answered here for text outputs with the use of \IfEqCase from the xstring package. But if I want to use the output as a value to set a parameter in a function, it fails.
Here is my MWE:
\documentclass[a4paper]{article}

\usepackage{lettrine,xstring}

\newcommand*{\Lettrine}[1]{%
    \lettrine[lines=1, findent=\IfEqCase{#1}{%
        {P}{-0.8em}%
        {Q}{1em}%
    }[\PackageError{Lettrine}{Undefined option to Lettrine: #1}{}]%
    ]{\textit{#1}}{}%
}

\newcommand*{\LettrineSimply}[1]{\lettrine[lines=1, findent=-0.8em]{\textit{#1}}{}}

\begin{document}
\LettrineSimply{P} erfectly working !
\Lettrine{P} ossibly it will work !
\end{document}

\LettrineSimply works, but I want to use different findent depending on the letter. In my attempt with the use of \IfEqCase, I have the following compilation error:
$ pdflatex MWE_lettrine_command.tex
This is pdfTeX, Version 3.1415926-2.5-1.40.14 (TeX Live 2013)
 restricted \write18 enabled.
entering extended mode
(./MWE_lettrine_command.tex
LaTeX2e <2011/06/27>
Babel <3.9f> and hyphenation patterns for 15 languages loaded.
(/usr/share/texmf-dist/tex/latex/base/article.cls
Document Class: article 2007/10/19 v1.4h Standard LaTeX document class
(/usr/share/texmf-dist/tex/latex/base/size10.clo))
(/usr/share/texmf-dist/tex/latex/lettrine/lettrine.sty
(/usr/share/texmf-dist/tex/latex/graphics/keyval.sty)
Loading lettrine.cfg
(/etc/texmf/tex/latex/lettrine.d/lettrine.cfg))
(/usr/share/texmf-dist/tex/generic/xstring/xstring.sty
(/usr/share/texmf-dist/tex/generic/xstring/xstring.tex))
(./MWE_lettrine_command.aux)
! Missing number, treated as zero.
<to be read again>
                   \let
l.17 \Lettrine{P}
                  ossibly it will work !
?

If I just ENTER:
! Illegal unit of measure (pt inserted).
<to be read again>
                   \let
l.17 \Lettrine{P}
                  ossibly it will work !

Do I try to assign a string to the findent parameter? How can I solve that?
Otherwise, is it possible to define tables or associative maps inside commands?

A: As your \Lettrine command certainly does some un-expandable things, we don't really need a fully expandable version of \IfEqCase.

\documentclass[a4paper]{article}

\usepackage{lettrine,xstring}

\makeatletter
\newcommand*{\Lettrine}[1]{%
    \IfEqCase{#1}{%
        {P}{\def\@@temp{findent=-0.8em,}}%
        {Q}{\def\@@temp{findent=1em,}}%
    }[\PackageError{Lettrine}{Undefined option to Lettrine: #1}{}%
      \def\@@temp{}]%
    \expandafter\lettrine\expandafter[\@@temp lines=1]{\textit{#1}}{}%
}
\makeatother

\newcommand*{\LettrineSimply}[1]
   {\lettrine[lines=1, findent=-0.8em]{\textit{#1}}{}}

\begin{document}\thispagestyle{empty}

\LettrineSimply{P} erfectly working !
\Lettrine{P} ossibly it will work !
\Lettrine{Q} uite certainly it does work !
%\Lettrine{R} arely are errors encountered ! % generates error as expected
\end{document}

A: You need the \ifeqcase to be defined as expandable macro. My solution uses only TeX primitives, no xparse package is needed:
\documentclass[a4paper]{article}
\usepackage{lettrine}

\def\ifeqcase#1#2{\ifeqcaseA#1#2\end}
\def\ifeqcaseA#1#2#3#4{%
   \ifx#1#2#3\expandafter\ifeqcaseE\expandafter#4%
   \else\ifx#4\end
        \else \expandafter\expandafter\expandafter
              \ifeqcaseA\expandafter\expandafter\expandafter#1%
                        \expandafter\expandafter\expandafter#4%
   \fi \fi
}
\def\ifeqcaseE#1\end#2{}

\newcommand*{\Lettrine}[1]{%
    \lettrine[lines=1, findent=\ifeqcase{#1}{%
        {P}{-0.8em}%
        {Q}{1em}%
    }{\PackageError{Lettrine}{Undefined option to Lettrine: #1}{}}%
    ]{\textit{#1}}{}%
}
\newcommand*{\LettrineSimply}[1]{\lettrine[lines=1, findent=-0.8em]{\textit{#1}}{}}

\begin{document}
\LettrineSimply{P}erfectly working !
\Lettrine{P}ossibly it will work !
\Lettrine{Q}next test.
\end{document}

See that the different syntax is used for \ifcaseeq: the else part is in normal TeX braces.
I know that the question was LaTeX-type but we can compare the code which generates the same effect in plainTeX (using \eqifcase by @jfbu).
\input opmac

\def\eqifcase #1#2#3{\eqifcaseA #1#2#1{#3}\end}
\def\eqifcaseA #1#2#3{\ifx #1#2\eqifcaseE{#3}\fi \eqifcaseA #1}
\def\eqifcaseE #1\fi #2\end{\fi #1}

\def\letterfirst#1{\vskip.7\baselineskip\noindent{\it\thefontsize[24.7]#1}%
   \kern\eqifcase#1{P{-0.5em} Q{1em} R{.1em} S{.4em}}
   {0pt\opwarning{\string\letterfirs{#1} in unspaced}}%
}

\letterfirst Possibly it will work!
\letterfirst Qnext text.

\end

That is the beauty of TeX.

A: This is more of a comment on wipet's answer but is a bit too long.
Here is another way to do an expandable \ifeqcase. The conditions are the same: we only compare single tokens. We use \eqifcase as name.
Added note: initial motivation in revisiting wipet's interesting \ifeqcase was to move the execution of the selected branch to after  the case-switch has been cleared. This being done it is just one step to make the \eqifcase into a macro which expands in only two steps, before executing the selected code. And another aspect (independent of the added "expand in only two steps") worth pointing out is that \eqifcase can be used as argument to macros which expand their argument via  \romannumeral-`0. I have added an illustration of this below.

\documentclass{article}

\def\eqifcase #1#2#3{\eqifcaseA #1#2#1{#3}\end }

\def\eqifcaseA #1#2#3{\ifx #1#2\eqifcaseDo{#3}\fi \eqifcaseA #1}

\def\eqifcaseDo #1\fi #2\end{\fi #1}

\def\test #1{%
    \eqifcase {#1}{{A}{aa}{B}{bb}{C}{cc}}{not found}}

\begin{document}\thispagestyle{empty}
\test{A}

\test{B}

\test{C}

\test{D}
\end{document}

Illustration (using within macros expanding their arguments via f-expansion) and Extension (case-switch expands in only two steps; this aspect is not illustrated here)
\documentclass{article}

\def\eqifcase #1#2#3{\romannumeral0\eqifcaseA #1#2#1{#3}\end }

\def\eqifcaseA #1#2#3{\ifx #1#2\eqifcaseDo{#3}\fi \eqifcaseA #1}

\def\eqifcaseDo #1\fi #2\end{\fi \space #1}

\usepackage {xintfrac}

\makeatletter
\newcommand{\DOOPERATION}[1]{\eqifcase {#1}
    {+\xintAdd
     *\xintMul
     -\xintSub
     /\xintDiv
     T\xintTrunc}{\@gobbletwo}}
\makeatother

\begin{document}

Demonstrating the use within macros applying f-expansion to their arguments:

\xintIrr {\DOOPERATION -{113/355}{22/7}}

\xintIrr {\DOOPERATION *{1024/243}{243/1024}}

\xintIrr {\DOOPERATION /{\DOOPERATION *{1001}{999}}{\DOOPERATION *{77}{111}}}

\DOOPERATION {T}{18}{113/355}

\end{document}

A: You should use an expandable command as the value of findent, but \IfEqCase isn't. Here's a working version with xparse; I've added \ignorespaces so that it's immaterial if you leave a space after \Lettrine{P} or not.
\documentclass[a4paper]{article}

\usepackage{lettrine,xparse}

\ExplSyntaxOn
\NewDocumentCommand{\Lettrine}{m}
 {
  \lettrine[lines=1, findent=\lalebarde_case:n { #1 }]{\textit{#1}}{}
  \ignorespaces
}

\cs_new:Npn \lalebarde_case:n #1
 {
  \str_case:nnF { #1 }
   {
    {P}{-0.8em}
    {Q}{1em}
   }
   {% none of the above
    \PackageError{Lettrine}{Undefined option to Lettrine: #1}{}
   }
 }
\ExplSyntaxOff

\newcommand*{\LettrineSimply}[1]{\lettrine[lines=1, findent=-0.8em]{\textit{#1}}{}\ignorespaces}

\begin{document}
\LettrineSimply{P} erfectly working!

\Lettrine{P}erfectly working!

\Lettrine{Q}uestion: will it work?
\end{document}

You should be able to add whatever letter you want; the order is almost unimportant; for greater efficiency, put the most frequent letters first.

A: Here is the final code, from jfbu solution, mixed with what I have learnt from wipet and egreg:
\documentclass{article}
\usepackage{lettrine}

\def\eqifcase #1#2#3{\eqifcaseA #1#2#1{#3}\end }

\def\eqifcaseA #1#2#3{\ifx #1#2\eqifcaseDo{#3}\fi \eqifcaseA #1}

\def\eqifcaseDo #1\fi #2\end{\fi #1}

\def\Lettrine #1{\vspace{-4ex}\lettrine[lines=1,findent=%
    \eqifcase {#1}{{P}{-0.8em}{T}{-0.6em}}{-0.1em}%
    ]{\textit{#1}}{}}

\begin{document}\thispagestyle{empty}
\section{section 1}
\Lettrine{P}owerfull macro !
\section{section 2}
\Lettrine{D}efault.
\section{section 3}
\Lettrine{T}remendous!
\section{section 4}
without lettrine to show that thanks to \textit{\\vspace\{-4ex\}} in the macro, we keep the same vertical space between the text baseline and the section title.
\end{document}

Big thanks to all the three of you, you are amazing !
EDIT: update thanks to remarks.


text:
Q: Storing an arraylist for retrieval in Android I'm currently working on an Android application that is going to be somewhat like a student planner. My backend is all java and I am currently stuck because i am storing the objects that i create from my backend to arraylist. Being java, these objects dissapear as soon as the programs terminate. Whats the easiest way that i can store my java objects for retrieval the next time i boot my application? Any help is much appreciated! Im developing on 2.3 and eclipse(juno).

A: One of the data storage options listed in the Android developer tutorial will be the easiest thing to do. Which is the best fit will depend on how much data you're storing and how you need to access it. As the page says, the SharedPreferences class is best for a handful of items; for larger data sets, you could use Java serialization or some other way to write them to a file on the phone's storage; and if your data are large and/or you need structured access to them, an SQLite database is your best bet.

A: You can use Shared Preferences to store your data. The SharedPreferences lets you persist key-value pairs of primitive data types in you application. You can't store an entire ArrayList with a single key, but you can iterate over the array and systematically generate a key for each value in the list. I usually do something like this:
public class SomeActivity extends Activity {
    private ArrayList<Data> list; //We'll persist this array

    /* snip */

    //These strings can be anything - you just need something you can use to systematically generate distinct keys
    public static final String LIST_KEY = "SomeActivity_List";
    public static final String LIST_LENGTH_KEY = "SomeActivity_ListLength";

    /**
     * How this method works: It starts by getting a SharedPreferences object,
     * which offers an API for persisting data. It then systematically generates
     * Strings like "SomeActivity_List1", "SomeActivity_List2", "SomeActivity_List3",
     * and so on to use as keys fot the 1st, 2nd, 3rd, etc. elements in the list. Then
     * it Data.saveData(), a method defined below in the Data class, in order to give
     * each Data object in the ArrayList an opportunity to persist its primitive
     * members in the SharedPreferences.
     *
     * SomeActivity.restoreList() works similarly.
     */
    public void saveList() {
        SharedPreferences prefs = getPreferences(); //This method is part of the Activity class
        SharedPreferences.Editor editor = prefs.getEditor();

        //Save the length of the list so that when we restore it, we know how many
        //Data objects to recreate.
        editor.putInt(LIST_LENGTH_KEY, list.size());
        editor.commit();

        //This for loop is important - note how we concatenate i to each of the keys to give each element in list a distinct key
        for(int i = 0; i < list.size(); i++)
        {
            String identifier = LIST_KEY + Integer.toString(i); //generate distinct keys
            list.get(i).saveData(identifier, prefs);
        }
    }

    public void restoreList() {
        SharedPreferences prefs = getPreferences();

        int length = prefs.getInt(LIST_LENGTH_KEY);

        for(int i = 0; i < length; i++)
        {
            String identifier = LIST_KEY + Integer.toString(i); //re-generate distinct keys
            Data data = new Data();
            data.restoreData(identifier, prefs);
            list.addLast(data);
        }
    }

    public static class Data {
        private int i;
        private double j;
        private String s;

        public static final String I_KEY = "Data_I"
        public static final String J_KEY = "Data_J" //strings can really be whatever, as long as they're distinct.
        public static final String S_KEY = "Data_K"

        /**
         * How this method works: The SomeActivity.saveList() method generates a
         * unique String ("identifier") for each of the Data objects it contains.
         * This method uses that distinct string and makes some more distinct keys
         * to store each of Data's primitive members.
         *
         * restoreData() works similarly when it rebuilds Data objects
         */
        public saveData(String identifier, SharedPreferences prefs) {
            SharedPreferences.Editor editor = prefs.getEditor();
            editor.putInt(I_KEY + identifier, i);
            editor.putDouble(J_KEY + identifier, j);
            editor.putString(S_KEY + identifier, s);
            editor.commit();
        }

        public restoreData(String identifier, SharedPreferences prefs) {
            i = prefs.getInt(I_KEY + identifier);
            j = prefs.getDouble(J_KEY + identifier);
            s = prefs.getString(S_KEY + identifier);
        }
    }
}

This approach work recursively. If Data had an ArrayList as one of its fields, for example, it could systematically store all of the values in that list in SharedPreferences as well.
FYI: One of the implications of using SharedPreferences is that if the user uninstalls your app or clears the app data, the stored list will be deleted. Depending on the nature of your data, you may or may not want this behavior.


text:
Q: De-Broglie wavelength from two different reference frames If we were to measure the De-Broglie wavelength of a particle of mass $m$ and velocity $v$, in a given reference frame, it would be given as $$\lambda = h/p$$
(where $h$ is Planck's constant & $p$ is momentum)
Now if we were to measure the De-Broglie wavelength of the same particle from a reference frame moving with velocity $v$ the particle would seem stationary, so $p=0$ and its De-Broglie wavelength would be $$\lambda = h/0$$
So how exactly does a particle possess two different wavelengths when observed from two different reference frames?

A: The de Broglie frequency and wavelength of the "superluminar" plane phase wave accompaning a "subluminar" particle moving with speed $\:\upsilon\:$ are(1)
\begin{equation}
\nu \boldsymbol{=} \dfrac{E }{h} \boldsymbol{=} \dfrac{\sqrt{\left(m_{\mathrm{o}}c^{2}\right)^{2} \boldsymbol{+}\left(pc\right)^{2}}}{h} \boldsymbol{=}\dfrac{\gamma m_{\mathrm{o}}c^{2}}{h}
\tag{01}\label{01}
\end{equation}
\begin{equation}
\lambda  \boldsymbol{=} \dfrac{h }{p} \boldsymbol{=}\dfrac{h}{\gamma m_{\mathrm{o}}v}
\tag{02}\label{02}
\end{equation}
where $\:\gamma=\left(1\boldsymbol{-}\dfrac{\upsilon^2}{c^2}\right)^{\boldsymbol{-}1/2}\:$ and $\:m_0\:$ the rest mass.
The plane phase wave "superluminar" speed is
\begin{equation}
\mathrm w=\lambda\,\nu \boldsymbol{=} \dfrac{c^{2}}{\upsilon}
\tag{03}\label{03}
\end{equation}
In the rest frame  of the particle
\begin{equation}
\nu_{0} \boldsymbol{=} \dfrac{E_{0}}{h} \boldsymbol{=} \dfrac{m_{\mathrm{o}}c^{2}}{h}
\tag{04}\label{04}
\end{equation}
\begin{equation}
\lambda_{0}  \boldsymbol{=} \infty
\tag{05}\label{05}
\end{equation}
\begin{equation}
\mathrm w_{0}  \boldsymbol{=} \infty
\tag{06}\label{06}
\end{equation}
that is a uniform in space periodic in time vibration with frequency $\:\nu_{0}$.

EDIT :
responds to the OP's comment

I still don't know a lot of stuff in physics, the only thing I knew in your answer was the square root of the Lorentz gamma. Do you think you maybe dumb it down a little? – Kosh Rai

De Broglie hypothesis :

$^{\prime\prime}$The fundamental idea of [my 1924 thesis] was the following : The fact that, following Einstein's introduction of photons in light waves, one knew  that  light  contains  particles  which  are  concentrations of energy incorporated into the wave, suggests that all particles, like the electron, must be transported by a wave into which it is incorporated... My essential idea was to extend to all particles the coexistence of waves and particles discovered by Einstein in 1905 in the case of light and photons.$^{\prime\prime}$ $^{\prime\prime}$With every particle of matter with mass $m$ and velocity $\upsilon$ a real wave must be 'associated'$^{\prime\prime}$, related to the momentum by the equation:
  \begin{equation}
\lambda  \boldsymbol{=} \dfrac{h}{p}\boldsymbol{=}\dfrac{h}{\gamma m \upsilon}
\nonumber
\end{equation}
  where $\lambda$  is the wavelength, $h$ is the Planck constant, $p$ is the momentum, $m$ is the rest mass, $\upsilon$  is the velocity and $c$ is the speed of light in a vacuum.

Louis de Broglie hypothesis is based on the Special Relativity theory and the associated Lorentz transformations. Note that this picture of a particle with velocity $\upsilon$ and its associated plane phase wave with velocity $\mathrm w=c^2/\upsilon$ is Lorentz invariant, that is the same in any inertial system.

(1)
See my answer here : About de Broglie relations, what exactly is E? Its energy of what?.


text:
Q: What is a word for those times where you can't describe something well? I need a word that describes when you're trying to explain an idea to someone, but you just can't word it right. Like when the words are just on the tip of your tongue, but you simply don't know them, or they don't exist. I want the word to describe the feeling, or even the situation. The feeling is kind of like trying to describe the color blue to a blind person, but more about the speaker's incapability to communicate the idea, rather than the listener's incapability to understand.

A: If the idea is necessarily inexpressible, then it would be called ineffable:

*

*incapable of being expressed or described in words; inexpressible

Otherwise, the phenomenon of being unable to think of a particular word or phrase is actually known as tip-of-the-tongue.
Not sure what you'd call it if you can think of all the relevant terms, but can't seem to order them effectively, which may be what you're asking.


text:
Q: Automatic backup solution for Linux (maybe a GUI for rsync)? What I'm looking for is a backup solution that:

*

*is easy to setup (user friendly)

*does automatic and instant backups whenever a file is added/deleted/modified (I don't want multiple copies/versions, just a mirror image)

*works on Linux and Windows

I'm running Ubuntu (9.04 64 bit) and Windows (Vista Home 32 bit) dual booting.  I have a RAID setup via motherboard and formatted in Windows, and I also mount it when I run Ubuntu.  I have a backup plan for my RAID on Windows (via Memeo backup that came with my external WD) that automatically backs up to an external drive.  When I'm running in Ubuntu though, any changes I make to the RAID will not be backed up to that external because I don't have a Linux backup plan.  I'm looking for something that will allow me to backup the same RAID no matter which OS I boot into.
What is the best way to go about solving this?  Can I even do this since the path of the RAID is different between Linux and Windows (ie. Z:\Media on Windows and /media/Z on Ubuntu)?
If its rsync, what is the best GUI for it that will account for this?
I tried Crashplan but it doesn't do automatic backups, just scheduled ones, and it doesn't allow you to physically access the files I think it compresses them.

A: Personally, rsync really does very well without a UI.  That said:
A really good choice under ubuntu is Sbackup. It's well supported, free and simple to use - it handles both the backup & restore for you.  It's tabbed interface gives easy access to the most common features.  It's intended for desktop backup & restore.

Regarding rsync options:  Under Gnome there is GtkRsync.  If you use Kommander there is Krsync


text:
Q: How to use Underscore.js as View Engine for Express v3 There is a question on here answering for v2, but the v3 ExpressJS api is quite different, and uses a totally different layout system. Does anyone have any experience using Underscore.js (if needed with Consolidate.js) as the main view engine for an Express v3 app with the ability to use master layouts?
I've got it as the main view engine but no layouts work (it just prints out the single html file)

A: Express 3.x removes support for layout and partials. IF you need to do the same thing you used to do, you can always use "EJS" template engine which is basically the same used by underscore and compliment it wit express-partials plug in.


text:
Q: UDK error, how to examine crash dump I am working on a game in UDK, and sometimes the game crashes when restarting the level or trying to open a new one.
I cannot find the problem trough the log files, they are just displaying a critical error.
Now I am trying to fix it by examining the crash dump, but I do not have a clue how to do this. Does anyone have an idea how I can further investigate the problem? I tried some things that I found online and this is what I have so far.
*** ERROR: Symbol file could not be found.  Defaulted to export symbols for UDK.exe -
eax=00000000 ebx=39280070 ecx=0cdc0f10 edx=ffffffff esi=2a193f40 edi=296f96a0
eip=01c2caf3 esp=007cdf84 ebp=2c0132b0 iopl=0         nv up ei pl zr na pe nc
cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00010246
UDK!GetStackOwnerClass+0x10a73:
01c2caf3 8b10            mov     edx,dword ptr [eax]  ds:002b:00000000=????????
0:000> !sym noisy
noisy mode - symbol prompts on
0:000> lmvm ntdll
start    end        module name
77890000 77a10000   ntdll      (export symbols)       ntdll.dll
    Loaded symbol image file: ntdll.dll
    Mapped memory image file: C:\Windows\SysWOW64\ntdll.dll
    Image path: C:\Windows\SysWOW64\ntdll.dll
    Image name: ntdll.dll
    Timestamp:        Thu Aug 29 03:50:31 2013 (521EA8E7)
    CheckSum:         00140982
    ImageSize:        00180000
    File version:     6.1.7601.18247
    Product version:  6.1.7601.18247
    File flags:       0 (Mask 3F)
    File OS:          40004 NT Win32
    File type:        2.0 Dll
    File date:        00000000.00000000
    Translations:     0409.04b0
    CompanyName:      Microsoft Corporation
    ProductName:      Microsoft® Windows® Operating System
    InternalName:     ntdll.dll
    OriginalFilename: ntdll.dll
    ProductVersion:   6.1.7601.18247
    FileVersion:      6.1.7601.18247 (win7sp1_gdr.130828-1532)
    FileDescription:  NT Layer DLL
    LegalCopyright:   © Microsoft Corporation. All rights reserved.

A: The most basic analysis in WInDbg is done with
.symfix
.reload
!analyze -v

Since it crashes, there should be an exception somewhere. Try
.ecxr
.exr -1

Also the call stack is potentially interesting. Since this is about UDK (Unreal Engine Development Kit), I assume it's written in C++ and thus we need a native call stack
k


text:
Q: Access 2010: Embedding a form into a navigation form I have a form called ClientSearch which provides basic search on three fields into the Clients Table and displays results. This form is bound to the Clients table (Record Source is set to "Client" for the form). To search the Clients table, my code uses a DoCmd.ApplyFilter command in the event handler for the search button.
I then made a navigation form and dragged the ClientSearch form into one of its categories.
Now, when I click the search button, my DoCmd.ApplyFilter does not work anymore. I get a runtime error telling me my form is not bound to a particular table which is true. The navigation form is not bound to any tables and it can't be, since there will be multiple embedded forms on it for different tables and queries.
How do I address this problem? It seems that Access and VBA have no idea which table to use for the ApplyFilter query.

A: Usually the way that people go about searching is to create a query that contains the fields with the criteria related to another text field. for example criteria for [First Name] might be:
Like [Forms]![frm_RecordSearch]![txtFirst] & "*"

That will show all results if the text box is blank and allow for people to search based on partial matches.
From there all you would need to do is create a form based on the query and have the form with the search criteria call the display form. This will automatically sort it. If you want to avoid closing the form each time you search again you can also use Me.requery for example with two forms the search form would look like:
Private Sub cmdb_search_Click()
If CurrentProject.AllForms("frm_SearchResults").IsLoaded Then
Forms![frm_SearchResults].Form.Requery
Else
DoCmd.OpenForm "frm_SearchResults"
End If
End Sub

As well you can use a similar technique to sort using sub forms though where the subform is the results and the text boxes/combo boxes etc. are contained on the main form and have an after update requery or search button etc that triggers the search. The downside of this method is the form is not able to be continuous as far as I know, but you can still get a good result this way.
I hope that helps. Let me know if anything is unclear!


text:
Q: Fiducial volume in collider/detector physics I'm trying to make some sense of ATLAS measurements for a personal project to learn how to use Pythia, and part of my work requires me to recreate the distribution for Z boson decay. I encountered the term 'fiducial volume', and I am wondering what it is, because I couldn't find an answer online.
So, what is fiducial volume in the context of particle phenomenology? Is it the region of phase/energy space that is of interest?
Or does it have to do with hypothesis testing?

A: In some detector experiments,

*

*The response at the periphery of the detector is poorly understood.

*The majority of background events interact in the periphery of the detector. The periphery of the detector is the final shielding.

*Some parts of the detector may be broken.

In such cases, results from such parts of the detector are ignored. The results are drawn entirely from the fiducial volume (the reliable, central area of the detector) in which neither 1. nor 2. apply.
Occasionally, however, fiducial volume might refer, metaphorically, to an interesting volume of phase space of objects produced in a collision, in which 1. and 2. don't apply.

A: This presentation (NB: PDF) has a "jargon" page that states,

*

*Fiducial (Webster's):

*

*Taken as a standard of reference

*Founded on faith or trust

*Having a nature to be trusted

*

*Fiducial Volume (Particle Physics):

*The volume used to make physics measurements

*The volume where the detector is assumed to be well understood

With the following diagram (slightly modified for formatting purposes),

So basically the fiducial volume is the volume of the observatory at which a specified number (typically 90%) of events are to be accepted, and will be smaller than the total volume. For the particular case of Super-Kamiokande, it has a total volume of 50 kton and a fiducial volume of 22 kton.

A: ATLAS has no experiment-wide definition of "fiducial", it basically means sensitive to signal.
The definition is confusing because, unlike most experiments, ATLAS (and CMS, D0, CDF, etc) doesn't just define the physical area where the experiment is sensitive, they also define collision properties. This means the definition of fiducial isn't limited to the detector volume. Instead it's roughly defined as the parameter space of events where you can expect to measure your signal.
Unfortunately this may depend on what you're trying to measure. Other "fiducial cuts" may include:

*

*$p_\mathrm{t}$ of objects (jets, leptons, etc)

*$\eta$ of objects

*Various relationships among the objects in the detector (i.e. missing transverse energy, etc)

Further confusing matters, some groups within the experiment choose to omit the term "fiducial" entirely; the financial volume may just be referred to as the "signal region". So while in the most general sense it means the place where your signal is strong, the term should never appear without a more precise definition.


text:
Q: Dynamically getting info path form fields to send workflow task: SharePoint Designer 2007 I have a custom workflow that uses the "Collect data from a user" action, i have it set up so as task is either approved/rejected. In the "this user" selection i want to get the email field from my sharepoint library which will be populated when the form is submitted and send
the form to corresponding email using this workflow. I have tried using "Workflow" Look up and while connected to the sharepoint site, i can access the form library however i dont know how to properly use the workflow look up wizard: does anyone know how the "Look up details" and "Find the list item" options relate? how to use them to get infopath email field?

A: The first thing I would do would be to make sure you are publishing the email field to the form library. From there you should just be able to grab that field and put it right into the "This user" Section by selecting "Current item->email".


text:
Q: How to populate the modified_by with the user_id of who made the update to the record using laravel 5.1? When using Laravel 5.1, I am trying to create an Observer that will automatically update the following 3 columns

*

*created_by: populate when the record in created "never update this again"

*modified_by: populate a new value every time a record is modified

*purged_by: populate a value when a record is soft deleted.

I understand that Eloquent will automatically update the date time stamp (created_by, updated_at, removed_at) but I need to update the user_id that made the change.
I was advised to use Observer and a trait to handle this. Here is what I have done
1) created an observer class called "ModelSignature" located in app\Observers\ModelSignature.php and this is it's content
<?php

namespace App\Observers;

class ModelSignature {

    protected $userID;

    public function __construct(){
        $this->userID =  Auth::id();
    }

    public function updating($model)
    {
        $model->modified_by = $this->userID;
    }

    public function creating($model)
    {
        $model->created_by = $this->userID;
    }

    public function removing($model)
    {
        $model->purged_by = $this->userID;
    }

}

I then created a new Trait called "RecordSignature" located in app\Traits\RecordSignature.php and contains the following code
<?php

namespace App\Traits;

use app\Observers\ModelSignature;

trait RecordSignature
{

    public static function bootObservantTrait()
    {
        static::observe(new ModelSignature() );
    }
}

Finally, in my "Account" model located on "app\Models\Account.php" I use it like this
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Models\industry;
use App\Traits\RecordSignature;
use App\Traits\TrimScalarValues;

class Account extends Model
{
    use RecordSignature, TrimScalarValues;
    /**
     * The database table used by the model.
     *
     * @var string
    */
    protected $table = 'accounts';

    protected $primaryKey = 'account_id';

    const CREATED_AT = 'created_on';

    const UPDATED_AT = 'modified_on';

    const REMOVED_AT = 'purged_on';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
    */
    protected $fillable = ['client_id','account_name', 'company_code', 'legal_name', 'created_by','modified_by','instrucations'];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
    */
    //protected $hidden = ['account_id', 'remember_token'];

    protected $guarded = ['account_id'];

    /**
     * Get the industry record associated with the account.
    */
    public function industry()
    {
        return $this->hasOne(industry, industry::primaryKey);
    }

    public function pk(){

        return $this->primaryKey;
    }

}

The problem is that the methods updating(), removing() and creating() are not populating the userId as expected. It seems that the fields are being ignored or the methods are not being fired!
What am I doing wrong here?

A: You should be able to get rid of your ModelSignatures Class and change your trait to something like:
trait RecordSignature
{
    protected static function boot()
    {
        parent::boot();

        static::updating(function ($model) {

            $model->modified_by = \Auth::User()->id;
        });

        static::creating(function ($model) {

            $model->created_by = \Auth::User()->id;
        });
        //etc

    }

}

Update:
There are many packages nowadays that will handle this sort of thing for you. One that I currently use quite a bit is Laravel Auditing which will not only keep track of who performed a task but also any changes to row as well.

A: I suggest you to use venturecraft revisionable package with this upgrade https://github.com/fico7489/laravel-revisionable-upgrade
Everything will work out of the box, you just need to use 2 traits, you can do much more that get info who edited model, you can get info who edited particular column, even particular value and much more...

A: step 1: make trait
namespace App\Traits;

use App\Observer\ModelObserver;

trait ObservantTrait
{

    public static function bootObservantTrait()
    {
        static::observe(ModelObserver::class);
    }

}

step 2: make observer
<?php

namespace App\Observer;

use Illuminate\Auth\AuthManager;
use Illuminate\Contracts\Config\Repository;
use Request;

class ModelObserver
{

    public $userID;
    protected $auth;
    protected $login_user;
    protected $ip;
    protected $user_agent;

    public function __construct(AuthManager $auth, Repository $config)
    {
        $this->auth = $auth;
        $this->login_user = $auth->guard($this->auth->getDefaultDriver())->user();
        if (isset($this->login_user->id)) {
            $this->userID = $this->login_user->id;
            $this->ip = Request::ip();
            $this->user_agent = Request::header('user-agent');
        }
    }

    public function updating($model)
    {

        $model->updated_by = $this->userID;
        $model->ip = Request::ip();
        $model->user_agent = Request::header('user-agent');

    }

    public function creating($model)
    {

        $model->created_by = $this->userID;
        $model->ip = Request::ip();
        $model->user_agent = Request::header('user-agent');

    }

    public function deleted($model)
    {

        $model->deleted_by = $this->userID;
        $model->ip = Request::ip();
        $model->user_agent = Request::header('user-agent');
        $model->save();

    }

}

step 3: user trait in model
use ObservantTrait;


text:
Q: Which one is correct here- attacks or attackers? A blog's title is following:

Pak-based cyber attacks use phishing to target Indian defence sites

IMO, if we remove 'use phishing' then 'attacks' is okay in this title because an attack cannot 'use' anything including phishing. In a way, 'attackers' looks more proper for this title.
Is my opinion right? I know the question is quite simple, but I am not sure about 'attacks' is written here in an idiomatic manner.

A: Good question.
In such special structure, the subject is a noun often inanimate. And, it's okay. Here, the subject is 'attacks' that use phishing to target Indian defense sites.
If you are confused, I'll get you another example where you'll think that 'citizens' should be the choice!

The city witnesses huge traffic on Mondays

But, here, 'city' is the subject, and it can witness!


text:
Q: Ng-file-upload progress bar not working with offlinejs I'm use ng-file-upload for fileuploading in my home, and the good news is that it's working fine and I'm able to upload files.
The issue is that the progress bar only shows when i disable the offlinejs in index.html. It seems like offlineJS i preventing the progress callback from the post call.
Here is the error messege I get:
Error: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': 'function (xhr) {
          if (!xhr || !(xhr instanceof XMLHttpRequest)) return;
          config.__XHR = xhr;
          if (config.xhrFn) config.xhrFn(xhr);
          xhr.upload.addEventListener('progress', function (e) {
            e.config = config;
            notifyProgress(getNotifyEvent(e));
          }, false);
          //fix for firefox not firing upload progress end, also IE8-9
          xhr.upload.addEventListener('load', function (e) {
            if (e.lengthComputable) {
              e.config = config;
              notifyProgress(getNotifyEvent(e));
            }
          }, false);
        }' is not a valid HTTP header field value.
    at Error (native)
    at XMLHttpRequest.f.setRequestHeader (http://localhost:3000/lib/js/offline/offline.min.js:2:3272)

A: The issue was fixed in the latest version of ng-file-upload!


text:
Q: Zend Translate - Locale not working I started working on a multilangual Zend Framework application and I've been stucked on something I hate:
The locale is not working like expected.

There's the .ini config:
; Locale
resources.locale.default = "fr"
resources.locale.force = false
resources.locale.cache = "locale"
resources.locale.registry_key = "Zend_Locale"

; Translate
resources.translate.adapter = Ini
resources.translate.content = APPLICATION_PATH "/../data/locales"
resources.translate.scan = Zend_Translate::LOCALE_DIRECTORY
resources.translate.options.tag = "Zend_Translate"
resources.translate.options.logUntranslated = true
resources.translate.options.disableNotices = false
resources.translate.options.logMessage = "Untranslated message within '%locale%': %message%"
resources.translate.options.logPriority = 5
resources.translate.options.registry_key = "Zend_Translate"
resources.translate.cache = "languages"
resources.translate.locale = "auto"

My filename are:
/locales/en.ini
/locales/fr.ini

When I do a simple $this->translate('COPYRIGHT');, it always return the french translation. Even if my computer is in english. I tried adding force = true to the locale and changing it to en_US but without success.


text:
Q: Xcode 9 Interface Builder: How to make an Image View fill the window? I'm working on a MacOS app, and I have an Image View in Interface Builder which is the child of a Window. I would like the image to be centered in the window, and resized so it's big enough to completely fill the window.
I have tried setting a constraint on the size of the Image View from the constraints menu at the bottom. This constrained the window the size of the image - what I want is the opposite. I would like to not have any constraints on the size of the window.
I have seen in similar questions people have been informed to set the "mode" to "aspect fill". However there is no "mode" dropdown when I have my Image View selected.


text:
Q: Google maps api search returns unexpected results Using the example code at: https://developers.google.com/maps/documentation/javascript/examples/places-searchbox
I find that when I type: DePaul University
and then choose the third one: DePaul University, North Kenmore Avenue, Chicago, IL, United States
it actually returns me a place named "The Theater School at DePaul University" where I would prefer getting just "DePaul University" which was what was bolded in the textbox.
Also when I type: Herzing University
and then choose: Herzing University Madison, Madison, WI, United States
It returns me many places... many of them hotels around the university. (???)

A: Use the Places-Autocomplete instead


text:
Q: Where to put the code for a Google Adwords campaing on Magento 1.9.1? Magento 1.9.1
Porto theme

We are running an Adwords campaing and we were given the following code to place into the Magento shopping cart in order to track how successful the campaign is:
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-118694738-1"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'UA-113694994-1');
</script>

I've tried putting this in the CMS home page,

*

*In the "Porto - Settings Panel" under Customization Settings --> Custom Style

*Under GENERAL --) DESIGN --)  HTML HEAD --) Miscellaneous Scripts but it does not seem to work.
Where is the best place to place this code within Magento?

A: Search for checkout/cart.phtml file (if I've understood your requirements right it should be placed only in cart page) in your app/design/frontend folder
You'll probably find more than one result, due to Magento theme fallback system https://www.classyllama.com/blog/depth-look-magento-theme-fallback

app/design/frontend/base/default/template/checkout/cart.phtml
app/design/frontend/XXX/XXX/template/checkout/cart.phtml
etc...

Locate which one is being rendered in your project, and place that Analytics JS code there


text:
Q: How to align yticklabels when combining a barplot with heatmap I have similar problems as this question; I am trying to combine three plots in Seaborn, but the labels on my y-axis are not aligned with the bars.
My code (now a working copy-paste example):
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm

### Generate example data
np.random.seed(123)
year = [2018, 2019, 2020, 2021]
task = [x + 2 for x in range(18)]
student = [x for x in range(200)]
amount = [x + 10 for x in range(90)]
violation = [letter for letter in "thisisjustsampletextforlabels"] # one letter labels

df_example = pd.DataFrame({

    # some ways to create random data
    'year':np.random.choice(year,500),
    'task':np.random.choice(task,500),
    'violation':np.random.choice(violation, 500),
    'amount':np.random.choice(amount, 500),
    'student':np.random.choice(student, 500)
})

### My code
temp = df_example.groupby(["violation"])["amount"].sum().sort_values(ascending = False).reset_index()
total_violations = temp["amount"].sum()
sns.set(font_scale = 1.2)

f, axs = plt.subplots(1,3,
                      figsize=(5,5),
                      sharey="row",
                      gridspec_kw=dict(width_ratios=[3,1.5,5]))

# Plot frequency
df1 = df_example.groupby(["year","violation"])["amount"].sum().sort_values(ascending = False).reset_index()
frequency = sns.barplot(data = df1, y = "violation", x = "amount", log = True, ax=axs[0])

# Plot percent
df2 = df_example.groupby(["violation"])["amount"].sum().sort_values(ascending = False).reset_index()
total_violations = df2["amount"].sum()
percent = sns.barplot(x='amount', y='violation', estimator=lambda x: sum(x) / total_violations * 100, data=df2, ax=axs[1])

# Pivot table and plot heatmap
df_heatmap = df_example.groupby(["violation", "task"])["amount"].sum().sort_values(ascending = False).reset_index()
df_heatmap_pivot = df_heatmap.pivot("violation", "task", "amount")
df_heatmap_pivot = df_heatmap_pivot.reindex(index=df_heatmap["violation"].unique())
heatmap = sns.heatmap(df_heatmap_pivot, fmt = "d", cmap="Greys", norm=LogNorm(), ax=axs[2])
plt.subplots_adjust(top=1)

axs[2].set_facecolor('xkcd:white')
axs[2].set(ylabel="",xlabel="Task")

axs[0].set_xlabel('Total amount of violations per year')
axs[1].set_xlabel('Percent (%)')

axs[1].set_ylabel('')
axs[0].set_ylabel('Violation')

The result can be seen here:

The y-labels are aligned according to my last plot, the heatmap. However, the bars in the bar plots are clipping at the top, and are not aligned to the labels. I just have to nudge the bars in the barplot -- but how? I've been looking through the documentation, but I feel quite clueless as of now.

A: *

*See here that none of the y-axis ticklabels are aligned because multiple dataframes are used for plotting. It will be better to create a single dataframe, violations, with the aggregated data to be plotted. Start with the sum of amounts by violation, and then add a new percent column. This will insure the two bar plots have the same y-axis.

*Instead of using .groupby and then .pivot, to create df_heatmap_pivot, use .pivot_table, and then reindex using violations.violation.

*Tested in python 3.10, pandas 1.4.3, matplotlib 3.5.1, seaborn 0.11.2
DataFrames and Imports
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm

# Generate example data
year = [2018, 2019, 2020, 2021]
task = [x + 2 for x in range(18)]
student = [x for x in range(200)]
amount = [x + 10 for x in range(90)]
violation = list("thisisjustsampletextforlabels")  # one letter labels

np.random.seed(123)
df_example = pd.DataFrame({name: np.random.choice(group, 500) for name, group in
                           zip(['year', 'task', 'violation', 'amount', 'student'],
                               [year, task, violation, amount, student])})

# organize all of the data
# violations frequency
violations = df_example.groupby(["violation"])["amount"].sum().sort_values(ascending=False).reset_index()
total_violations = violations["amount"].sum()

# add percent
violations['percent'] = violations.amount.div(total_violations).mul(100).round(2)

# Use .pivot_table to create the pivot table
df_heatmap_pivot = df_example.pivot_table(index='violation', columns='task', values='amount', aggfunc='sum')
# Set the index to match the plot order of the 'violation' column
df_heatmap_pivot = df_heatmap_pivot.reindex(index=violations.violation)

Plotting

*

*Using sharey='row' is causing the alignment problem. Use sharey=False, and remove the yticklabels from axs[1] and axs[2], with axs[1 or 2].set_yticks([]).

*See How to add value labels on a bar chart for additional details and examples using .bar_label.

# set seaborn plot format
sns.set(font_scale=1.2)

# create the figure and set sharey=False
f, axs = plt.subplots(1, 3, figsize=(12, 12), sharey=False, gridspec_kw=dict(width_ratios=[3,1.5,5]))

# Plot frequency
sns.barplot(data=violations, x="amount", y="violation", log=True, ax=axs[0])

# Plot percent
sns.barplot(data=violations, x='percent', y='violation', ax=axs[1])

# add the bar labels
axs[1].bar_label(axs[1].containers[0], fmt='%.2f%%', label_type='edge', padding=3)
# add extra space for the annotation
axs[1].margins(x=1.3)

# plot the heatmap
heatmap = sns.heatmap(df_heatmap_pivot, fmt = "d", cmap="Greys", norm=LogNorm(), ax=axs[2])

# additional formatting
axs[2].set_facecolor('xkcd:white')
axs[2].set(ylabel="", xlabel="Task")

axs[0].set_xlabel('Total amount of violations per year')
axs[1].set_xlabel('Percent (%)')

axs[1].set_ylabel('')
axs[0].set_ylabel('Violation')

# remove yticks / labels
axs[1].set_yticks([])
_ = axs[2].set_yticks([])

*

*Comment out the last two lines to verify the yticklabels are aligned for each axs.

DataFrame Views
df_example.head()
   year  task violation  amount  student
0  2020     2         i      84       59
1  2019     2         u      12      182
2  2020     5         s      20        9
3  2020    11         u      56      163
4  2018    17         t      59      125

violations
   violation  amount  percent
0          s    4869    17.86
1          l    3103    11.38
2          t    3044    11.17
3          e    2634     9.66
4          a    2177     7.99
5          i    2099     7.70
6          h    1275     4.68
7          f    1232     4.52
8          b    1191     4.37
9          m    1155     4.24
10         o    1075     3.94
11         p     763     2.80
12         r     762     2.80
13         j     707     2.59
14         u     595     2.18
15         x     578     2.12

df_heatmap_pivot
task          2      3      4      5      6      7      8      9      10     11     12     13     14     15     16     17     18     19
violation
s           62.0   36.0  263.0  273.0  191.0  250.0  556.0  239.0  230.0  188.0  185.0  516.0  249.0  331.0  212.0  219.0  458.0  411.0
l           83.0  245.0  264.0  451.0  155.0  314.0   98.0  125.0  310.0  117.0   21.0   99.0   98.0   50.0   40.0  268.0  192.0  173.0
t          212.0  255.0   45.0  141.0   74.0  135.0   52.0  202.0  107.0  128.0  158.0    NaN  261.0  137.0  339.0  207.0  362.0  229.0
e          215.0  315.0    NaN  116.0  213.0  165.0  130.0  194.0   56.0  355.0   75.0    NaN  118.0  189.0  160.0  177.0   79.0   77.0
a          135.0    NaN  165.0  156.0  204.0  115.0   77.0   65.0   80.0  143.0   83.0  146.0   21.0   29.0  285.0   72.0  116.0  285.0
i          209.0    NaN   20.0  187.0   83.0  136.0   24.0  132.0  257.0   56.0  201.0   52.0  136.0  226.0  104.0  145.0   91.0   40.0
h           27.0    NaN  255.0    NaN   99.0    NaN   71.0   53.0  100.0   89.0    NaN  106.0    NaN  170.0   86.0   79.0  140.0    NaN
f           75.0   23.0   99.0    NaN   26.0  103.0    NaN  185.0   99.0  145.0    NaN   63.0   64.0   29.0  114.0  141.0   38.0   28.0
b           44.0   70.0   56.0   12.0   55.0   14.0  158.0  130.0    NaN   11.0   21.0    NaN   52.0  137.0  162.0    NaN  231.0   38.0
m           86.0    NaN    NaN  147.0   74.0  131.0   49.0  180.0   94.0   16.0    NaN   88.0    NaN    NaN    NaN   51.0  161.0   78.0
o          109.0    NaN   51.0    NaN    NaN    NaN   20.0  139.0  149.0    NaN  101.0   60.0    NaN  143.0   39.0   73.0   10.0  181.0
p           16.0    NaN  197.0   50.0   87.0    NaN   88.0    NaN   11.0  162.0    NaN   14.0    NaN   78.0   45.0    NaN    NaN   15.0
r            NaN   85.0   73.0   40.0    NaN    NaN   68.0   77.0    NaN   26.0  122.0  105.0    NaN   98.0    NaN    NaN    NaN   68.0
j            NaN   70.0    NaN    NaN   73.0   76.0    NaN  150.0    NaN    NaN    NaN   81.0    NaN   97.0   97.0   63.0    NaN    NaN
u          174.0   45.0    NaN    NaN   32.0    NaN    NaN   86.0   30.0   56.0   13.0    NaN   24.0    NaN    NaN   69.0   54.0   12.0
x           69.0   29.0    NaN  106.0    NaN   43.0    NaN    NaN    NaN   97.0   56.0   29.0  149.0    NaN    NaN    NaN    NaN    NaN


text:
Q: Project management: Implementing custom errors in VS compilation process AGAIN: If you're voting -1, please leave a comment explaining why. This post isn't about whether or not you approve if this approach, but how to go about it.
Like many architects, I've developed coding standards through years of experience to which I expect my developers to adhere.
This is especially a problem with the crowd that believes that three or four years of experience makes you a senior-level developer.Approaching this as a training and code review issue has generated limited success.
So, I was thinking that it would be great to be able to add custom compile-time errors to the build process to more strictly enforce our in-house best practices and coding standards.
For instance, we use stored procedures for ALL database access, which provides procedure-level security, db encapsulation (table structure is hidden from the app), and other benefits. (Note: I am not interested in starting a debate about this.) Some developers prefer inline SQL or parametrized queries, and that's fine - on their own time and own projects.
I'd like a way to add a compilation check that finds, say, anything that looks like
string sql = "insert into some_table (col1,col2) values (@col1, @col2);"

and generates an error or, in certain circumstances, a warning, with a message like
Inline SQL and parametrized queries are not permitted.
Or, if they use the var keyword
var x = new MyClass();

Variable definitions must be explicitly typed.
Do Visual Studio and MSBuild provide a way to add this functionality? I'm thinking that I could use a regular expression to find unacceptable code and generate the correct error, but I'm not sure what, from a performance standpoint, is the best way to to integrate this into the build process.
We could add a pre- or post-build step to run a custom EXE, but how can I return line- and file-specifc errors?  Also, I'd like this to run after compilation of each file, rather than post-link.
Is a regex the best way to perform this type of pattern matching, or should I go crazy and run the code through a C# parser, which would allow node-level validation via the parse tree?
I'd appreciate suggestions and tales of prior experience.
Comments
Several respondents have pointed out that it's possible to restrict the ability of a user to run anything but a stored proc through db permissions. However, we're in the process of porting a 350k+ line application from ASP 3.0 to ASP.NET MVC, and the existing code base relies pretty heavily on concatenated SQL, whereas the new stuff all uses Enterprise Library. I guess I could add a separate web user account for the .NET code with more restrictive permissions.

A: What about writing a plugin for Resharper? Here is a tutorial to start with: Writing plug-ins for ReSharper: Part 1 of Undefined

A: For coding standards I would look at writing custom rules for FxCop or StyleCop.  I don't think Regex would be a suitable tool for the job.
For the specific case of requiring Stored Procedures - if you ensure the application doesn't have permission to do anything else on the production database, everyone will soon fall in line.

A: Implicit typing (var x = ....) is a feature that can be turned off on project level in visual studio.
The other one is trickier. Have you had a look at FxCop, which is the tool for enforcing code standards.

A: The requirement that only stored procedures can be used should be managed through database permissions. The rule against using var seems fairly arbitrary to me and I can't think of a way to enforce it. Do you have any more examples of your best practices?


text:
Q: Emacs autocomplete-mode extension for ESS and R Is there an R-extension to Emacs autocomplete-mode that can be used with ESS?
If the extension doesn't exist I'd also appreciate any hints for writing one!

A: auto-complete-acr is auto-complete sources.
it is more useful than ac-R.
add to .emacs below.
(require 'auto-complete)
(require 'auto-complete-acr)

A: There is an ac-source for R here. I recall struggling with it and finally wrote my own which at that time was much faster, but buggy since I didn't manage to make prefix regexp work properly.
EDIT: the newest ESS (only svn currently) has out-of-the-box integration with auto-complete. I have added the instructions to the wiki.


text:
Q: New iPhone transfer did not bring AirTag info from old phone I just got a new iPhone SE 3rd generation to replace my iPhone SE 2nd generation. I just when through the automated migration process of transferring over all info while holding the phones close. Seemed to have worked well.
But I was surprised to find that the Items tab of the Find My app knows none of my AirTags.
 Is there a way to bring over those AirTag registrations? Or must I re-register AirTags with the new phone from scratch?
If re-registering is required, is the proper route that is described in Apple Support page, How to reset your AirTag, where you remove, replace, and press the battery inside the AirTag five times?

A: Wait
Just wait. It takes a long while for the iPhone to retrieve all information from iCloud. Makes sure you leave your iPhone connected to the internet.
Some items such as the AirTag registrations may take like an hour to appear.

A: I had this same problem with a new iPhone 14. The attached AirTags were not showing up in Find My. I was about to re-register all the tags again, but then I tried a hard-reset of the phone. (I hadn't rebooted it since I had set it up, and transferred the data from my old iPhone). After the reset, all the AirTags were showing again in Find My. Now I have to go and return all the AirTags to their hiding spots.