text:
Q: Given count data with many zero observations, what is a reasonable amount of zero observations in the data? I have sales data which records at what time (by second) and how many were sold. Therefore, the data is count data with around 90-150 sales during a 3-day period. If I agggregated it to the 10 minute interval, I will have around 75% zero observations because for example 100/(24*3*6) = 0.2314815. But I think this is still leads to too high a zeros/total ratio even when applying the data to zero-inflated Poisson or similar types of models. What is a reasonable amount of zero observations contained in the dataset to apply zero-inflated Poisson like models? According to the literature or examples elsewhere, I think 40% zero observations is acceptable. But I don't know if 50% okay.

A: I am not sure there are any hard and fast rules about an acceptable number of zeros.  Particularly when working with a zero inflated model.  Zero inflated models have two parts, one that predicts the probability of $y > 0$, that is
$$
P(y_{i} > 0 | x_{i}) = p_{i} = \frac{1}{1 + e^{-Xb_{i}}}
$$
This is typically done with a logistic model although probit is also not uncommon.  Note that this is a conditional probability, conditional on some vector $x$ which in the simplest case is a scalar, $1$, but could contain information that predicts whether the outcome, $y_i$ is a zero or not.  The more accurately you can predict whether an observation will be zero or not, the better the adjustment to your count model.  This adjustment is evident in the log likelihood function for the zero-inflated poisson:
$$
\mathcal{L} = \sum_{i=1}^{n}\left\{ \begin{array}{rl} ln(p_{i} + (1 - p_{i})e^{(-\mu_{i})}) &\mbox{if $y_{i} = 0$} \\ y_{i}ln(\mu_{i}) + ln(1 - p_{i}) - \mu_{i} - ln(y_{i}!) &\mbox{if $y_{i} > 0$} \end{array} \right.
$$
where $\mu_i = e^{x_{i}^{'}\beta}$, the expected count given your model (I assume the canonical log link).  In particular, consider the behavior as $p_i$ goes to the extremes: 1 or 0.  For $y_i > 0$ the formula converges to:
$$
\mathcal{L} = y_{i}ln(\mu_{i}) - \mu_{i} - ln(y_{i}!)
$$
More pragmatically, one concern would be do you have sufficient data that are not zero?  Estimates will be instable given insufficient data.  For example, 250 observations may be great, but if 240 are zeros, even if you can perfectly predict 0/>0, you still only have 10 observations about the actual count distribution.  In addition, one thing you could check is the distribution of residuals and the residuals versus fitted values.  Particularly, if you are concerned about the number of zeros being an issue, check the residuals and fit of zero values.
If your model is not fitting the zeros or the count data well, you may want to consider some other form of model.  One common alternative to the zero-inflated poisson is the zero inflated negative binomial.  The primary difference is an over dispersion parameter (although the log likelihood function is rather more complex):
$$
\mathcal{L} = \sum_{i=1}^{n} \left\{ \begin{array}{rl} ln(p_{i}) + (1 - p_i)\left(\frac{1}{1 + \alpha\mu_{i}}\right)^{\frac{1}{\alpha}} &\mbox{if $y_{i} = 0$} \\ ln(p_{i}) + ln\Gamma\left(\frac{1}{\alpha} + y_i\right) - ln\Gamma(y_i + 1) - ln\Gamma\left(\frac{1}{\alpha}\right) + \left(\frac{1}{\alpha}\right)ln\left(\frac{1}{1 + \alpha\mu_{i}}\right) + y_iln\left(1 - \frac{1}{1 + \alpha\mu_{i}}\right) &\mbox{if $y_{i} > 0$} \end{array} \right.
$$
You could also explore mixture models that assume observed data comes from an underlying mixture of distributions.
Here are some pages that may be helpful either for fitting models, talking about them, or graphing. For full transparency, I was the primary author of those pages.  I am sure there are other good resources, but I linked those because I know them off the top of my head.
Zero-inflated poisson
Zero-inflated negative binomial
Zero-truncated poisson this more for different graphing approaches than actually as a model suggestion, although you could try a zero-truncated model on just non zero observations (i.e., exclude all zeros and see how that compares with the ZIP).


text:
Q: DVI+HDMI out, at startup only HDMI is available I have my computer next to my hdtv. The main screen is connected via DVI while the tv is connected via HDMI.
If I start the computer without the HDMI plugged in, everything is ok: I see the login screen and sound is output through analog out.
But if the HDMI is plugged in before I start the computer, only the tv gets an image (the login screen), the main screen is black or at some times purple, but even after login the main screen is black. Also sound is still output through analog out.
Not sure whether it's a hw issue, or an Ubuntu issue, or a combined hardware/Ubuntu compatibility issue (Sandy Bridge).
This is my setup:

*

*Ubuntu 11.10 Oneiric Ocelot (64bit)

*ASUS P8H67-M LE

*Intel Core i3-2100

I don't have any custom video settings, my main screen is recognized properly when HDMI is not plugged in at startup.
Cheers.

A: This was a kernel issue for Sandy/Ivy Bridge that is now fixed in 12.04 (among other stuff fixed for Sandy/Ivy Bridge). I just so happen to have an Sandy Bridge and have the same Black problem.
This also happens with Nvidia card using HDMI but for them the solution was to upgrade to the latest Nvidia PPA Driver. In the case of the integrated video we need to wait for 12.04 to come out.
My setup is:
Ubuntu 11.10 (32 Bit)
Intel DZ68DP
Intel Core i7 2600

redpajama_set_name: RedPajamaStackExchange


text:
Q: simple int to hex conversion not working I have a very simple code where I get a value from numeric updown which I have then to convert to hex. (for numericupdown Hexadecimal property is set true)
I select FF from nud located in winForm. then in code
string str = nudID.Value.ToString("X");

But this is not working and I am getting format exception

A: NumericUpDown value isn't Int type, it's Decimal. Maybe here is the problem?

A: NumericUpDown.Value returns Decimal. Decimal.ToString(string) does not support "X":

The format parameter can be any valid standard numeric format specifier except for D, R, and X

Adapting some code from this solution, try this if you are on .NET 4.0 or later:
string str = new System.Numerics.BigInteger(nudID.Value).ToString("X");

A: Try this
string str = nudID.Value.ToString("X2");

A: this should work:
string str = ((int)nudID.Value).ToString("X");

You need to parse the decimal value to int. You can make it a bit safer by using TryParse if you want to.


text:
Q: Unable to resolve dependency tree, I no longer can install packages with node package manager I'm developing a react native application. Throughout the project I have used Node package manager to install the packages. But I ran into this dependency problem first time when I try to install react-native-styled-components with npm, so I installed it with yarn.
Now I can't install any package with node package manager, I run into this unable to resolve dependency tree error.
PS C:\Users\94774\OneDrive\React Projects\Native Projects\Android\socialmediaapp> npm install react@latest react-native@latest
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: socialmediaapp@0.0.1
npm ERR! Found: react@17.0.2
npm ERR! node_modules/react
npm ERR!   react@"17.0.2" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react@"17.0.1" from react-native@0.64.1
npm ERR! node_modules/react-native
npm ERR!   react-native@"0.64.1" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See C:\Users\94774\AppData\Local\npm-cache\eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\94774\AppData\Local\npm-cache\_logs\2021-05-06T12_12_44_173Z-debug.log
PS C:\Users\94774\OneDrive\React Projects\Native Projects\Android\socialmediaapp> npm install --save @react-native-firebase/app
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: socialmediaapp@0.0.1
npm ERR! Found: react@17.0.1
npm ERR! node_modules/react
npm ERR!   react@"17.0.1" from the root project
npm ERR!   peer react@">= 16.8.0" from styled-components@5.3.0
npm ERR!   node_modules/styled-components
npm ERR!     styled-components@"^5.3.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react@"17.0.2" from react-dom@17.0.2
npm ERR! node_modules/react-dom
npm ERR!   peer react-dom@">= 16.8.0" from styled-components@5.3.0
npm ERR!   node_modules/styled-components
npm ERR!     styled-components@"^5.3.0" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See C:\Users\94774\AppData\Local\npm-cache\eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\94774\AppData\Local\npm-cache\_logs\2021-05-06T12_41_01_675Z-debug.log

A: npm install react-native-styled-components --legacy-peer-deps


text:
Q: Show results in popup This code is working fine to show results on the page itself but I want to show the results in a popup.
We have linked the code to a database and it is retrieving the expected result, but how can I use jQuery to display division in a popup or dialogue box? Also it should be responsive.
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>PHP, jQuery search demo</title><link rel="stylesheet" type="text/css" href="my.css">

<form method="post" action="do_search.php"><input type="text" name="search" id="search_box" class='search_box'/><input type="submit" value="Search" class="search_button" />
</form>

Search results :

A: Using jQuery Dialogue you can accomplish exactly what you want.
With jQuery Dialogue you can

*

*Animate your dialogue box to give it a nice appearance

*You can use it to simply display a message

*You can use it to display a form such as an insert form or "Contact Us" form

*You can use it as a confirmation box

Easy to use and style.
Read about it here


text:
Q: display candidate information to user only on request in codeigniter i have candidate details form in my application..so when vendor posting the candidate details..user will got the candidate details through mail..after click on mail they can see candidate details..
so what i want to do is when vendor click on submit i need to give popup like "you want to show contact info or not" if they click on yes..user got candidate details with contact info(email,phone number)..if no user has to send request for contact info..when user send request for contact info then vendor can show candidate info to user..
How will we do that in codeigniter..
Can anyone help me..
Thanks in advance..

A: Follow below steps:

*

*keep one input type with 'hidden' and then set a value of it on the
click of 'yes/no' of the pop-up. post that value at the time of
sending mail. then check if it is no then don't display contact info
otherwise display it.

*to display contact info to the user, vendor have to send mail again
to that user


text:
Q: Master must start with yarn,spark I am getting this error when is want to run SparkPi example.
   beyhan@beyhan:~/spark-1.2.0-bin-hadoop2.4$ /home/beyhan/spark-1.2.0-bin-hadoop2.4/bin/spark-submit --master ego-client --class org.apache.spark.examples.SparkPi /home/beyhan/spark-1.2.0-bin-hadoop2.4/lib/spark-examples-1.jar
        Spark assembly has been built with Hive, including Datanucleus jars on classpath
        Error: Master must start with yarn, spark, mesos, or local
        Run with --help for usage help or --verbose for debug output
        Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties

Also i already start my master via another terminal
>./sbin/start-master.sh
starting org.apache.spark.deploy.master.Master, logging to /home/beyhan/spark-1.2.0-bin-hadoop2.4/sbin/../logs/spark-beyhan-org.apache.spark.deploy.master.Master-1-beyhan.out

Any suggestion ?
Thanks.

A: Download and extract Spark:
$ cd ~/Downloads
$ wget -c http://archive.apache.org/dist/spark/spark-1.2.0/spark-1.2.0-bin-hadoop2.4.tgz
$ cd /tmp
$ tar zxf ~/Downloads/spark-1.2.0-bin-hadoop2.4.tgz
$ cd spark-1.2.0-bin-hadoop2.4/

Start master:
$ sbin/start-master.sh

Find master's URL from logs in the file that above command printed. Lets assume that master is: spark://ego-server:7077
In this case, you can also find your master url by visiting this URL: http://localhost:8080/
Start one slave, and connect it to master:
$ sbin/start-slave.sh --master spark://ego-server:7077

Another way to ensure that master up and running start a shell bound to that master:
$ bin/spark-submit --master "spark://ego-server:7077"

If you get a spark shell, then everything seems fine.
Now execute your job:
$ find . -name "spark-example*jar"
./lib/spark-examples-1.2.0-hadoop2.4.0.jar

$ bin/spark-submit --master "spark://ego-server:7077" --class org.apache.spark.examples.SparkPi ./lib/spark-examples-1.2.0-hadoop2.4.0.jar

A: The error you're getting

Error: Master must start with yarn, spark, mesos, or local

Means that --master ego-client is not recognized by spark.
Use
--master local

for a local execution of spark or
--master spark://your-spark-master-ip:7077


text:
Q: Declare object and its prototype in a JSON block I'd like to fake a namespace in Javascript. This can be done as follows:
var cars = {};
cars.car = function() {
    ...
}
cars.car.prototype = {
    drive: function() {
        ...
    }
}

Works fine. My question, however, is if I can directly fill the whole namespace with JSON, like this:
var cars = {
    car: function() {
        ...
    },
    car.prototype: {
        drive: function() {
            ...
        }
    }
}

That doesn't work. Can I somehow declare the prototype of car inside the car() function? Or is there another way to solve this?

A: Right off the bat, you need to use : (the "property assignment operator") instead of = (the "assignment operator") in a JSON object (JavaScript object literal). You also can't use a property accessor (. or []) on the left side of a property assignment in an object literal.
I think you need at least two statements in JavaScript to both (1) declare a function expression, and (2) assign its prototype. This would prevent you from being able to do what you describe ("directly fill the whole namespace with JSON). I'm not sure why you're trying to do this -- running two statements of JavaScript is fine for most purposes.


text:
Q: Skipping entry in package table because it is not complex In Logcat I get the following:

W/ResourceType(12122): Skipping entry 0x7f02000c in package table 0 because it is not complex!

I checked R.java and 0x7f02000c is the following selector:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true"
          android:drawable="@drawable/ic_action_play" />
    <item android:drawable="@drawable/ab_solid_background" />
</selector>

Every time I bring up the activity, which uses this selector for the background of buttons, I get dozens of these warnings, which makes debugging a mess. How can I fix it?

A: May be it's too late for an answer but
I think, you should take a look at R file, see the int id with the item and check the associative attributes with these widgets


text:
Q: Migrate Magento EE 2.1.8 to Magento CE 2.1.8 How to migrate Magento Enterprise Version 2.1.8 to Magento Community Version 2.1.8?
I have installed a fresh copy of Magento CE with new database then Transfered the theme and the extensions.
Everything works fine.
Then I changed the database connection to the EE database. When I view a product and go to checkout/Cart, I got the below error:
Fatal error: Class 'Magento\GiftCard\Model\Attribute\Backend\Giftcard\Amount' not found in /home/user/public_html/vendor/magento/framework/ObjectManager/Factory/AbstractFactory.php on line 93

Knowing that I have disabled all the GiftCard Extensions on the EE version before migration.

A: I would suggesting NOT copying the Database, because EE have more features/modules installed. This also affects database entires.
I recommend exporting all the data from EE and import it to CE.


text:
Q: Regex that grep numbers after specific string in multiple files and return average I would like to return the average of all numbers after a specific string in multiple files i.e.
We are given 10 files (file1.txt,...,file10.txt). Each file contains among others
Test1: Avg. length 24.01000, time: 0.579
Test2: Avg. length 22.02000, time: 0.879

with different numbers.
If we have 10 files it could look like
file1.txt
Test1: Avg. length 24.01000, time: 0.679
Test2: Avg. length 22.01000, time: 0.479

file2.txt
Test1: Avg. length 27.01000, time: 0.279
Test2: Avg. length 24.01000, time: 0.779

.....
file10.txt
The output I desire is the mean of the lengths and times of Test1 and Test2 over all files:
Mean Test1: Avg. length (file1_Test1_length+...+file10_Test1_lenght)/10, time (file1_Test1_time+...+file_10_Test1_time)/10
Mean Test2: Avg. length (file1_Test2_length+...+file10_Test2_lenght)/10, time (file1_Test2_time+...+file_10_Test2_time)/10

To grep the full output of Test1 I execute:
egrep -rh 'Test1: Avg. length.*' /home/timo/Documents

I'm not sure how to grep only the numbers. I tried
egrep -rhP '(?<=length )\d+' /home/timo/Documents

But I get an error
grep: conflicting matchers specified

I would be really thankful if someone could help me!

A: The following awk solution should work:
awk -F'[ ,:]+' '$1~/^Test[12]/{l[$1]+=$4; t[$1]+=$6; n[$1]++;}
                END{if (n["Test1"]) {for (tst in l) printf("Mean %s: Avg. length %f, time: %f\n",tst,l[tst]/n[tst], t[tst]/n[tst]);} else {print "No input found"}}' file*.txt

This will parse the input files for lines starting Test1 or Test2 and sum fields 4 and 6 (the "length" and "time", respectively). In addition, it will increase the data counter n. In the end, it will either print the average (if any data was found) or an error message.
If you are sure that at least one file will be present, you can simplify this to
awk -F'[ ,:]+' '$1~/^Test[12]/{l[$1]+=$4; t[$1]+=$6; n[$1]++;}
                END{for (tst in l) printf("Mean %s: Avg. length %f, time: %f\n",tst,l[tst]/n[tst], t[tst]/n[tst]);}' file*.txt

Since all your files seem to be in individual sub-folders, the approach depends on your shell. In the easiest case, you can try
awk -F'[ ,:]+' ' ... ' subdir*/file*.txt

A: Using GNU datamash:
$ grep '^Test.*Avg\. length.*time:' file*.txt | tr -d ',' | LC_ALL=C datamash -W -s -g 1 mean 4,6
Test1:  25.51   0.479
Test2:  23.01   0.629

This first extracts the lines that you show using grep.  I do this by matching the text Test at the start of a line, followed by the strings Avg. length and time: somewhere else on the line.  You may want to modify this expression (I don't know if it uniquely matches only the lines that we're interested in).
I then delete all commas from the data, because they mess up the interpretation of the numbers.  I do this with tr.
The grep+tr bit could also be done with sed as
sed '/^Test.*Avg\. length.*time:/!d; s/,//g' file*.txt

I then use GNU datamash to compute the mean lengths and times for each test.  I first tell datamash that whitespaces are to be used as delimiters using -W. The -s sorts the data, because it comes unsorted from grep+tr (or sed), to efficiently group the data globally.
Grouping is done with -g 1 which defines the TestN: labels on each line as the grouping key.  Then, for each such group, the mean is calculated over the 4th and 6th whitespace-delimited column, with mean 4,6.
I set the locale to C (the POSIX locale) for datamash, because the utility may otherwise want decimal numbers to use comma rather than dot as a decimal dot.
Would you want to decorate the output a bit, do so with awk:
sed '/^Test.*Avg\. length.*time:/!d; s/,//g' file*.txt |
LC_ALL=C datamash -W -s -g 1 mean 4,6 |
awk '{ printf "%s Avg. length: %s time: %s\n", $1,$2,$3 }'

This may output something like
Test1: Avg. length: 25.51 time: 0.479
Test2: Avg. length: 23.01 time: 0.629


text:
Q: Browser Repaint/Reflow performance: using CSS3 Gradients vs PNG Gradients I am working at an app that causes lots of browser reflows. Performance is a key issue here. From the performance point of view Is it better to use a CSS3 gradient or an image gradient for some DOM elements? Does a page that uses CSS text shadows and gradients will have a slower reflow as a page that uses images to achieve those visual effects?
Also, are there any reflow tests out there I can use?

A: For drawing, CSS gradients and shadows do task the CPU more than images. Performance used to be pretty bad, these days they are acceptable. If you have a ton of gradients/shadows, you should just implement them and do the tests in your real-world setting. If you just have a few, I wouldn't worry about it.

A: It depends a lot on how the browser renders it, but for the most part those things will render slower. In addition, you'll have a less pixel-perfect display in older browsers. However, this also serves to segment your audience, as generally those with updated browsers also have updated computers. So, it's a trade-off that can work in your favor to essentially serve a stripped down version of your site to those that wouldn't be able to handle it. It's not guaranteed, but I've found it usually balances out pretty well.
Overall, real-world testing is the way to go. Build it, see if it works, and fix performance issues once you find them. I wouldn't hesitate just because there's a chance it might not work. If it works just fine and you don't try it, you'll never know!


text:
Q: How do I filter Python screen print? I want to filter the screen print by my Python program.
Ideally, it would be nice to specify a "print blacklist", such as this one.
*FutureWarning*
INFO*

When part of a screen printout matches one of the above patterns, the whole printout is filtered out.
I'm surprised no one has yet to ask this question, as I think this is extremely useful, because without it, I need to go through different types of screen printouts and deal with them accordingly. You can imagine some of them may be due to print, some due to warning, etc.
I am running my Python script from bash, so bash-based methods are welcome too!

A: You can bind the print variable to a custom function of yours that checks for any output you don't want to see.
Here is an example:
>>> def print(*args, **kwargs):
...     import builtins
...     if not any(str(s).startswith('INFO') for s in args):
...             builtins.print(*args, **kwargs)

A: You say you're willing to do bash. You could write another script, say filter.py:
from sys import stdin

def print_filtered(line):
    if line.startswith("print this"):
        print(line, end='') # The line includes its own newline character

for line in stdin:
    print_filtered(line)

Of course, you can put whatever filtering options you want in print_filtered(). You could even do some replacements; maybe you would want to remove the print this section of the string before you print it.
Now any program that you want to have filtered output, you can run like this:
$ python myfile.py | python filter.py

Rishav also mentioned in his comment that you could replace sys.stdout with a custom object. I don't really like that idea, but you could do that with something like this:
import sys

class FilteredPrinter(object):
    def __init__(self, filtered_print, stdout):
        self._filtered_print = filtered_print
        self._stdout = stdout

    def _write(self, string):
        self._filtered_print(string, self._stdout)

    def __getattr__(self, attr):
        if attr == 'write':
            return self._write
        return getattr(self._stdout, attr)

def filtered_print(string, stdout):
    if string == "\n" or string.startswith("print this"):
        stdout.write(string)

sys.stdout = FilteredPrinter(filtered_print, sys.stdout)
print("print this: my text")
print("print this text")
print("Don't print this")

With this solution, you can specify whatever filters you want; you could also do this with sys.stderr. If you want to go back to the old, use sys.stdout = sys.stdout._stdout. Do be aware that the print function calls sys.stdout.write() once for each of its arguments and again for the newline character. That is, calling print("first", "second") will do this:
sys.stdout.write("first")
sys.stdout.write(" ")
sys.stdout.write("second")
sys.stdout.write("\n")

So just be sure to keep that in mind when writing your filter function.

A:
I want to filter the screen print by my Python program.

You can use Python's logging module, routing all print and warnings output through it:
# in your main module
import logging

# -- log all output to myapp.log
logging.basicConfig(filename='myapp.log', level=logging.DEBUG)
# -- OR log all output to console
logging.basicConfig(level=logging.DEBUG)
# route all output to logging
logging.captureWarnings(True)
print  = logging.info

With this add your own Filter to filter all output as per the required keywords:
# define Filter in its own module, say logfilter.py
class OutputFilter(logging.Filter):
    def __init__(self, keywords, name=None):
        super(OutputFilter, self).__init__(name)
        self.keywords = keywords

    def filter(self, record):
        msg = record.getMessage()
        return not any(k in msg for k in self.keywords)

# add this in your main module
from logfilter import OutputFilter
flt = OutputFilter(['*FutureWarning*', 'INFO*'])
logger = logging.getLogger() # root logger
logger.addFilter(flt)
warnLogger = logging.getLogger('py.warnings') # warnings logger
warnLogger.addFilter(flt)

(...) without it, I need to go through different types of screen printouts and deal with them accordingly.

If you can change the source code it is better to always use a module logger instead of print:
# in any module with output, right after imports
logger = logging.getLogger(__name__)
...
# instead of print
logger.info(...)
logger.error(...)
logger.debug(...)

The advantage is logging allows you very fine grained control on what to output and where, while configuring everything from a central place.
For example, while the above uses the root logger that applies to all logging output, every module of your application can have its own logger, with its specific configuration, e.g.
# somewhere in your main module
# -- basic config is to console
logging.basicConfig(level=logging.DEBUG)
# -- module A output should go into its own file
logger = logging.getLogger('path.to.module.A')
handler = logging.FileHandler(filename='myapp-A.log') # see above
logger.setHandler(handler)
logger.setLevel(logging.INFO)

# path/to/module/A.py
# -- right at the top of the module
import logging
logger = logging.getLogger(__name__)
...
# in the actual code
logger.info('info message')

This example will route all INFO messages by module A into file myapp-A.log while all other output goes to the terminal.
Note: All examples where adopted from the Python Logging Cookbook. Also check out the tutorial for more in-depth explanations.


text:
Q: Using $scope in ui-router resolve I am using ui-router resolve in order to get some data from a service.
The thing is that I need to get a value from the parent $scope in order to call the service as shown bellow.
resolve: {
              contactService: 'contactService',
              contacts: function ($scope, contactService) {
                  return contactService.getContacts($scope.parentCtrl.parentObjectId);
              }
          }

I keep getting Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Also tried a few desperate attempts such as adding scope to the resolve object as shown bellow with not success.
scope: $scope

Any ideas?

A: That's impossible, scope hasn't been initialized at that point so you can't use it in the resolve object. You can access the scope in the controller after it's been initialized. The whole point of resolve is that it runs before controller initialization so that you can inject and directly access the resolved items in your scope.
If you need to pass a variable to the next state you can do that by using the $stateParams object which is available for use in resolve. You can add data to it when changing states, eg:
In your template, if you have a objectId in your scope:
Change states

Or in your controller:
$scope.go('statename', {'id': $scope.objectId});

You can then retrieve that in your resolve by using the $stateParams:
resolve: {
    contactService: 'contactService',
    contacts: function ($stateParams, contactService) {
        return contactService.getContacts($stateParams.id);
    }
}

A: As an alternative to the accepted solution, which requires another round trip to the server for the same resource (if you are getting the value from the server/api) you could $watch the parent from the child controller.
function ParentController($http) {
  var vm = this;
  $http.get(someResourceUrl).then(function(res) {
    vm.someResource = res.data;
  });
}

function ChildController($scope) {
  // wait untill the parent gets the value
  var unwatch = $scope.$watch('parent.someResource', function(newValue) {
    if (newValue) {
      // the parent has the value, init this controller
      init(newValue);
      // dispose of the watcher we no longer need
      unwatch();
    }
  });
  function init(someResource) {
    // ... do something
  }
}

function routerConfig($stateProvider) {
  $stateProvider
    .state('parent', {
      url: '/parent',
      controller: 'ParentController',
      controllerAs: 'parent',
      templateUrl: '...',
    })
    .state('parent.child', {
      url: '/child',
      controller: 'ChildController',
      controllerAs: 'child',
      templateUrl: '...',
    });
}


text:
Q: Skipping over an error warning in an lme loop in R I'm trying to automate my R script to do a loop with loads of analyses and currently I've run aground on getting it to give me a warning during a failed CI test and proceed to the next response variable. I've tried "tryCatch" and "try" separately. Can someone tell me what I'm doing wrong and how to amend it? It's probably something dumb but I've spent weeks trying to sort it out. If I generalize the code below it will get confusing so I've left it in its original form.
Here's what I've got and here are the associated errors-
int <- try(intervals(tmpLme))
if (inherits(int, "try-error"))
    lme(tmp ~ I(log10(Body.mass..kg.)), random = ~1 | Species / CatNumber,
        data=felids, na.action=na.omit )

lower <- dim(int$fixed)[1]
upper <- dim(int$fixed)[1]
felidCIlower <- append(felidCIlower, int$fixed[,1],lower)
felidCIupper <- append(felidCIupper, int$fixed[,3],upper)

This is the error I want to skip over but note:
Error in intervals.lme(tmpLme) :
  Cannot get confidence intervals on var-cov components: Non-positive
  definite approximate variance-covariance

This is the error I don't want - it shows my attempt to skip over the above error isn't working:
Error in int$fixed : $ operator is invalid for atomic vectors

Then there's this attempt
int.model <- function(tmpLme)
int <- tryCatch(intervals(tmpLme), error=function(e) NULL )

-or-
int <- tryCatch(intervals(tmpLme),
                error=function(e) lme(tmp ~ I(log10(Body.mass..kg.)),
                                      random = ~1 | Species / CatNumber,
                                      data=felids,na.action=na.omit ))
lower <- dim(int$fixed)[1]
upper <- dim(int$fixed)[1]
felidCIlower <- append(felidCIlower, int$fixed[,1], lower)
felidCIupper <- append(felidCIupper, int$fixed[,3], upper)

Error in !after : invalid argument type

Thanks in advance!

A: The mistake in the first chunk of code is that if int does inherit from class "try-error", you fit but throw away the lme() fit. Did you intend to assign that and then call intervals() on it and assign that to int so that int contained model term intervals no matter what?
If so the first code chunk should be:
int <- try(intervals(tmpLme))
if (inherits(int, "try-error")) {
    tmpLme2 <- lme(tmp ~ log10(Body.mass..kg.), random = ~1 | Species/CatNumber,
                   data=felids, na.action=na.omit)
    int <- intervals(tmpLme2)
}

Note also that you don't need I(....) around the log10() call in the formula.

A: what about using failwith() in package plyr?
library(plyr)
# Change the NULL to whatever you want to return in case of an error.
clean_interval <- failwith(NULL, intervals)
int <- clean_interval(tmpLme)


text:
Q: LINQ code to combine two database tables? So I have a table that I am showing on a website that gets all the information from a database via some LINQ code. The table "db.Log" contains a few things and a foreign key customerId which is linked to the Id in a database called dbo.customers (it has Id and customerName only) and I would like the LINQ code to combine those two so I can fill the table with the names of the customers instead of an ID which doesn't really say anything unless you know them all. Below is the current code:
LogModelsController.cs
message = (from log
           in db.Log
           select log);

int pageSize = 10;
int pageNumber = (page ?? 1);

return View(message.OrderByDescending(i => i.timeStamp).ToPagedList(pageNumber, pageSize));

LogModel.cs
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;

namespace ASDMVC.Models
{
    [Table("Log")]
    public class LogModel
    {
        [Key]
        public long id { get; set; }
        public string message { get; set; }
        public DateTime timeStamp { get; set; }
        public string level { get; set; }
        public int customerId { get; set; }
    }

    public class LogDBContext:DbContext
    {
        public LogDBContext() : base("MySqlConnection")
        {

        }

        public DbSet <LogModel> Log { get; set; }

    }
}

I'm very new to LINQ code so excuse me for that, any help would be appreciated.
Thanks in advance.
Edit: NewCustomerModel.cs
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Web.Mvc;

namespace ASDMVC.Models
{
    [Table("Customers")]
    public class NewCustomerModel
    {
        [Key]
        public int Id { get; set; }
        [Display(Name = "Customer Id")]
        public int CustomerId { get; set; }
        public string CustomerName { get; set; }
    }

    public class CustomerDBContext : DbContext
    {
        public CustomerDBContext() : base("MySqlConnection")
        {

        }
        public DbSet<NewCustomerModel> Customers { get; set; }
    }
}

I think (after speaking to a friend) that this model is needed - might be completely wrong.

Code after user1666620 suggestion
LogModelsController.cs
message = (from log in db.Log join customers in dbo.Customers on log.customerId equals customers.Id select log);

int pageSize = 10;
int pageNumber = (page ?? 1);

return View(message.OrderByDescending(i => i.timeStamp).ToPagedList(pageNumber, pageSize));

LogModel.cs
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;

namespace ASDMVC.Models
{
    [Table("Log")]
    public class LogModel
    {
        [Key]
        public long id { get; set; }
        public string message { get; set; }
        public DateTime timeStamp { get; set; }
        public string level { get; set; }
        public int customerId { get; set; }
        public int customerName { get; set; }
    }

    public class LogDBContext:DbContext
    {
        public LogDBContext() : base("MySqlConnection")
        {

        }

        public DbSet <LogModel> Log { get; set; }

    }
}

With the error:

The specified LINQ expression contains references to queries that are
  associated with different contexts.

A: This should do it for you:
var message = (from log in db.Log
               join customers in dbo.customers on log.customerid equals customers.Id
               select log);

In the above, there's no need to explicitly use a where clause as that is handled in the join.
If you want to return only specific columns, you can do something like the below:
var message = (from log in db.Log
               join customers in dbo.customers on log.customerid equals customers.Id
               select new { customerId = customers.Id, logId = log.id });

If you want to do a Join between two contexts, take a look at this workaround: Simulating Cross Context Joins--LINQ/C#

A: Controller:
message = db.GetLogs();

int pageSize = 10;
int pageNumber = (page ?? 1);
var logs = message.OrderByDescending(i => i.timeStamp).ToPagedList(pageNumber, pageSize);

foreach (var log in logs)
    log.Name = Customer.Where(a => a.Value == log.customerId.ToString()).FirstOrDefault().Text;
                return PartialView("_LogPartialLayout", logs);

Model:
using System;
using System.Linq;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Collections.Generic;
using System.Web.Mvc;

namespace ASDMVC.Models
{
    [Table("Log")]
    public class LogModel
    {
        [Key]
        public long id { get; set; }
        public string message { get; set; }
        public DateTime timeStamp { get; set; }
        public string level { get; set; }
        public int customerId { get; set; }
        [NotMapped]
        public string Name { get; set; }
    }

    public class LogDBContext:DbContext
    {
        public LogDBContext() : base("MySqlConnection")
        {

        }

        public DbSet <LogModel> Log { get; set; }

        public IQueryable<LogModel> GetLogs()
        {
            return from log in Log
                   select log;
        }
    }
}


text:
Q: Angular CDK: How to set Inputs in a ComponentPortal I would like to use the new Portal from material CDK to inject dynamic content in multiple part of a form.
I have a complex form structure and the goal is to have a form that specify multiple place where sub components could (or not) inject templates.
Maybe the CDK Portal is not the best solution for this?
I tried something but I am sure it is not the way of doing:
https://stackblitz.com/edit/angular-yuz1kg
I tried also with new ComponentPortal(MyPortalComponent) but how can we set Inputs on it ? Usually is something like componentRef.component.instance.myInput

A: After version angular 9 'DomPortalHost' has been deprecated and this has been changed to 'DomPortalOutlet'. so now it will like:
this.portalHost = new DomPortalOutlet(
   this.elementRef.nativeElement,
   this.componentFactoryResolver,
   this.appRef,
  this.injector
);

const componentRef = this.portalHost.attachComponentPortal(this.portal);
componentRef.instance.myInput = data;
Apart from this I felt the best solution for this is just bind the (attached) event and set inputs there:
<ng-template [cdkPortalOutlet]="yourPortal" (attached)="setInputs($event)"> </ng-template>
and in ts set your inputs:
setInputs(portalOutletRef: CdkPortalOutletAttachedRef) {
    portalOutletRef = portalOutletRef as ComponentRef<myComponent>;
    portalOutletRef.instance.inputPropertyName = data;
}

A: If you are using Angular 10+ and following Awadhoot's answer, PortalInjector is now deprecated so instead of:
new PortalInjector(this.injector, new WeakMap([[SOME_TOKEN, data]]))

You now have:
Injector.create({
  parent: this.injector,
  providers: [
    { provide: SOME_TOKEN, useValue: data }
  ]
})

A: You can create a custom injector and inject it to the component portal you create.
createInjector(dataToPass): PortalInjector {
    const injectorTokens = new WeakMap();
    injectorTokens.set(CONTAINER_DATA, dataToPass);
    return new PortalInjector(this._injector, injectorTokens);
}

CONTAINER_DATA is a custom injector (InjectorToken) created by -
export const CONTAINER_DATA = new InjectionToken<{}>('CONTAINER_DATA');

To consume created injector, use -
let containerPortal = new ComponentPortal(ComponentToPort, null, this.createInjector({
          data1,
          data2
        }));

overlay.attach(containerPortal);

overlay is an instance of OverlayRef (Which is Portal Outlet)
Inside ComponentToPort, you will need to inject the created injector -
@Inject(CONTAINER_DATA) public componentData: any

More on this here.

A: Can set component inputs (or bind to outputs as an observable) in this way:
portal = new ComponentPortal(MyComponent);
this.portalHost = new DomPortalHost(
      this.elementRef.nativeElement,
      this.componentFactoryResolver,
      this.appRef,
      this.injector
    );

const componentRef = this.portalHost.attach(this.portal);
componentRef.instance.myInput = data;
componentRef.instance.myOutput.subscribe(...);
componentRef.changeDetectorRef.detectChanges();

A: No idea from what version of Angular this is working (at least from 13.3.9). But there is a much simpler way now because overlayRef.attach(portal) is now returning ComponentRef.
So
    const overlayRef = this._overlay.create();
    const portal = new ComponentPortal(MyComponent);
    const cmpRef = overlayRef.attach(portal);
    cmpRef.instance.myInput = 42;

will work now

A: I know, the question is 4 years old, but maybe helpful for someone:
In current version of CDK the ComponentPortal has a new function named "setInput":
setInputs(portalOutletRef: CdkPortalOutletAttachedRef) {
portalOutletRef = portalOutletRef as ComponentRef<BaseAuditView>;

portalOutletRef.setInput('prop1', this.prop1);
portalOutletRef.setInput('prop2', this.prop2);

}
if you using this function, angular`s change detections works very well!

(method) ComponentRef.setInput(name: string, value: unknown): void
Updates a specified input name to a new value. Using this method will properly mark for check component using the OnPush change detection strategy. It will also assure that the OnChanges lifecycle hook runs when a dynamically created component is change-detected.

@param name — The name of an input.
@param value — The new value of an input.

A: this seems a bit more simple, using the cdkPortalOutlet and the (attached) emitter
    import {Component, ComponentRef, AfterViewInit, TemplateRef, ViewChild, ViewContainerRef, Input, OnInit} from '@angular/core';
    import {ComponentPortal, CdkPortalOutletAttachedRef, Portal, TemplatePortal, CdkPortalOutlet} from '@angular/cdk/portal';

    /**
     * @title Portal overview
     */
    @Component({
      selector: 'cdk-portal-overview-example',
      template: '<ng-template [cdkPortalOutlet]="componentPortal" (attached)=foo($event)></ng-template>',
      styleUrls: ['cdk-portal-overview-example.css'],
    })
    export class CdkPortalOverviewExample implements OnInit {
      componentPortal: ComponentPortal<ComponentPortalExample>;

      constructor(private _viewContainerRef: ViewContainerRef) {}

      ngOnInit() {
        this.componentPortal = new ComponentPortal(ComponentPortalExample);
      }

      foo(ref: CdkPortalOutletAttachedRef) {
        ref = ref as ComponentRef<ComponentPortalExample>;
        ref.instance.message = 'zap';
      }
    }

    @Component({
      selector: 'component-portal-example',
      template: 'Hello, this is a component portal {{message}}'
    })
    export class ComponentPortalExample {
      @Input() message: string;
    }

A: You can inject data to ComponentPortal with specific injector passed on 3rd param of ComponentPortal
fix syntax issue:
Can't resolve all parameters for Component: ([object Object], [object Object], ?

This is the code
export const PORTAL_DATA = new InjectionToken<{}>('PortalData');

class ContainerComponent {
  constructor(private injector: Injector, private overlay: Overlay) {}

  attachPortal() {
    const componentPortal = new ComponentPortal(
      ComponentToPort,
      null,
      this.createInjector({id: 'first-data'})
    );
    this.overlay.create().attach(componentPortal);
  }

  private createInjector(data): PortalInjector {

    const injectorTokens = new WeakMap<any, any>([
      [PORTAL_DATA, data],
    ]);

    return new PortalInjector(this.injector, injectorTokens);
  }
}

class ComponentToPort {
  constructor(@Inject(PORTAL_DATA) public data ) {
    console.log(data);
  }
}


text:
Q: Add Post Format Support to Twentyeleven Child Theme On a Twentyeleven child theme's functions.php file I attempted to add video post format support using:
add_theme_support('post-formats', array( 'aside', 'chat', 'gallery', 'image', 'link', 'quote', 'status', 'video', 'audio'));

...adding the 'video' format to the array.  But it would not work until I deleted the function in the parent theme. Obviously, when the theme is updated and functions.php is overwritten, I will lose the change.
Whats the best way to avoid this and add support to my child theme?
Thanks.

A: try running your code with a lower priority:
add_action( 'after_setup_theme', 'my_twentyeleven_setup', 20 );

function my_twentyeleven_setup(){
  add_theme_support('post-formats',  array(
     'aside',
     'chat',
     'gallery',
     'image',
     'link',
     'quote',
     'status',
     'video',
     'audio',
  ));
}


text:
Q: AFNetworking AFHTTPRequestOperation responseObject convert to NSXMLParser. The parser doesn't contain the all http information I have a problem about AFNetworking to get HTML web page.
I had a url:
NSString *url = @"http://www.w3schools.com/";

Also I had a method:
- (void)AFNReturnXMLString:(NSString *)string{

NSURL *url = [NSURL URLWithString:string];
NSURLRequest *request = [NSURLRequest requestWithURL:url];

AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];

// Make sure to set the responseSerializer correctly
op.responseSerializer = [AFXMLParserResponseSerializer serializer];
op.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];

[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

    // Get XMLParser Object
    NSXMLParser *XMLParser = (NSXMLParser *)responseObject;
    [XMLParser setShouldProcessNamespaces:YES];
    NSLog(@"%@", XMLParser);

    // Leave these commented for now (you first need to add the delegate methods)
    XMLParser.delegate = self;
    [XMLParser parse];

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error Fucking: %@", error);
}];
[op start];}

I have already use the NSXMLParser delegate. When I ran the method, the variable "qName" only shows the root <html> and <head> tag, but does not show <body> and <body>'s sub node.
Also I used the following method in the block instead of NSXMLParser object:
// Get HTML String
NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"%@", string);

The string shows all the pages content.
Do anyone meet such the problem before?


text:
Q: How to tell if a Horn's formula is satisfiable? I have this formula:
F = (¬A ∨ B) ∧ D ∧ (¬D ∨ E ∨ ¬C) ∧ C ∧ (¬C ∨ E ∨ ¬B) ∧ ¬B.
And I converted into a horns formula:
F = (A -> B) ∧ ( 1 -> D) ∧ (D ∧ C -> E) ∧ (1 -> C) ∧ (C ∧ B -> E) ∧ (B -> 0)
I now want to tell if this is satisfiable but I'm not sure how to do that. Any help will be much appreciated. Thanks!

A: One style of reasoning is forward propagation.
Iterate over the clauses, and whenever you find one whose preconditions have been satisfied (in the first iteration, $1\rightarrow D$ would be one) note down its consequent as satisfied and delete the clause.
Then once you reach the end of the list start again from the beginning, until you do a complete iteration in which no further consequences could have been satisfied.
For example, in the first iteration you would deduce $D, C$.
In the second $E$, etc.
Does that make sense to you?


text:
Q: Mule Log4j2 not working I have a log4j2 XML file in my src/main/resources as below. But Still I do not see the log file created. Any idea what could I be missing.
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
  <Appenders>
    <File name="file" fileName="C:\\Users\\Guest\\Desktop\\Mule.log">
      <PatternLayout>
        <Pattern>%d %p %c{1.} [%t] %m %ex%n</Pattern>
      </PatternLayout>
    </File>
    <Console name="STDOUT" target="SYSTEM_OUT">
      <PatternLayout pattern="%m%n"/>
    </Console>
  </Appenders>
  <Loggers>
    <Root level="trace">
      <AppenderRef ref="file" level="DEBUG"/>
      <AppenderRef ref="STDOUT" level="INFO"/>
    </Root>
  </Loggers>
</Configuration>

A: Log4j2 configuration works only in Mule-3.6 version+, check your Mule version and give file name to C:/Users/Guest/Desktop/Mule.log format.
Sample file:
    <?xml version="1.0" encoding="utf-8"?>
<Configuration>
    <Properties>
        <Property name="log-path">${env:MULE_HOME}/logs/test</Property>
        <Property name="log-name">test</Property>
    </Properties>
    <Appenders>
        <Console name="console-log" target="SYSTEM_OUT">
            <PatternLayout
                pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n" />
        </Console>
        <RollingFile name="info-log" fileName="${log-path}/${log-name}-info.log"
            filePattern="${log-path}/${log-name}-info-%d{yyyy-MM-dd}.log">
            <PatternLayout>
                <pattern>[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n
                </pattern>
            </PatternLayout>
            <Policies>
                <TimeBasedTriggeringPolicy interval="1" modulate="true" />
            </Policies>
            <SizeBasedTriggeringPolicy size="10 MB" />
            <DefaultRolloverStrategy max="10"/>
        </RollingFile>
        <RollingFile name="debug-log" fileName="${log-path}/${log-name}-debug.log"
            filePattern="${log-path}/${log-name}-debug-%d{yyyy-MM-dd}.log">
            <PatternLayout>
                <pattern>[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n
                </pattern>
            </PatternLayout>
            <Policies>
                <TimeBasedTriggeringPolicy interval="1" modulate="true" />
            </Policies>
            <SizeBasedTriggeringPolicy size="10 MB" />
            <DefaultRolloverStrategy max="10"/>
        </RollingFile>
        <RollingFile name="trace-log" fileName="${log-path}/${log-name}-trace.log"
            filePattern="${log-path}/${log-name}-trace-%d{yyyy-MM-dd}.log">
            <PatternLayout>
                <pattern>[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n
                </pattern>
            </PatternLayout>
            <Policies>
                <TimeBasedTriggeringPolicy interval="1" modulate="true" />
            </Policies>
            <SizeBasedTriggeringPolicy size="10 MB" />
            <DefaultRolloverStrategy max="10"/>
        </RollingFile>
        <RollingFile name="error-log" fileName="${log-path}/${log-name}-error.log"
            filePattern="${log-path}/${log-name}-error-%d{yyyy-MM-dd}.log">
            <PatternLayout>
                <pattern>[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n
                </pattern>
            </PatternLayout>
            <Policies>
                <TimeBasedTriggeringPolicy interval="1" modulate="true" />
            </Policies>
            <SizeBasedTriggeringPolicy size="10 MB" />
            <DefaultRolloverStrategy max="10"/>
        </RollingFile>
    </Appenders>
    <Loggers>
        <!-- CXF is used heavily by Mule for web services -->
        <AsyncLogger name="org.apache.cxf" level="WARN"/>

        <!-- Apache Commons tend to make a lot of noise which can clutter the log-->
        <AsyncLogger name="org.apache" level="WARN"/>

        <!-- Reduce startup noise -->
        <AsyncLogger name="org.springframework.beans.factory" level="WARN"/>

        <!-- Mule classes -->
        <AsyncLogger name="org.mule" level="INFO"/>
        <AsyncLogger name="com.mulesoft" level="INFO"/>

        <!-- Reduce DM verbosity -->
        <AsyncLogger name="org.jetel" level="WARN"/>
        <AsyncLogger name="Tracking" level="WARN"/>

        <AsyncRoot level="DEBUG">
            <appender-ref ref="info-log" level="info" />
            <appender-ref ref="trace-log" level="trace" />
            <appender-ref ref="debug-log" level="debug" />
            <appender-ref ref="error-log" level="error" />
            <appender-ref ref="console-log" level="debug" />
        </AsyncRoot>

    </Loggers>
</Configuration>

For studio, specify location of MULE_HOME in Run Configuration->Environment->new->Name->MULE_HOME and Value->c:/test

A: Try changing fileName to fileName="C:/Users/Guest/Desktop/Mule.log"


text:
Q: Portable VS 2008 Web Project I want to setup a VS 2008 Web Project in such a way that if some other developer wants to use VS 2010 (s)he can do it without affecting other developers. Can I do it by ignoring (svn:ignore or gitignore) some local IDE specific resources. Can you please point me to a guide, if this is possible.
Thanks


text:
Q: How to define tile provider (H.map.provider.TileProvider)? I am trying to get the the tiles in a bounding box to pass them to the PDE. I am using the following code, but I am not sure how to define the H.map.provider.TileProvider.
// I don't know how to define the tileProvider (this is what I have for now)
var tileProvider = new H.map.provider.TileProvider({
min: 12,
max: 15,
});

var overlayLayer = new H.map.layer.TileLayer(tileProvider, {
// Let's make it semi-transparent
opacity: 0.5
})

var boundingBox = new
H.geo.Rect(map.getViewBounds().getTop(),map.getViewBounds().getLeft(),map.getVi
ewBounds().getBottom(),map.getViewBounds().getRight());

var zoomLevel=14;
var cacheOnly=false;
var prioCenter=new H.math.Point(42.36099070901032,-71.09613451879883);

overlayLayer.requestTiles(boundingBox, zoomLevel, cacheOnly, prioCenter)

Would you please let me know how to define the TileProvider?
Thanks

A: You can't create instance of TileProvider since it is an abstract class. You can create instance of its children(ImageTileProvider, MarkerTileProvider etc. refer documentation in developer site).
Example:
  // Create your own LocalObjectProvider and add some hierarchical objects:
  myProvider = new H.map.provider.LocalObjectProvider();
  myMap.addLayer(new H.map.layer.ObjectLayer(myProvider));

A: I know it has been a year for this question, but an answer might help others:
(function (map) {
    tileProvider = new H.map.provider.ImageTileProvider({
        min: 5, //min zoom factor
        max: 12,  //max zoom factor

define a getURL function which takes 3 parameters:
getURL: function (column, row, zoom) {

here you should return a url contains the tiles. You could get it over an API or even local. At the end pass the 3 factors: zoom / col / row  .. or how your image is called
In the next example the image is stored in a folder named after the zoom number and the image called for example: 12-16.png
            return `.../${zoom}/${column}-${row}.png`;
        }
    });

Notice that if you get your tile images from an external provider
You should acknowledge the provider with the Copyrights method:
tileProvider.getCopyrights = function (bounds, level) {
    return [{
        label: "© ....", // this will appear under the map
        alt: "© ...."
    }];
};

Then define a layer that contains the tiles.
var overlayLayer = new H.map.layer.TileLayer(tileProvider);

Add the layer to the map (I am assuming you have already initialized a map)
 map.addLayer(overlayLayer);
})(map);

(function(map) {
    tileProvider = new H.map.provider.ImageTileProvider({
        min: 5,
        max: 12,
        getURL: (column, row, zoom) =>
            `${site_url}/images-folder/tiles-folder/${zoom}/${column}_${row}.png`,
    });
    tileProvider.getCopyrights = (bounds, level) => {
        return [{
            label: "©...",
            alt: "©..."
        }];
    };
    let overlayLayer = new H.map.layer.TileLayer(tileProvider);
    map.addLayer(overlayLayer);
})(map);


text:
Q: how to get the specific text form xml file using python? <?xml version="1.0" encoding="UTF-8"?>
<robot generator="Robot 3.2.1 (Python 3.8.3 on darwin)" generated="20200715 10:39:17.458" rpa="false">
<suite id="s1" name="CCC" source="/Users/admin/Desktop/robotframeworknewdesign/CCC-robotframework/tests/Csss.robot">
<test id="s1-t1" name="Launch the Application and select the CMC in Dashboard">
<kw name="Given Launch the Browser" library="LandDef">
<kw name="Open the Browser" library="LandingPage">
<kw name="Open Browser" library="SeleniumLibrary">
<doc>Opens a new browser instance to the optional ``url``.</doc>
<arguments>
<arg>about:blank</arg>
<arg>${BROWSER}</arg>
</arguments>
<msg timestamp="20200715 10:39:31.181" level="INFO">Opening browser 'headlesschrome' to base url 'about:blank'.</msg>
<status status="PASS" starttime="20200715 10:39:31.181" endtime="20200715 10:39:33.740"></status>
</kw>
<kw name="APIResponse ping_msg" library="InsightsPageObject">
<kw name="Call Method" library="BuiltIn">
<doc>Calls the named method of the given object with the provided arguments.</doc>
<arguments>
<arg>${connectionObj}</arg>
<arg>ping_msg</arg>
</arguments>
<assign>
<var>${response_ping_msg}</var>
</assign>
<msg timestamp="20200715 10:39:33.742" level="INFO">${response_ping_msg} = o</msg>
<status status="PASS" starttime="20200715 10:39:33.741" endtime="20200715 10:39:33.742"></status>
</kw>

Here I will have different msg text are available. I need to pic specific msg i.e., Opening browser 'headlesschrome' to base url 'about:blank'. Below I tried but it displays all msg text
        data_file = 'output.xml'
        tree = ET.parse(data_file)
        root = tree.getroot()
        for i in root.findall('.//msg'):

            message = i.text
            expmsg ="Opening browser"
            if expmsg.find(message):
                findtext=message
                print(findtext)

A: You can use BeautifulSoup to find all msg tags and then filter them so you only get the ones that start with the string 'Opening'
from bs4 import BeautifulSoup

...

soup = BeautifulSoup(your_text, 'lxml')
messages = soup.find_all('msg')

for message in messages:
    if message.text.startswith('Opening'):
        print('*\t',message.text)


text:
Q: Randomize the divs that I append into another one This is what I have:
$(function(){
    $('.apple').appendTo('.container');
});

Now, lets say I have 20 different divs with class name .apple.
How can I have them append into Container randomly? So every time that I load the page the order would be different.
Thank you in advance!

A: You can try below code by getting some random value and use it for if / else conditions :
$(function(){
    $('.apple').each(function(){
       var random = ((Math.random()*100) + 50).toFixed();

       if(random > 100)
          $('.container').append($(this));
       else if(random < 100)
           $('.container').prepend($(this));
        else
        {
          var childCount = $('.container').children().length;
            $('.container').find('div:eq('+(childCount/2)+')').append($(this));
        }
    });
});

Demo

A: Giving you an approach which can be used for any number of elements.
Generate random numbers between 0 and 1 and based on it, either append or prepend your element
$('.apple').each(function(){
   var j = Math.floor(Math.random() * 2);
   if(j== 0)
       $('.container').append($(this));
   else
       $('.container').prepend($(this));
});

A: EDITED
You can do something like this:
//create an array equals number of .apple
var arr = [];

$(".apple").each(function(index){
    arr.push(index);//create an array with index
});

var shuffled_array = shuffle(arr);//shuffle the array

shuffled_array.forEach(function(index) {
    $(".apple:eq("+index+")").appendTo('.container');
});

function shuffle(array) { //Fisher–Yates Shuffle function
  var m = array.length, t, i;

  // While there remain elements to shuffle…
  while (m) {

    // Pick a remaining element…
    i = Math.floor(Math.random() * m--);

    // And swap it with the current element.
    t = array[m];
    array[m] = array[i];
    array[i] = t;
  }

  return array;
}

A: Use like this:
var idx;
$('.apple').each(function(){
   idx = Math.floor(Math.random() * 20) +1;
   $(this).eq(idx).appendTo('.container');
});

A: You may also use like this:
$('.apple').sort(function(a,b){
  var tmp = parseInt( Math.random()*20 );
  var isOE = tmp % 2;
  var isPN = tmp > 10 ? 1 : -1;
  return( isOE * isPN );
}).appendTo('.container');

for more details view this

A: Try Something like this:

HTML Code :

Apple

<button id="test">Add</button>

js code :

  $('#test').click(function(){
    var div_length = $('.container .apple').length;
    var rand = Math.floor(Math.random() * div_length);
    if($(".container").children().length > 0)
        $(".container .apple:eq("+rand+")").after(jQuery('.wrapper').html()).attr('rand',rand);
    else
        $(".container").append(jQuery('.wrapper').html());
  });

 Note : I have taken wrapper to .apple class and have fired click event on button to append div

A: $.when($(".apples"), [])
    .done(function (data, apples) {
    $.each(data, function (k, v) {
        setTimeout(function () {
            apples.push(v);
            if (apples.length === data.length) {
                $(apples).appendTo(".container")
            };
        }, 1 + Math.floor(Math.random() * 5));
    });
});

jsfiddle http://jsfiddle.net/guest271314/d4p39/


text:
Q: python filename, _ = urlretrieve(url + filename, dest_filename, reporthook=download_progress_hook) I'm a newbie of Python and trying to get to know about machine learning.  Following is a code bock that I get from Udacity assignnment.
def maybe_download(filename, expected_bytes, force=False):
  """Download a file if not present, and make sure it's the right size."""
  dest_filename = os.path.join(data_root, filename)
  if force or not os.path.exists(dest_filename):
    print('Attempting to download:', filename)
    filename, _ = urlretrieve(url + filename, dest_filename, reporthook=download_progress_hook)
    print('\nDownload Complete!')
  statinfo = os.stat(dest_filename)
  if statinfo.st_size == expected_bytes:
    print('Found and verified', dest_filename)
  else:
    raise Exception(
      'Failed to verify ' + dest_filename + '. Can you get to it with a browser?')
  return dest_filename

I can understand most of the part.  However, I'm very confused about filename, _ = urlretrieve(...) part.  What is this assign to?  I trace it in debugger and find that filename = '.\\notMNIST_large.tar.gz' remain no change before or after this expression.
So my question what does this filename, _ = urlretrieve(...) really mean?  Is this some kind of advance technique to assign value in hidden expression?

A: In Python, the _ variable is an idiom for "I am not interested in this return value".  The urlretrieve function returns a tuple (a sequence of immuntable values) containing two values: the filename of the file containing the results of the request, and the headers of the returned document.  So the headers are essentially "thrown away" because the function does not want to care about them.
Here is a little toy example that further illustrates the concept:
def myFunction():
  return(1,2)

a, _ = myFunction()
print a

A: Python has a feature named "tuple unpacking" that allow to assign elements of a tuple (or of just any sequence actually) to variables. So if you have for exemple a (width, height) tuple and want to assign it's elements to individual variables, you can just do it in one single statement ie:
size = (42, 124)
width, height = size
print width
print height

Some functions make use of this by returning a tuple, which is usually unpacked on function call return ie:
def foo():
    return "a", 42

letter, answer = foo()

and sometimes the caller just don't care about one of those values, so assigning the unwanted value to _ is a common convention meaning "I don't care about this value" (FWIW '_' is nothing special or magic, it's a valid variable name just like 'a' or 'foo' or whatever else).
urlretrieve() happens to be one of those functions - it actually

Return a tuple (filename, headers) where filename is the local file name under which the object can be found, and headers is whatever the info() method of the object returned by urlopen() returned (for a remote object, possibly cached)

https://docs.python.org/2/library/urllib.html#urllib.urlretrieve
The reason for returning the local filename is that urlretrieve can be called without a filename argument, in which case it saves the content in a tempfile with a generated name and returns this name so the caller can access the file.
In your snippet there's actually no real reason to reassign this value to the existing filename since it's supposed to be the very same name anyway so it's confusing at best. Inspecting the headers (which are here ignored) to find out if what we got is really what we expected (content-type, encoding etc) would have been a better idea.


text:
Q: Recognizing Image Target Lines I'm trying to write a script that views an image, looks at lines on the image, and creates bounding boxes around the lines. Here is what I'm talking about...
I have this image:

I'm trying to have a way of intelligently cropping each section using a script. The best idea I came up with was to have colored tape around each of the sections like this:

Given this image with the colored tape the program should be able to find the colored lines and identify where they intersect. Here is a visual of what the program should be able to locate: (Black lines are where the tape is, red dots are the intersecting positions)

The end game here is for the program to be able to use this data to

*

*Know how many sections there are (in this case 9)

*Know where the sections are and create a bounding box around each one

Visually something like this:

OpenCV has facial detection and feature detection so something like this with a static image should be fairly possible. What is the best method to accomplish this?

A: There are many ways to do what you want.
One is to use sift:
https://docs.opencv.org/3.3.0/da/df5/tutorial_py_sift_intro.html
You will need to use keypoint detection, something like:
sift = cv2.SIFT()
kp = sift.detect(img,None)

You can check if the points are right with:
    img2 = cv2.drawKeyPoints(kp)
Then you will need to use cv2.boundingRect
box = cv2.boundingRect(kp)

If your marker is of a different color then the rest of the image, you only need to make a color filter to find the points.


text:
Q: how to give relative path to jquery load function

A: $(document).ready(function(){
    $('#includedContent').load("../Projects/menu.html", function() {
       //stuff
    });
});


text:
Q: vue data variables are undefined in method I'm working with Vue and making a game and when getting the data for said game, some variables that I have defined in data are being returned undefined. Here's the code:
data() {
    return {
      receivedGame: undefined,
      allSteps: [],
}

methods: {

     async gameData() {
     const response = await fetch(`...`);

        const responseData = await response.json();

        this.receivedGame = responseData.steps; //returns correct data

        responseData.steps.map((step) => {
          this.allSteps.push({ //returns error, allSteps is undefined
            type: step.type,
          });
        });
 }
}

A: The data hook must be a function that returns an object. Here you don't return anything!
data() {
  return {
    receivedGame: undefined,
    allSteps: [],
  }
}


text:
Q: Is there any better way to access twitter streaming api through python? I need to fetch twitter historical data for a given set of keywords. Twitter Search API returns tweets that are not more than 9 days old, so that will not do. I'm currently using Tweepy Library (http://code.google.com/p/tweepy/) to call Streaming API and it is working fine except the fact that it is too slow. For example, when I run a search for "$GOOG" sometimes it takes more than an hour between two results. There are definitely tweets containing that keyword but it isn't returning result fast enough.
What can be the problem? Is Streaming API slow or there is some problem in my method of accessing it? Is there any better way to get that data free of cost?

A: How far back do you need?  To fetch historical data, you might want to keep the stream on indefinitely (the stream API allows for this) and store the stream locally, then retrieve historical data from your db.
I also use Tweepy for live Stream/Filtering and it works well.  The latency is typically < 1s and Tweepy is able to handle large volume streams.

A: streaming API too fast you get message as soon as you post it, we use twitter4j. But streamer  streams only current messages, so if you not listening on streamer the moment you send tweet then message is lost.


text:
Q: Bounty custom message less than 30 characters breaks dialog There's a strange edge case when adding custom bounty messages. An empty message is allowed, but if you do type a message, it must be at least 30 characters:

If you try to submit a non-empty message less than 30 characters, the "Start Bounty" button is disabled, and nothing happens:

The button never re-enables, even if you fix the message:

A: Coming to you in the next build: a re-enabled button and an error message to go with it.


text:
Q: Pictures in HTML I'm kinda new in HTML. I'm trying to make a page with HTML where I have text in the left of my page (the lyrics of a song) and then a picture that repeats itself at the right (just beside) of that text. But I want the picture to stop repeating itself at the bottom at some point. I want it to go just the length of the text, so I can write some thing below it, but the pictures just go endlessly. This is how I put the picture in the HTML file:

Just to clarify: i want the image to repeat itself (one below itself again and again) but then STOP repeating at a certain point.
that's why i used "repeat-y". But with with it just goes on repeating itself, non-stop.
and the possition there (95%) is so it will place at the point i want it in the right of the page (so i can write a text at the left of it)
Also i receive a -1 point, im not very sure why but i'll leave the full code here, in case that was my error:
<!doctype html>

<meta charset="utf-8">
<title>Documento sin título</title>
<link rel="stylesheet" href="mihojadeestilosTSlyrics.css"/>

August

Salt air, and the rust on your door

I never needed anything more

Whispers of "Are you sure?"

"Never have I ever before"

But I can see us lost in the memory

August slipped away into a moment in time

'Cause it was never mine

And I can see us twisted in bedsheets

August sipped away like a bottle of wine

'Cause you were never mine

Your back beneath the sun

Wishin' I could write my name on it

Will you call when you're back at school?

I remember thinkin' I had you

But I can see us lost in the memory

August slipped away into a moment in time

'Cause it was never mine

And I can see us twisted in bedsheets

August sipped away like a bottle of wine

'Cause you were never mine

Back when we were still changin' for the better

Wanting was enough

For me, it was enough

To live for the hope of it all

Cancel plans just in case you'd call

And say, "Meet me behind the mall"

So much for summer love and saying "us"

'Cause you weren't mine to lose

You weren't mine to lose, no

But I can see us lost in the memory

August slipped away into a moment in time

'Cause it was never mine

And I can see us twisted in bedsheets

August sipped away like a bottle of wine

'Cause you were never mine

'Cause you were never mine, never mine

But do you remember?

'Remember when I pulled up and said, "Get in the car"

And then canceled my plans just in case you'd call?

Back when I was livin' for the hope of it all, for the hope of it all

"Meet me behind the mall"

Remember when I pulled up and said, "Get in the car"

And then canceled my plans just in case you'd call?

Back when I was livin' for the hope of it all (For the hope of it all)

For the hope of it all

For the hope of it all

(For the hope of it all)

(For the hope of it all)

and then in the css file, there is this for the text:
body{position:absolute;
    text-align:center;
    padding:20px;
}

A: You try to assign the repeating image pattern to the whole page body - which is why it continues forever.
What you should do instead, is to create two DIVs (optionally wrapped inside a third, outer DIV), one for your text, one for the image, and make the CSS applicable only to the one with image.
See this CodePen for an example code:

#outerdiv {
  display: flex;
}

#div1 {
  width: 50%;
}

#div2 {
  width: 50%;
  background: url("https://images.unsplash.com/photo-1489389944381-3471b5b30f04?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=80");
  background-repeat: repeat-y;
}

"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia
    voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi
    tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui
    in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"

Codepen
Here is your web page with a working side-image:
<!doctype html>

<meta charset="utf-8">
<title>Documento sin título</title>

August

Salt air, and the rust on your door

I never needed anything more

Whispers of "Are you sure?"

"Never have I ever before"

But I can see us lost in the memory

August slipped away into a moment in time

'Cause it was never mine

And I can see us twisted in bedsheets

August sipped away like a bottle of wine

'Cause you were never mine

Your back beneath the sun

Wishin' I could write my name on it

Will you call when you're back at school?

I remember thinkin' I had you

But I can see us lost in the memory

August slipped away into a moment in time

'Cause it was never mine

And I can see us twisted in bedsheets

August sipped away like a bottle of wine

'Cause you were never mine

Back when we were still changin' for the better

Wanting was enough

For me, it was enough

To live for the hope of it all

Cancel plans just in case you'd call

And say, "Meet me behind the mall"

So much for summer love and saying "us"

'Cause you weren't mine to lose

You weren't mine to lose, no

But I can see us lost in the memory

August slipped away into a moment in time

'Cause it was never mine

And I can see us twisted in bedsheets

August sipped away like a bottle of wine

'Cause you were never mine

'Cause you were never mine, never mine

But do you remember?

'Remember when I pulled up and said, "Get in the car"

And then canceled my plans just in case you'd call?

Back when I was livin' for the hope of it all, for the hope of it all

"Meet me behind the mall"

Remember when I pulled up and said, "Get in the car"

And then canceled my plans just in case you'd call?

Back when I was livin' for the hope of it all (For the hope of it all)

For the hope of it all

For the hope of it all

(For the hope of it all)

(For the hope of it all)

And here is how it looks:


text:
Q: Double or Square python function I have been trying to create a double or square function on python where the result is to give the user the biggest number back when doubling or squaring. The problem states:

double(x) returns 2 * x square(x) returns x**2 double_or_square(x) returns the larger number between double(x) and square(x)

My code so far has been:
def double(x):
    return (2 * x)
def square(x):
    return (x ** 2)
def double_or_square(x):
    return max(d, q)
d = double
q = square

I keep getting errors, what did I do wrong?

A: You weren't CALLING any of these functions.  Of course, the only integer where "double" will be larger is 1.
Do it like this:
def double(x):
    return 2 * x
def square(x):
    return x ** 2
def double_or_square(x):
    d = double(x)
    q = square(x)
    return max(d, q)
print( double_or_square( 2 ) )
print( double_or_square( 9 ) )


text:
Q: Finding the average rating of each movies SQL I'm currently taking the online standford class on databases, If you could help me solve this sql problem I would greatly appreciate it. Sorry I'm a complete noob.
Table Movie:
mID | title | year | director

Table Rating
rID | mID | stars | ratingDate

Table Reviewer
rID | name

For all pairs of reviewers such that both reviewers gave a rating to the same movie, return the names of both reviewers. Eliminate duplicates, don't pair reviewers with themselves, and include each pair only once. For each pair, return the names in the pair in alphabetical order.

A: Okay. You actually asked two different questions.
First, I'll answer the question you asked in the title of the post.
This should work.
select Movie.title, avg(Rating.stars) as AR from
Rating join Movie on Rating.mID = Movie.mID
group by Movie.title
order by AR desc

If you don't specify the "on" clause in the join, like this,
select Movie.title, avg(Rating.stars) as AR from
Rating join Movie
group by Movie.title
order by AR desc

then all movies will have the same rating, the global average, to due the full cross product of the join. You want an inner join on name or, in this case, id.
Second, here is the answer to the other question you asked, about pairs of reviewers. R1.name < R2.name ensures the reviewer names will be sorted left to right. and order by R1.name ensures those pairs will be sorted top to bottom.
select distinct R1.name, R2.name from
Rating Ra1 join Rating Ra2
join Reviewer R1 join Reviewer R2
where Ra1.mID = Ra2.mID and Ra1.rID != Ra2.rID
and R1.name < R2.name
and Ra1.rID = R1.rID and Ra2.rID = R2.rID
order by R1.name

A: This will get you started.
SELECT m.*, ra.*, re.*
FROM Movie m
JOIN Rating ra ON ra.mID = m.mID
JOIN Reviewer re ON re.rID = ra.rID

A: Maybe something like this:
SELECT rev.rID, rev.name, m.title
FROM [Reviewer] rev
   JOIN [Rating] rate ON rev.rID = rate.rID
   JOIN [Movie] m ON rate.mID = m.mID
   JOIN (
     SELECT mID
     FROM [Rating]
     GROUP BY mID
     HAVING COUNT(Distinct rID) > 1
   ) m2 on m.mID = m2.mID
ORDER BY rev.name

--EDIT
If you need to get the average as well:
SELECT rev.rID, rev.name, m.title, ar.avgRating
FROM [Reviewer] rev
   JOIN [Rating] rate ON rev.rID = rate.rID
   JOIN [Movie] m ON rate.mID = m.mID
   JOIN (
     SELECT mID
     FROM [Rating]
     GROUP BY mID
     HAVING COUNT(Distinct rID) > 1
   ) m2 on m.mID = m2.mID
   JOIN (
     SELECT mID, AVG(stars) as avgRating
     FROM [Rating]
     GROUP BY mID
   ) ar on m.mID = ar.mID
ORDER BY rev.name

And the SQL Fiddle.

A: Find the average rating per movie:
SELECT
    [m].[mID],
    [m].[title],
    AVG([r].[stars]) AS [AvgRating]
  FROM [Movie] [m]
  LEFT JOIN [Rating] [r] ON [m].[mID] = [r].[mID]
  GROUP BY
    [m].[mID],
    [m].[title]

Find the unique reviewers per movie:
SELECT
    [r].[mID],
    [v].[rID],
    [v].[name]
  FROM [Reviewer] [v]
  INNER JOIN [Rating] [r] ON [v].[rID] = [r].[rID]
  GROUP BY
    [v].[rID],
    [v].[name],
    [r].[mID]

Combine:
SELECT
  [rat].[mID],
  [rat].[title],
  [rev].[rID],
  [rev].[name],
  [rat].[AvgRating]
FROM
(
  SELECT
    [m].[mID],
    [m].[title],
    AVG([r].[stars]) AS [AvgRating]
  FROM [Movie] [m]
  LEFT JOIN [Rating] [r] ON [m].[mID] = [r].[mID]
  GROUP BY
    [m].[mID],
    [m].[title]
) AS [rat]
LEFT JOIN
(
  SELECT
    [r].[mID],
    [v].[rID],
    [v].[name]
  FROM [Reviewer] [v]
  INNER JOIN [Rating] [r] ON [v].[rID] = [r].[rID]
  GROUP BY
    [v].[rID],
    [v].[name],
    [r].[mID]
) AS [rev] ON [rat].[mID] = [rev].[mID]
ORDER BY
  [rat].[mID] ASC,
  [rev].[name] ASC

For a Fiddle, look here.

A: select distinct r2.name, r1.name
from
(select r1.rid, r1.mid, r2.name
from (select * from reviewer order by name) r2
join (select r1.rid, r1.mid from rating r1 join reviewer r2 on r1.rid = r2.rid order by r2.name) r1
on r2.rid = r1.rid
group by mid
order by r2.name) r1,
(select r1.rid, r1.mid, r2.name
from reviewer r2,
rating r1
where r1.rid = r2.rid)r2
where r1.rid <> r2.rid and r1.mid = r2.mID
order by r2.name, r1.name

A: I'm doing the same course and this is the answer I got:
SELECT DISTINCT name1, name2
FROM (SELECT R1.name AS name1, R2.name AS name2
FROM (Rating JOIN Reviewer using(rId)) AS R1,
(Rating JOIN Reviewer using(rId)) AS R2
WHERE R1.mId = R2.mId AND R1.rId <> R2.rId) AS Tuple
WHERE name1 < name2;

I don't know why OP talk about average on title, since this question don't ask for it.
EDIT: for further reference, here's the data: https://class.stanford.edu/c4x/DB/SQL/asset/moviedata.html


text:
Q: jQuery hide And fadeIn help?

Hello I'm one

Hello I'm two

Hello I'm three

Hello I'm four

Hello I'm five

Next

Previous

What i achieved here is when i click on lets say Next box1 hides and box2 fadesIn
then if i click Previous box2 hides and box1 fadesIn
but i have 5 boxes so what i want to achieve here is when i click Next box1 hides then box2
fadesIn then if i click Next again box2 hides then box3 fadesIn and so on until i reach box5
then the functionality of Previous has to work to, but i'm having a hard time doing this since i'ts been a long time since i stop coding but now i'm coming back again and the only thing that i can't remember is jquery since i was barely studying...
thanks for your help...! :)

A: You want to take advantage of classes being applied to more than one DOM node :)
HTML:

        Hello I'm one

        Hello I'm two

        Hello I'm three

        Hello I'm four

        Hello I'm five

Next  Prev

JQuery: (Edit: Added some selector caching and spam clicking prevention)
$('.box:first-child').fadeIn();

var _fading = false;

$('#next').click(function()
{
    if(_fading)
    {
        return false;
    }

    _fading = true;
    var _visible = $('.box:visible');

    if(_visible.next().length > 0)
    {
        _visible.fadeOut().next().fadeIn('slow',function()
        {
            _fading = false;
        });
    }
    else
    {
        _visible.fadeOut().siblings(':first-child').fadeIn('slow',function()
        {
            _fading = false;
        });
    }
});

$('#prev').click(function()
{
    if(_fading)
    {
        return false;
    }

    _fading = true;
    var _visible = $('.box:visible');

    if(_visible.prev().length > 0)
    {
        _visible.fadeOut().prev().fadeIn('slow',function()
        {
            _fading = false;
        });
    }
    else
    {
        _visible.fadeOut().siblings(':last-child').fadeIn('slow',function()
        {
            _fading = false;
        });
    }
});

Working Demo: http://jsfiddle.net/AlienWebguy/GvjKu/


text:
Q: Unknown column in 'where clause' while there`s no 'where clause' and the column isn`t mentioned in the query I`m new in SQL and now straggling with an error 1054 Unknown column in 'where clause' in MySQL.

*

*There`s a simple table 'customer_orders' with 3 columns 'order_id', 'staff_id' and 'order_total'

*I needed to insert a line. My query was
INSERT INTO customer_orders VALUES (25,1,10.50);

*First that worked, then I realized a need to delete the row and insert with a slight change

*Now it throws the error 'Error Code: 1054. Unknown column 'order_id' in 'where clause''
Theres no such column in the query and the column isnt mentioned.
I renamed the column into 'order_id_new' and explicitly specified the column names in the INSERT statement - the same error.

INSERT INTO customer_orders (order_id_new, staff_id, order_total) VALUES
(23,1,11.43);
When I created a copy of the table the same worked fine.
Any ideas what is wrong with the table?
Thanks in advance.

A: It turned out there was a Trigger which conflicted with the query. Strange that the error doesn`t refer to the trigger in any way. Once I fixed the trigger the query worked.


text:
Q: Selected state of tab bar icon in IOS 7 I'm having fun learning to build my first iPhone app and wonder if someone would kindly point me in the right direction.
I have basically added in custom icons for my tab bar (IOS 7). Now I want to add in a custom selected state icon for each of these. How would I do this?
Thanks
Shell

A: On iOS7 you should set selectedImage
tabBarItem.selectedImage = selectedImage;
tabBarItem.image = unselectedImage;

Keep in mind that selectedImage is not available in iOS6.
Use – setFinishedSelectedImage:withFinishedUnselectedImage: if you have to support iOS6.

A: Here is the swift solution based on @MrAlek's solution, create a custom UITabBarItem
import UIKit

@IBDesignable
class YourTabBarItem: UITabBarItem {

    @IBInspectable var selectedImageName:String!{
        didSet{
            selectedImage = UIImage(named: selectedImageName)
        }
    }
}

and in interface builder, change the class of the tab bar item and you will see the Selected Image Name attribute, just specify your selected image name there. I reckon @IBInspectable is using the runtime attribute.

A: See my more complete answer at https://stackoverflow.com/a/20007782/1755055
Often your tab will have a Navigation Controller stack, so you will need the following
- (void)viewDidLoad
{
    [super viewDidLoad];

...

    [self.navigationController.tabBarItem setSelectedImage:[UIImage imageNamed:@"MySelectedIcon.png"]];

}

If you only have one view controller in the tab without the UINavigationController wrapper, you would use
[self.tabBarItem setSelectedImage:[UIImage imageNamed:@"MySelectedIcon.png"]];

A: As of Xcode 6, you can do this by default in Interface Builder. No need for any custom subclasses or categories as before.

A: Use like below and its solve the image issue in iOS7:
[self.navigationController.tabBarItem setSelectedImage:[[UIImage imageNamed:@"MySelectedIcon.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];

A: You can user sub method to init a tabBarItem.
-(instancetype)initWithTitle:(NSString *)title image:(UIImage *)image selectedImage:(UIImage *)selectedImage


text:
Q: How could I find the percentage of customers who made a transaction in the first 90 days of enrolling as a store member? I am trying to find the PERCENTAGE of customers who have made a purchase in the first 90 days of becoming store benefit members. I've initially tried writing two separate queries and then performed my calculations from there, but I would like to have it in one query if possible (I'm still new to SQL). I want to compare this over time, so I've been including the benefits enrollment date as well.
I am using Amazon Redshift.
I've tried writing two separate queries, but I want to combine them if possible.
/*
* Numerator (counting customers with purchases within 90 days of becoming members)
*/
SELECT
    c.customer_id,
    c.member_start
FROM
     (SELECT * FROM before_2012_data
      UNION ALL
      SELECT  * FROM after_2012_data
     ) t
     LEFT JOIN customer_information c
     ON c.customer_id = t.customer_id
WHERE DATEDIFF(day, c.member_start, t.purchase_data) between 0 and 90
GROUP BY  member_start, c.customer_id
ORDER BY member_start

/*
* Denominator (counting customers both with and without purchases within 90 days of becoming members)
*/
SELECT
  c.customer_id,
  c.member_start
FROM
     (SELECT * FROM before_2012_data
      UNION ALL
      SELECT  * FROM after_2012_data
     ) t
     LEFT JOIN customer_information c
     ON c.customer_id = t.customer_id
GROUP BY  member_start, c.customer_id
ORDER BY member_start

A: You may use conditional aggregation with a single query:
SELECT
    c.customer_id,
    c.member_start,
    100.0 * COUNT(CASE WHEN DATEDIFF(day, c.member_start, t.purchase_data)
                            BETWEEN 0 AND 90 THEN 1 END) / COUNT(*) AS percentage
FROM
(
    SELECT * FROM before_2012_data
    UNION ALL
    SELECT * FROM after_2012_data
) t
LEFT JOIN customer_information c
    ON c.customer_id = t.customer_id
GROUP BY
    c.customer_id,
    c.member_start
ORDER BY
    c.member_start;

A: Hoping, I understood your question correctly. you can check below query.
SELECT
    count(case when DATEDIFF(day, c.member_start, t.purchase_data) between 0 and 90  then t.customer_id end) / NULLIF(count(t.customer_id),0)
FROM
     (SELECT * FROM before_2012_data
      UNION ALL
      SELECT  * FROM after_2012_data
     ) t
     LEFT JOIN customer_information c
     ON c.customer_id = t.customer_id;


text:
Q: Magento 2 admin form save button not working in custom module Magento 2 i have created admin grid and form. when i am trying to add new data save button not working
add new->new form ->save and continue , save both not wokring
below is my code
  <?php
namespace MagePsycho\Customshipping\Block\Adminhtml\Zipcodes;

use Magento\Backend\Block\Widget\Form\Container;

class Edit extends Container
{
    /**
     * Core registry
     *
     * @var \Magento\Framework\Registry
     */
    protected $_coreRegistry = null;

    /**
     * @param \Magento\Backend\Block\Widget\Context $context
     * @param \Magento\Framework\Registry $registry
     * @param array $data
     */
    public function __construct(
        \Magento\Backend\Block\Widget\Context $context,
        \Magento\Framework\Registry $registry,
        array $data = []
    ) {
        $this->_coreRegistry = $registry;
        parent::__construct($context, $data);
    }

    /**
     * Department edit block
     *
     * @return void
     */
    protected function _construct()
    {
        $this->_objectId = 'zip_id';
        $this->_blockGroup = 'MagePsycho_Customshipping';
        $this->_controller = 'adminhtml_zipcodes';

        parent::_construct();

        if ($this->_isAllowedAction('MagePsycho_Customshipping::zipcodes_save')) {
            $this->buttonList->update('save', 'label', __('Save'));
            $this->buttonList->add(
                'save_and_continue',
                [
                    'label' => __('Save and Continue Edit'),
                    'class' => 'save',
                    'data_attribute' => [
                        'mage-init' => [
                            'button' => ['event' => 'saveAndContinueEdit', 'target' => '#edit_form'],
                        ],
                    ]
                ],
                -100
            );
        } else {
            $this->buttonList->remove('save');
        }

    }
    /**
     * Get header with Department name
     *
     * @return \Magento\Framework\Phrase
     */
    public function getHeaderText()
    {
        if ($this->_coreRegistry->registry('deliveryzipcodes_data')->getZipId()) {
            return __("Edit Department '%1'", $this->escapeHtml($this->_coreRegistry->registry('deliveryzipcodes_data')->getZipId()));
        } else {
            return __('New Department');
        }
    }

    /**
     * Check permission for passed action
     *
     * @param string $resourceId
     * @return bool
     */
    protected function _isAllowedAction($resourceId)
    {
        return $this->_authorization->isAllowed($resourceId);
    }
    /**
     * Getter of url for "Save and Continue" button
     * tab_id will be replaced by desired by JS later
     *
     * @return string
     */
    protected function _getSaveAndContinueUrl()
    {
        return $this->getUrl('zips/*/save', ['_current' => true, 'back' => 'edit', 'active_tab' => '']);
    }

}
?>

below is form file
    <?php
namespace MagePsycho\Customshipping\Block\Adminhtml\Zipcodes\Edit;

use \Magento\Backend\Block\Widget\Form\Generic;

class Form extends Generic
{
    /**
     * @var \Magento\Store\Model\System\Store
     */
    protected $_systemStore;

    /**
     * @param \Magento\Backend\Block\Template\Context $context
     * @param \Magento\Framework\Registry $registry
     * @param \Magento\Framework\Data\FormFactory $formFactory
     * @param \Magento\Store\Model\System\Store $systemStore
     * @param array $data
     */
    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Framework\Registry $registry,
        \Magento\Framework\Data\FormFactory $formFactory,
        \Magento\Store\Model\System\Store $systemStore,
        array $data = []
    ) {
        $this->_systemStore = $systemStore;
        parent::__construct($context, $registry, $formFactory, $data);
    }

    /**
     * Init form
     *
     * @return void
     */
    protected function _construct()
    {
        parent::_construct();
        $this->setId('deliveryzipcodes_form');
        $this->setTitle(__('Delivery Zipcode Information'));
    }

    /**
     * Prepare form
     *
     * @return $this
     */
    protected function _prepareForm()
    {
        /** @var \Maxime\Jobs\Model\Department $model */
        $model = $this->_coreRegistry->registry('deliveryzipcodes_data');

        /** @var \Magento\Framework\Data\Form $form */
        $form = $this->_formFactory->create(
            ['data' => ['zip_id' => 'edit_form', 'action' => $this->getData('action'), 'method' => 'post']]
        );

        $form->setHtmlIdPrefix('department_');

        $fieldset = $form->addFieldset(
            'base_fieldset',
            ['legend' => __('General Information'), 'class' => 'fieldset-wide']
        );
        if ($model->getId()) {
            $fieldset->addField('entity_id', 'hidden', ['name' => 'entity_id']);
        }

        $fieldset->addField(
            'zip_code',
            'text',
            ['name' => 'zip_code', 'label' => __('Zip Code'), 'title' => __('Zip Code')]
        );

        $fieldset->addField(
            'weekday_price',
            'text',
            ['name' => 'weekday_price', 'label' => __('Weekday Price'), 'title' => __('Weekday Price')]
        );
        $fieldset->addField(
            'weekend_price',
            'text',
            ['name' => 'weekend_price', 'label' => __('Weekend Price'), 'title' => __('Weekend Price')]
        );
        $fieldset->addField(
            'workwave_zips',
            'checkbox',
            ['name' => 'workwave_zips', 'label' => __('Workwave'), 'title' => __('Workwave'),'onchange' => 'this.value = this.checked;']
        );
        $fieldset->addField(
            'thirdparty_zips',
            'checkbox',
            ['name' => 'thirdparty_zips', 'label' => __('Thirdparty'), 'title' => __('Thirdparty'),'onchange' => 'this.value = this.checked;']
        );

        $form->setValues($model->getData());
        $form->setUseContainer(true);
        $this->setForm($form);

        return parent::_prepareForm();
    }
}

A: Please check this post for Admin Grid CRUD In Magento 2 : https://www.magetop.com/blog/admin-grid-crud-in-magento/


text:
Q: Should one account for absolute precision producing variable number of significant digits in a dependent variable measurement? If so how? Sometimes data for a variable are available in absolute precision, which can create different numbers of significant digits. For example, the CDC's estimates of state prevalences and incidence rates of HIV diagnoses report figures to a single decimal place of absolute precision, rather than, for example three significant digits (relative precision). For example, in 2017, the CDC reports that Alabama's prevalence* was 15.9 HIV diagnoses per 100,000 persons age 13+, but reports Alaska's prevalence was 4.8 HIV diagnoses per 100,000 persons age 13+. Alabama's measurement is thus using 3 significant digits, and Alaska's is using 2 significant digits** (contrast the value 4.8 with a value like 4.81, or 4.77).
Suppose I was modeling annual state prevalences of HIV diagnoses, say in a regression context:

*

*Should I account for the resulting variability in significant digits? (What bias emerges in my estimates and inference if I do not?)

*How? (I suppose I could truncate all figures to 2 significant digits, for example, rounding Alabama's 2017 prevalence to 16, but that necessarily discards information, decreasing precision. Are there alternatives I should consider?)
Bonus consideration: The distribution of values of the most significant digit of the CDC's figures skews strongly rightward, with most values being 0 or 1, some values being 2, and very few values being 3 or 5. Does this affect how I interpret any risk of bias in question (1) above?
NB: This is not a question about measurement error in a dependent variable in general—I am not asking about accounting for the reliability of the dependent variable figures generally.

* Actually, what the CDC terms "prevalence" the epidemiology textbooks I am familiar with term "count of prevalent cases," and what the CDC terms "prevalence rate" the epidemiology textbooks I am familiar with term "prevalence". I side strongly with the latter nomenclature, as "rate" means change (usually over time), but prevalences are static measures by definition (although one may certainly measure change in prevalence over time, that is not what the reported measures are), thus "prevalence rate" lands as an oxymoron to me.
** Assuming for the moment that Alaska's value in 3 significant digits is not actually 4.80.

References
CDC. (2018) Diagnoses of HIV Infection in the United States and Dependent Areas, 2017 (see Table 26).

A: Alabama's total 2010 population was about 4.8 million. Let's say 4 million age 13+. 15.9 diagnoses per 100,000 then comes to 636 diagnoses. If these are rare, Poisson-distributed events then the standard deviation in that number is about 25 diagnoses, about 4% of the total.* Corresponding error in the value of 15.9 is about $\pm 0.6$
Alaska's total 2010 population was about 700,000. Let's say 600,000 age 13+. At 4.8 diagnoses per 100,000 that's about 29 diagnoses total. Under the above assumptions, the standard deviation in that number is about 5 diagnoses, or 17% of the mean. Corresponding error in the value of 4.8 is about $\pm 0.8$.
Those inherent errors arising from counts of rare events would seem to
overwhelm any issue you might fear in terms of the numbers of significant digits of the reported values. For those two examples, at least, the truncation to a single decimal digit seems to represent the inherent errors pretty well.

*One could argue that almost all HIV cases are captured in the data, so it's not fair for this argument to assume that there is some broader population from which the cases are being sampled. This illustration would be for a hypothetical case where there is a large number of Alabamas with the same overall mean HIV prevalence; among such a set of Alabamas that would be the standard deviation among their prevalence values.