text:
Q: Why 0 results on "where not in" query mysql> show columns in m like 'fld';
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| fld   | varchar(45) | YES  | MUL | NULL    |       |
+-------+-------------+------+-----+---------+-------+
1 row in set (0.02 sec)

mysql> show columns in i like 'fld';
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| fld   | varchar(45) | YES  | MUL | NULL    |       |
+-------+-------------+------+-----+---------+-------+
1 row in set (0.02 sec)

mysql> select count(distinct fld) from i;
+---------------------+
| count(distinct fld) |
+---------------------+
|               27988 |
+---------------------+
1 row in set (0.03 sec)

mysql> select count(distinct fld) from m;
+---------------------+
| count(distinct fld) |
+---------------------+
|               72558 |
+---------------------+
1 row in set (0.07 sec)

The above results seem reasonable based on what I know of the tables in question.
mysql> select count(*) from m where fld not in (select fld from i);
+----------+
| count(*) |
+----------+
|        0 |
+----------+
1 row in set (0.11 sec)

That last result does not seem reasonable. There must be some rows in m with fld not in i! Can someone please explain why I get 0 as the result?

For completeness (because I suspect it may be relevant), I'll also paste this result:
mysql> select count(*) from m where fld is null;
+----------+
| count(*) |
+----------+
|        0 |
+----------+
1 row in set (0.00 sec)

Edit: In reply to comments, I'm editing in the following info also, in case it helps someone answer my question:

*

*select count(*) from m join i using (fld) yields 9350; with left join, 73087; with right join, 28872.

*select count(*) from i where fld is null yields 810.

A: I've now figured it out. The documentation reads:

To comply with the SQL standard, IN returns NULL not only if the expression on the left hand side is NULL, but also if no match is found in the list and one of the expressions in the list is NULL.

Thus, fld not in (i.e. not fld in) returns not null (i.e. null) whenever there's a null in the derived table (which there is here) and fld isn't found in the derived table (which is what I'm testing for).

There may be a better workaround than this, but I'm using (select fld from i where fld is not null).


text:
Q: Visual Studio Code no longer jumps to errors in terminal with control click Previously I've been able to jump to the error after running a program by control clicking on the error in the terminal window, but seemingly on restart this feature has gone away. Is this a setting I've messed with somewhere by accident or a key bind?
Update 1:
When control + hovering it gives the 'search project for' option
that just searches the code for the individual word as a string. I checked my settings using the preferences -> modified preferences and reset them with no change.

A: Add the following lines in settings.json file
"window.restoreWindows": "none"

redpajama_set_name: RedPajamaStackExchange


text:
Q: OpenCV, C++ cvCaptureFromFile not working but Python VideoCapture is Im working with some legacy code that I need to use, as well as do some work in Python.  I am able to read from file in Python but not in C++.  Here is the C++ code
int main(int argc, char** argv) {

  CvCapture *capture = NULL;

  capture = cvCaptureFromFile("path/to/foo.mov");
  if (!capture) {
    std::cerr << "Cannot open " << "path/to/foo.mov" <<   std::endl;
    return 1;
  }
  return 0;
}


text:
Q: Smartforms trigger new page for given condition I have prepared a smart form, which has a table in main window. So there can be hundreds of lines in the table. What I want to do is to trigger new page for every 10 records.
I'have resized the main window to height that at most 10 records are fit and selected the new page  tick in command. It is kind of working but I want to do this programatically.
Like;
if count % 10 = 0
then GO_TO_NEW_PAGE

How can I do this ?

A: You should be able to trigger a Dynamic Page Break using a Command Node. I haven't tried what this does to the table header / footer though...


text:
Q: How can I use reactJS within SpringBoot project? I am a Java developer trying to use ReactJS to present the data I am getting back from a rest API, I read different posts about the need of installing browserify to compile the jsx files, etc but ran into some issues during the installation process

"Error: 140737135018944:error:14077410:SSL
  routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure"

and was wondering if there is a simple way to make things running without the need of installing anything extra, The way that things are explained in different blogs is targeting someone who has a frontend experience and I don't have that knowledge to know if there is something missing, I kept trying to solve the issue but ended up in a rabbit hole, Anyway here is what I have and I hope that I can get a layman answer to make this project up and running. Fell free to ask me any questions, I would be happy to provide more details if necessary !!
I have a file called WeatherBoard.jsx which imports other react components but I am getting this error

Uncaught SyntaxError:
  http://localhost:8080/demo/js/WeatherManager.jsx: Unexpected token
  (54:2)   52 |             );   53 |         }

54 | });
         |   ^   55 |    56 | // Render    57 | ReactDOM.render(  ,
        at Parser.pp.raise (browser.min.js:41)
        at Parser.pp.unexpected (browser.min.js:42)
        at Parser.pp.expect (browser.min.js:42)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html >

 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css" />
 <link rel="stylesheet" type="text/css" href="css/neo.css">

 <title>Weather </title>

var Wind=require(['Wind'],
Sys=require(['Sys'],
Main=require(['MAin'],
Coord=require(['Coord'],
WeatherManager= React.createClass({

 getInitialState: function() {

   var weather={};

   return {
    weather
   };

  },
  componentDidMount() {
      fetch('http://localhost:8080/demo/async/weatherInCity')
             .then(result=>result.json())
             .then(weather=>this.setState({weather}));
  },
  render: function() {
   return(

     City : {this.state.weather.name}

     Date :  {this.state.weather.dt}

     Cod  : {this.state.weather.cod}

     Visibility : {this.state.weather.visibility}

     Base : {this.state.weather.base}

     Id : {this.state.weather.id}

     Sys :
     <Sys sys={this.state.weather.sys}/>

     Wind :
     <Wind wind={this.state.weather.wind}/>

     Coord :
     <Coord coord={this.state.weather.coord}/>

      Main :

);
  }
});

// Render
ReactDOM.render( <WeatherManager /> ,
  document.getElementById('main')
);

Here is an example of one of the components :

var WeatherManager= React.createClass({
 render: function() {
  var wind=this.props.wind;
  if(wind){
   return(

    Wind Speed : {wind.speed}

    Wind deg   : {wind.deg}

    Wind gust  : {wind.gust}

);
  }else{
   return(

   No data available

);
  }

 }
});


text:
Q: Twilio Phone Calling - Fetch User's Keypad Input from a node.js application (not web server) const args = message.content.split(' ')
const phNumber = args[1]
const ttsMessage = args.slice(2).join(' ')

            if (phNumber) {
                // Call phNumber and say ttsMessage and collect keypad input code
                const call = await TwilioClient.calls.create({
                    url: 'http://demo.twilio.com/docs/voice.xml',
                    to: phNumber,
                    from: process.env.TWILIO_PHONE_NUMBER,
                })
            }

           // somehow get the input the user entered and do something with it here. Maybe by using await or Promises etc...

I want to get the number the user entered and do some stuff with it!

A: When you create a call resource in the Twilio API, it will initiate a phone call between the two numbers you specified, and also send a webhook request to the url you specified.
This url should point to your webserver where you can handle the webhook request and respond with TwiML instructions. These instructions are how you manage the phone call. One of the TwiML verbs is <Gather> where you can ask for input using DTMF (digits on the phone dialer) or voice.
The user response will be posted back to you with another webhook request, this time to the URL specified in the action attribute from the <Gather> verb.
You cannot provide TwiML instructions using the Twilio API or get the input back, you have to use webhooks.
It's not easy, but you technically could use a websocket connection (or some other way of communication) to connect your webhook server and your node.js app, so that your webhook server can stream the data to your node.js app, and your node.js app could send information back. This way you could exchange information from the call in realtime between the node.js app that created the call, and the webhook server that is managing the call.
I recommend checking out this tutorial on responding to phone calls using node.js.


text:
Q: FFMpeg Cygwin Compilation I'm trying to compile ffmpeg with the following:
./configure --disable-stripping --enable-debug=3 --extra-cflags="-g" --disable-optimizations

However, I'm getting an undefined reference to GUID_NULL:
$ make
LD      ffmpeg_g.exe
/usr/lib/gcc/x86_64-pc-cygwin/9.3.0/../../../../x86_64-pc-cygwin/bin/ld: libavdevice/libavdevice.a(dshow_enummediatypes.o):dshow_enummediatypes.c (.rdata$.refptr.GUID_NULL[.refptr.GUID_NULL]+0x0): undefined reference to `GUID_NULL'
collect2: error: ld returned 1 exit status
make: *** [Makefile:114: ffmpeg_g.exe] Error 1

However, my libavdevice.pc reads:
prefix=/usr/local
exec_prefix=${prefix}
libdir=/usr/local/lib
includedir=/usr/local/include

Name: libavdevice
Description: FFmpeg device handling library
Version: 58.11.101
Requires: libavfilter >= 7.87.100, libswscale >= 5.8.100, libavformat >= 58.48.100, libavcodec >= 58.96.100, >Requires.private:
Conflicts:
Libs: -L${libdir}  -lavdevice -lpsapi -lole32 -lstrmiids -luuid -loleaut32 -lshlwapi -lgdi32 -lm -lvfw32 -lxc>Libs.private:
Cflags: -I${includedir}

Note the libs line is cut off by nano, but includes -luuid. Any ideas?

A: Added an ff_GUID_NULL define to the following and it compiles and runs fine.
libavdevice/dshow_enummediatypes.c:
#include "dshow_capture.h"

DECLARE_QUERYINTERFACE(libAVEnumMediaTypes,
    { {&IID_IUnknown,0}, {&IID_IEnumMediaTypes,0} })
DECLARE_ADDREF(libAVEnumMediaTypes)
DECLARE_RELEASE(libAVEnumMediaTypes)
DEFINE_GUID(ff_GUID_NULL, 0x00000000,0x0000,0x0000,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00);

A: I met the same problem. Yes, GUID_NULL is alread defined in the cguid.h, so define a new GUID_NULL_N  DEFINE_GUID(GUID_NULL_N, 0x00000000,0x0000,0x0000,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00) in the libavdevice/dshow_enummediatypes.c to substitute the GUID_NULL.


text:
Q: Why is the the permeability of a ferromagnetic material given as B/H not it's slope dB/dH? I was going through my Electromagentics book by Sadiku where it was mentioned as a point that permeability of ferromagnetic material is given by the ratio of B(magnetic flux density) to H(magnetic field intensity) and not by the slope dB/dH at a point in the magnetisation or B-H curve.
I am not able to understand why the permeability is given as B/H at a point and not the slope(dB/dH) of B-H curve at a particular point?

A: When you buy magnetic materials you usually buy it based on a single permeability number, and for "soft" materials (materials that don't have significant hysteresis) you can get away with designing based on a single permeability number, too.
I think the book is a bit over the top on saying that \$\mu\$ should always be taken as \$B/H\$.  There are times when you need to use \$dB/dH\$, and if you're working with hard magnetic materials (i.e., materials that have significant hysteresis) there are times when \$dB/dH\$ is not only a function of \$B\$ or \$H\$, but also a function of the direction that you're going on the curve.
However, that's your book (and to some extent that's the terminology that the field uses), so you need to go with the flow.
Easy: \$\mu\$ is constant, or nearly so.  This is true for most soft magnetic materials in most applications.
Harder but even with soft materials, \$dB/dH\$ is often different for large swings in \$H\$ (because the material saturates) or for small swings of \$H\$ around a point (because even soft magnetic materials have some hysteresis).
Harder yet

*

*Some "soft" materials are intentionally operated well into saturation.  There's a thing called a "magnetic amplifier" that uses the fact that a core driven to saturation will have a lower \$dB/dH\$ around a point.

*Any time that a magnetic material is used for storage you're using a hard (but not too hard) material, and purposely magnetizing it.  This is the basis of magnetic media like disk drives, and in an earlier time, core memory.  There's a lot of materials science and physical knowledge that goes into making this work.

*Rare earth magnets have a really big \$\mu\$ if you take \$\mu = B/H\$ as the magnet is shipped.  But, as magnetized, if you're not subjecting it to a strong enough \$H\$ to demagnetize it, \$dB/dH \simeq \mu_0\$ -- i.e., to a magnetic circuit it looks like a chunk of air that generates a very strong \$H\$ field.

The best thing to do here (and any time that terminology is vague) is to, first, be aware that your \$\mu\$ may not be my \$\mu\$, second, don't be afraid to ask, and third, if you're using something other than what's standard for the field, be sure to clarify your terms (i.e., start by saying "when I say 'effective permeability' I mean ...").

A: Magnetic permeability is usually a constant for most materials. For these materials you use one parameter to describe the material.
\$ \frac{B}{H}=\mu\$

Source: https://en.wikipedia.org/wiki/Permeability_(electromagnetism)
Edit: The statement in the book is not wrong, but confusing.
The derivative of a constant is zero, so looking at the rate of change of magnetic permeability would not be useful.
In materials that have a changing magnetic permeability you can use incremental permeability to describe change in the material. In some materials, they also have memory/ hysteresis between B and H, it is then more useful to look the rate of change between B and H:
\$ \frac{\Delta B}{\Delta H}=\mu_{\Delta}\$

Source: https://www.codecogs.com/library/physics/magnetism/magnetic-hysteresis.php


text:
Q: Laravel mix: config to convert images to base 64 I'm looking for some pointers on how to set up Laravel mix to find image assets under a certain threshold size and recode them in the stylesheet as Base 64 strings. I can achieve this with Webpack using url-loader, but I'm struggling to get the config working in my Mix config. What I've tried:
const mix = require('laravel-mix');

mix.setPublicPath('public_html/');
mix.js('resources/uxmaps/js/app.js', 'uxmaps/js/app.js').version()
.webpackConfig({
        module: {
            rules: [
{
                test: /\.(png|jpg|gif)$/i,
                use: [
                  {
                    loader: 'url-loader',
                    options: {
                      limit: 8192,
                        outputPath: 'images'
                    },
                  },
                ],
}
            ]
        }
    })
   .sass('resources/sass/app.scss', 'css/main.css')

This compiles without errors, and yet it simply doesn't work; my background image in my sass file for example background-image: url(/assets/logo.jpg); (3kb) remains as-is in the ouputted css.
Secondly, I have also tried separating out the url-loader part of the config into a separate file (imported module) as per the mix docs: https://laravel-mix.com/docs/5.0/extending-mix (see 'Usage' section at the bottom). Same result: it compiles without errors, but simply doesn't work.
Finally, I have also tried doing this with this Post CSS plugin but on compilation it was giving me errors relating to dependency versions (I think this is outdated now).
Any pointers as to why this code isn't working properly, or otherwise any other ways to convert images to inline Base 64 with Laravel mix ?
Thanks
EDIT
I discovered that I was using absolute paths for the image, and therefore Mix was ignoring them, as per the docs. If I change to a relative path, then Mix outputs the css as background-image: url(/images/logo.jpg?dab783c3f2e3b389830733b050848c8a); and- get this- url-loader takes the jpg file, and gives me a file called 'logo.jpg' in a public_html/images folder, which isn't a jpg at all, but a text file containing Base64 code.... :/
How do I get that Base 64 code to be written into the stylesheet?!

A: mix.override(function (webpackConfig) {})

... will be triggered once the webpack config object has been fully generated by Mix.
Maybe here try to remove their file-loader and add yours setup.


text:
Q: newbie: php preg_match_all not working as expected i'm trying to parse tags from a string like the following:
$string = "foo [cmd:tag1] bar [cmd:tag2] bla bla";
$pattern = "/\[cmd:(.+)\]/";
preg_match_all($pattern, $string, $matches, PREG_OFFSET_CAPTURE);
$rc = $matches[0];
foreach($rc as $tag)
{
    print_r2($tag);
}

which will return:
Array
(
    [0] => [cmd:tag1] bar [cmd:tag2]
    [1] => 4
)

what is wrong in my syntax as i'm expecting the following result:
Array
(
    [0] => [cmd:tag1]
    [1] => [cmd:tag2]
)

thanks

A: \[cmd:(.+?)\]

or use
\[cmd:([^\]]*)\]

Make your quantifier * non greedy by putting ? ahead of it.
See demo.
https://regex101.com/r/fA6wE2/23


text:
Q: How can I use loop to update formula for forward selection Good afternoon.
I am constructing loops for forward variable selection. At each step, I am sequentially adding one more terms in the dynlm regression and see which variable among explanatory variables yields the best in terms of maximizing rsquared. Since I have 100 explanatory variables, I have 100 models at most, and want to store residuals of each model so that I can compare which one of 100 models has the lowest AIC, BIC (by hand)
So far What I've accomplished is
### M0 (Null Model)
fm0 <- tr.y.nm[,1]~L(tr.y.nm[,1],1:4) #AR(4) model

r0 <- summary(dynlm(fm))$r.squared

### loop to choose M1 ~ M100 with forward selection
fml <- vector("list", 100)

r <- rep(0, 100)

ssr <- rep(0,100)

rr <- matrix(c(1:100, 1:100), nrow=100,ncol=100) # 100 by 100

x <- rep(0,100) # index to indicate which regressor should be added when selecting best model

### M1
for (i in 1:ncol(tr.x.nm)){
  fml[[1]] <- update(fm0, .~. + L(tr.x.nm[,i], 0:1), evaluate=F)
  model <- dynlm(fml[[1]])
  rr[i,1] <- summary(model)$r.squared
}
x[1] <- which.max(rr[,1])
ssr[1] <- sum(model$resid^2, na.rm=T)

### M2
for (i in 1:ncol(tr.x.nm)){
  fm <- fml[[1]]
  fml[[2]] <- update(fm, .~. + L(tr.x.nm[,x[[1]]], 0:1), evaluate=F)
  model <- dynlm(fml[[2]])
  rr[i,2] <- summary(model)$r.squared
}
x[2] <- which.max(rr[,2])
ssr[2] <- sum(model$resid^2, na.rm=T)

### M3
for (i in 1:ncol(tr.x.nm)){
  fm <- fml[[2]]
  fml[[3]] <- update(fm, .~. + L(tr.x.nm[,x[[2]]], 0:1), evaluate=F)
  model <- dynlm(fml[[3]])
  rr[i,3] <- summary(model)$r.squared
}
x[3] <- which.max(rr[,3])
ssr[3] <- sum(model$resid^2, na.rm=T)

# M4
for (i in 1:ncol(tr.x.nm)){
  fm <- fml[[3]]
  fml[[4]] <- update(fm, .~. + L(tr.x.nm[,x[[3]]], 0:1), evaluate=F)
  model <- dynlm(fml[[4]])
  rr[i,4] <- summary(model)$r.squared
  }
x[4] <- which.max(rr[,4])
ssr[4] <- sum(model$resid^2, na.rm=T)

fml is a list of 100, which I want to store formulas that will be used at each model.
e.g. > head(fml)
[[1]]
tr.y.nm[, 1] ~ L(tr.y.nm[, 1], 1:4) + L(tr.x.nm[, i], 0:1)

[[2]]
tr.y.nm[, 1] ~ L(tr.y.nm[, 1], 1:4) + L(tr.x.nm[, i], 0:1) +
L(tr.x.nm[, x[[1]]], 0:1)

[[3]]
tr.y.nm[, 1] ~ L(tr.y.nm[, 1], 1:4) + L(tr.x.nm[, i], 0:1) +
L(tr.x.nm[, x[[1]]], 0:1) + L(tr.x.nm[, x[[2]]], 0:1)

[[4]]
tr.y.nm[, 1] ~ L(tr.y.nm[, 1], 1:4) + L(tr.x.nm[, i], 0:1) +
L(tr.x.nm[, x[[1]]], 0:1) + L(tr.x.nm[, x[[2]]], 0:1) + L(tr.x.nm[,
x[[3]]], 0:1)

Considering this, since M2 ~ M100 model is adding one more term from M1~M99, respectively
I'd like to use loop something like the follow
    for (j in 2:100) {
     for (i in 1:ncol(tr.x.nm)){
       fm <- fml[[j-1]]
       fml[[j]] <- update(fm, .~. + L(tr.x.nm[,x[j-1]], 0:1), evaluate=F)
       model <- dynlm(fml[[j]])
       rr[i,j] <- summary(model)$r.squared
       }
    x[j] <- which.max(rr[,j])
   }

However, j is not identified in the above loop and since 4th index, the output is the same as the previous one, not working.
> fml
[[1]]
tr.y.nm[, 1] ~ L(tr.y.nm[, 1], 1:4) + L(tr.x.nm[, i], 0:1)

[[2]]
tr.y.nm[, 1] ~ L(tr.y.nm[, 1], 1:4) + L(tr.x.nm[, i], 0:1) +
    L(tr.x.nm[, x[j - 1]], 0:1)

[[3]]
tr.y.nm[, 1] ~ L(tr.y.nm[, 1], 1:4) + L(tr.x.nm[, i], 0:1) +
    L(tr.x.nm[, x[j - 1]], 0:1)

[[4]]
tr.y.nm[, 1] ~ L(tr.y.nm[, 1], 1:4) + L(tr.x.nm[, i], 0:1) +
    L(tr.x.nm[, x[j - 1]], 0:1)

I guess indexing with j is not working, and don't know why. How can I index list with letter j whose value is defined before?

A: Actually I succeeded in running the loop but it takes too long for the loop to complete. I believe sapply or lappy will be more efficient but dont know how to modify my code.
for (j in 2:100){
  for (i in 1:ncol(tr.x.nm)){
    fm <- update(fm0,.~.+L(tr.x.nm[,i], 0:1))
    scope <- paste0("L(tr.x.nm[,x[", 1:(j-1), "]],0:1)")
    fit<-fml[[j]]<- update.formula(fm, paste(".~. +", paste(scope, collapse="+")))
    model <- dynlm(fit)
    rr[i,j] <- summary(model)$r.squared
    }
  x[j] <- which.max(rr[,j])
  ssr[j] <-sum(model$resid^2, na.rm=T)
}


text:
Q: Python - can a dict have a value that is a list? When using Python is it possible that a dict can have a value that is a list?
for example, a dictionary that would look like the following (see KeyName3's values):
{
keyName1 : value1,
keyName2: value2,
keyName3: {val1, val2, val3}
}

I already know that I can use 'defaultdict' however single values are (understandably) returned as a list.
The reason I ask is that my code must be generic so that the caller can retieve single key values as an item (just like from a dict key-value) and not as list (without having to specify pop[0] the list) - however also retrieve multiple values as a list.
If not then any suugestions would be welcome.
If someone can help then that would be great.
Thanks in Advance,
Paul
*I'm using Python 2.6 however writing scripts that must also be forward compatible with Python 3.0+.

A: Yes, it's possible:
d = {}
d["list key"] = [1,2,3]
print d

output:
{'list key': [1, 2, 3]}

A: Yes. The values in a dict can be any kind of python object. The keys can be any hashable object (which does not allow a list, but does allow a tuple).
You need to use [], not {} to create a list:
{ keyName1 : value1, keyName2: value2, keyName3: [val1, val2, val3] }

A: It definitely can have a list and any object as value but the dictionary cannot have a list as key because the list is mutable data structure and keys cannot be mutable else of what use are they.


text:
Q: Python Pandas: How do I average ONLY the data >1000 from several columns? I am new to pandas. I just want to average the revenue from Revenue1 to Revenue3 that are > 1000. Thank you!
Input:
|Name | Revenue1| Revenue2|  Revenue3|
|Peter| 1000    | 2000    |  3000    |
|Jane | 9000    | 10000    |  5000    |

Desired Output:
| Name  | Average |
| Peter | 2500    |
| Jane  | 8000    |

Peter =average (2000+ 3000) = 2500
Jane =average (9000+ 10000 +5000) = 8000

A: Try via filter(),gt() and mean():
out=df.filter(like='Revenue')
df['Average']=out[out.gt(1000)].mean(axis=1)

output of df:
    Name    Revenue1    Revenue2    Revenue3    Average
0   Peter   1000        2000        3000        2500.0
1   Jane    9000        10000       5000        8000.0

Breakdown of code:
Firstly we select all the columns that Named like 'Revenue' via filter() method and it will give a DataFrame of columns named like that so we are storing it in out variable
out=df.filter(like='Revenue')
#output of above code:
  Revenue1  Revenue2    Revenue3
0   1000    2000        3000
1   9000    10000       5000

Then we will filter out rows where values is greater than 1000:
out.gt(1000)
#your condition
#output of above code:
   Revenue1     Revenue2    Revenue3
0   False       True        True
1   True        True        True

As you saw the condition gives you boolean values so now we will pass that boolean mask to out so where there is True in the above boolean values you will get the values and where there is False you will get NaN this is know as boolean masking:
out[out.gt(1000)]
#output of above code:
   Revenue1     Revenue2    Revenue3
0   NaN         2000        3000
1   9000.0      10000       5000

Finally we will calculate mean via mean() method on axis=1 so the NaN's are ignored..In other words mean() method doesn't considered NaN's while calculating mean(because by default skipna=None in mean() method)
out[out.gt(1000)].mean(axis=1)
#output of above code:
0    2500.0
1    8000.0
dtype: float64

Finally we will assign this result back to df:
df['Average']=out[out.gt(1000)].mean(axis=1)

Update:
If df also has other numerical columns like 'Income' and you also want to include it in your calculation along with columns like 'Revenue' then use:
out=df.filter(regex='Revenue|Income')
df['Average']=out[out.gt(1000)].mean(axis=1)

A: or using a mask
df['average'] = df.mask(df.filter(like='Revenue')<=1000).mean(1)

   Name  Revenue1  Revenue2  Revenue3  Revenue4  average
0  Peter      1000      2000      3000      2500   2500.0
1   Jane      9000     10000      5000      8000   8000.0

A: Hello Try this out
 d['average']=d[d.filter(like='revenue')>1000].mean(1)
 d

A: Maybe try using a condition of > 1000:
df['Mean'] = df.select_dtypes(int)[df.select_dtypes(int) > 1000].mean(1)
print(df)

Output:
    Name    Revenue1    Revenue2    Revenue3    Mean
0   Peter   1000        2000        3000      2500.0
1   Jane    9000        10000       5000      8000.0


text:
Q: Redux questions about the real-world example I have a few questions about redux's real-world example.

*

*Unlike the async example where  ajax calls are made directly using dispatch, the real-world example uses middleware to deal with this. Which method is recommended when using redux in an react app? and why?
My guess is that middleware is reusable, so if multiple ajax calls need to be made, one general purpose ajax calling middleware is enough as long as different api path are passed in as parameters. But the samething can be said with dispatch...

*When do middlewares get executed? By looking at the source code and reading the doc, my understanding is: dispatch an action -> all middlewares get executed , ajax calls can be made here and the returned json data can be put inside the action object and pass it onto the reducers-> reducers get executed. Am I correct?

A:
Unlike the async example where ajax calls are made direactly using dispatch, the real-world example uses middleware to deal with this. Which method is recommended when using redux in an react app? and why?

Use what you like. Different people have different preferences. Some want terse code like what middleware provides, others prefer explicitness and sparseness.

When do middlewares get executed? By looking at the source code and reading the doc, my understanding is: dispatch an action -> all middlewares get executed , ajax calls can be made here and the returned json data can be put inside the action object and pass it onto the reducers-> reducers get executed. Am I correct?

This sounds correct. Each middleware can be asynchronous and pass actions to the next middleware. By the time they reach the reducer, they need to be plain objects. Async Flow and Middleware docs mention this.


text:
Q: What is the difference between NavigationService.Navigate() method and PhoneApplicationFrame.Source property? Taken from Exercise 1: Creating Windows Phone Applications with Microsoft Visual Studio 2010 Express for Windows Phone
Task 3: Step 9
// navigate
this.NavigationService.Navigate(new Uri("/PuzzlePage.xaml", UriKind.Relative));

Note:
  The PhoneApplicationPage class provides methods and properties to navigate to pages through its NavigationService property. You can call the Navigate method of the NavigationService and pass the URI for the page as a parameter. You can also use the GoBack and GoForward methods to navigate backward or forward in the navigation history. The hardware back button also provides backward navigation within an application. The event handler shown above uses the NavigationService to go to the PuzzlePage.xaml page.

Task 4: Step 3
(RootVisual as Microsoft.Phone.Controls.PhoneApplicationFrame).Source =
    new Uri("/ErrorPage.xaml", UriKind.Relative);

Note:
  ...
  Whenever you set the Source property to a value that is different from the displayed content, the frame navigates to the new content.
  ...

What are the differences and similarities of both techniques?

A: Essentially, they both do the same thing.
NavigationService.Navigate is a native Silverlight navigation service to allow the asynchronous navigation from one xaml file to another (eliminating the need to load usercontrols) - there's an excellent little overview here.
The difference is that NavigationService has the ability to go backward and forward in a browser-esque fashion. Setting the Source property of the PhoneApplicationFrame does not.
Still early days and it's probably too soon to make an educated guess as to which you should use.
NavigationService has the advantage of being a Silverlight-native class, however PhoneApplicationFrame.Source is specific to WP.


text:
Q: Apiary io mixing up json from iOS I am trying to send a simple json object from iOS to apiary server. I printout my json object after creating it and everything looks good. But apiary is showing everything mixed up. If I have only one item, then it looks fine.
Here I create the object and encode it
let jsonDict = ["name":student.name,
        "email":student.email,
        "password":student.password,
        "gender":student.gender,
        "graduationYear":student.graduationYear,
        "school":student.school,
        "street":student.address.address,
        "city":student.address.city,
        "state":student.address.state
    ]

    var error: NSError?
    let jsonData = NSJSONSerialization.dataWithJSONObject(jsonDict, options: NSJSONWritingOptions(0), error: &error)
    let s = NSString(data: jsonData!, encoding: NSUTF8StringEncoding)
    println(s)

Next I use AFNetworking to send the data
let manager = AFHTTPRequestOperationManager(baseURL: NSURL(string: "\(server)"))
    manager.POST("students", parameters: nil,
        constructingBodyWithBlock: { (data: AFMultipartFormData!) in
            data.appendPartWithFormData(jsonData!, name: "json")
            data.appendPartWithFileData(imageData, name: "image", fileName: "image.jpg", mimeType: "image/jpeg")
        },
        success: { operation, response in
            println("[success] operation: \(operation), response: \(response)")
        },
        failure: { operation, error in
            println("[fail] operation: \(operation), error: \(error)")
    })

Logging the decoded json object I get
{"city":"city","state":"Alabama","gender":"Male","street":"101  ","password":"password","graduationYear":"2014","email":"joe@joe.com","school":"Abcott Institute","name":"joe"}

Finally, on apiary I get the following

The json is all mixed up. I am not sure if AFNetworking is the culprit or of apiary is mixing it up and I shouldn't worry about it because the real server will not have this issue.
Finally, here is how I am setting up apiary

Anyone see anything dubious that I am doing?
Thank you
Oh, in addition to mixing things up, the json has repeated data.

A: Try changing your request to:
+ Request (application/json)

        {"city":"city","state":"Alabama","gender":"Male","street":"101  ","password":"password","graduationYear":"2014","email":"joe@joe.com","school":"Abcott Institute","name":"joe"}


text:
Q: want to return percentage in Django Rest Framework
*

*I wanted to return the percentage of every poll options_data in response.

*I'm Expecting output Like in below.

{
    "response": true,
    "return_code": "remove_vote_success",
    "result": {
        "id": 9,
        "user_id": 2,
        "question": "what would you like to see more of on our channel?",
        "created_on": "2022-09-06T05:52:39",
        "active": true,
        "options_data": [
            {
                "id": 25,
                "poll_id": 9,
                "option_text": "Video editing tutorials",
                "percentage_count": 50.0
            },
            {
                "id": 26,
                "poll_id": 9,
                "option_text": "Clipchamp product updates",
                "percentage_count": 10.0
            },
            {
                "id": 27,
                "poll_id": 9,
                "option_text": "Social media growth tips"
                "percentage_count": 40.0
            },
            {
                "id": 28,
                "poll_id": 9,
                "option_text": "Clipchamp tips and tricks",
                "percentage_count": 0.0
            }
        ]
    },
    "message": "Vote get successfully."
}

*

*this is my models.py
class Polls(models.Model):
    user = models.ForeignKey(User, related_name="polls_data", on_delete=models.CASCADE)
    question = models.TextField(max_length=250, blank=False, null=False)
    created_on = models.DateTimeField(default=timezone.now)
    active = models.BooleanField(default=True)

class Options(models.Model):
    poll = models.ForeignKey(Polls, related_name="options_data", on_delete=models.CASCADE)
    option_text = models.CharField(max_length=255)

class Vote(models.Model):
    user = models.ForeignKey(User, related_name="vote_data", on_delete=models.CASCADE)
    poll = models.ForeignKey(Polls, on_delete=models.CASCADE)
    option = models.ForeignKey(Options, on_delete=models.CASCADE)

*

*this is my serializer.py
class OptionsSerializer(serializers.ModelSerializer):

    class Meta:
        model = Options
        fields = ('id', 'poll_id', 'option_text')

class PollsSerializer(serializers.ModelSerializer):

    options_data = OptionsSerializer(many=True, read_only=True)

    class Meta:
        model = Polls
        fields = ('id','user_id', 'question', 'created_on', 'active',  'options_data')

A: In your OptionsSerializeradd a field that takes the .count() of the option in question and divide by the count() of all answers for that question. (then multiply that by 100 to get to percentage)
class OptionsSerializer(serializers.ModelSerializer):
    percentage_count = serializers.SerializerMethodField()

    ...

    def get_percentage_count(self, obj):
       total_votes = Vote.objects.filter(poll=obj.poll).count()
       share_of_votes = Vote.objects.filter(option=obj).count()
       return Decimal(
           (share_of_answers / total) * 100
       ).quantize(Decimal('.01'))

A: if we return values direct in response there maybe you will face ZeroDivisionError.
so for code efficiency use this.
class OptionsSerializer(serializers.ModelSerializer):

    percentage_count = serializers.SerializerMethodField()

    class Meta:
        model = Options
        fields = ('id', 'poll_id', 'option_text', 'percentage_count')

    def get_percentage_count(self, obj):
       total_votes = Vote.objects.filter(poll_id=obj.poll).count()
       share_of_votes = Vote.objects.filter(option_id=obj).count()
       try:
            percentage = Decimal((share_of_votes / total_votes) * 100).quantize(Decimal('.01'))
       except ZeroDivisionError:
            return 0
       return percentage

class PollsSerializer(serializers.ModelSerializer):

    options_data = OptionsSerializer(many=True, read_only=True)

    class Meta:
        model = Polls
        fields = ('id','user_id', 'question', 'created_on', 'active',  'options_data')


text:
Q: Load iframe sources into Foundation Modal after page load I'm creating a one page portfolio site using Foundation that is simple at first, but then if you click on links modals pop up feeding in the html src from other pages.  However, I want the sources of these modals to load after the page loads (around 10mb of images trying to load). What is the best way to do this in jQuery/js?
I have around six of these modals:
View Project Details

A: One of the best practices is to use AJAX to load content into the modal.
and Reveal modal lets you do it
<button data-reveal-id="myModal" data-reveal-ajax="http://some-url">
Click Me For A Modal
</button>

Click Me For A Modal

or you can use JS to configure it
    // just an url
$('#myModal').foundation('reveal', 'open', 'http://some-url');

// url with extra parameters
$('#myModal').foundation('reveal', 'open', {
    url: 'http://some-url',
    data: {param1: 'value1', param2: 'value2'}
});

// url with custom callbacks
$('#myModal').foundation('reveal', 'open', {
    url: 'http://some-url',
    success: function(data) {
        alert('modal data loaded');
    },
    error: function() {
        alert('failed loading modal');
    }
});

for more configuration options refer this linklink


text:
Q: How to disable mouse wheel scrolling with xinput? xinput says my mouse is id 11:
$ xinput
⎡ Virtual core pointer                      id=2    [master pointer  (3)]
⎜   ↳ Virtual core XTEST pointer                id=4    [slave  pointer  (2)]
⎜   ↳ VirtualBox mouse integration              id=9    [slave  pointer  (2)]
⎜   ↳ ImExPS/2 Generic Explorer Mouse           id=11   [slave  pointer  (2)]
⎣ Virtual core keyboard                     id=3    [master keyboard (2)]
    ↳ Virtual core XTEST keyboard               id=5    [slave  keyboard (3)]
    ↳ Power Button                              id=6    [slave  keyboard (3)]
    ↳ Sleep Button                              id=7    [slave  keyboard (3)]
    ↳ Video Bus                                 id=8    [slave  keyboard (3)]
    ↳ AT Translated Set 2 keyboard              id=10   [slave  keyboard (3)]

Setting buttons 4 and 5 to 0 works:
$ xinput --set-button-map 11 1 2 3 0 0 6 7 8 9
$ xinput --get-button-map 11
1 2 3 0 0 6 7 8 9

However, mouse wheel scrolling is not disabled. Any ideas what to do about it? Ubuntu 18.04.3.
ETA: Please note that the answer accepted in How to disable mouse wheel scroll in ubuntu 11.04 or 10.10? does not work, at least in my case.
ETA2: Added as per request:
$ xinput list-props 11
Device 'ImExPS/2 Generic Explorer Mouse':
    Device Enabled (127):   1
    Coordinate Transformation Matrix (129): 1.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 1.000000
    libinput Natural Scrolling Enabled (266):   0
    libinput Natural Scrolling Enabled Default (267):   0
    libinput Scroll Methods Available (274):    0, 0, 1
    libinput Scroll Method Enabled (275):   0, 0, 0
    libinput Scroll Method Enabled Default (276):   0, 0, 0
    libinput Button Scrolling Button (277): 2
    libinput Button Scrolling Button Default (278): 2
    libinput Middle Emulation Enabled (279):    0
    libinput Middle Emulation Enabled Default (280):    0
    libinput Accel Speed (281): 0.000000
    libinput Accel Speed Default (282): 0.000000
    libinput Accel Profiles Available (283):    1, 1
    libinput Accel Profile Enabled (284):   1, 0
    libinput Accel Profile Enabled Default (285):   1, 0
    libinput Left Handed Enabled (270): 0
    libinput Left Handed Enabled Default (271): 0
    libinput Send Events Modes Available (249): 1, 0
    libinput Send Events Mode Enabled (250):    0, 0
    libinput Send Events Mode Enabled Default (251):    0, 0
    Device Node (252):  "/dev/input/event4"
    Device Product ID (253):    2, 6
    libinput Drag Lock Buttons (272):   <no items>
    libinput Horizontal Scroll Enabled (273):   1

A: Remove libinput by
sudo apt remove 'xserver-xorg-input-libinput.*'

The mouse will be handled by evdev and all former solutions will work.


text:
Q: How to turn off Windows Azure's "This copy of Windows is not genuine" message? Is there any setting/configuration item to avoid Windows Azure from printing that error on the screen or detecting it? I've put a screenshot below that shows the message when you RDP into the web role. My web role runs on Windows Azure Guest OS 1.17 (variant of Windows Server 2008 SP2)

Background: I was explaining our architecture to some outside engineers (NDA'd and all) and had to demystify the webrole as they were unfamiliar with Azure. I RDP'd into the VMs running the Web Role when one of their engineers gasped "are you guys running pirated copies of Windows in the cloud?" I also noticed that within the RDP screen, the Azure machines had "This copy of Windows is not genuine" on the bottom left corner.
Now obviously, Microsoft is running their own OS in their own datacenter with no influence from me. So no 'piracy' here, despite that obvious warning. However, they seemed so distracted by this ("how can it be? really? hmmm?") that we wasted more time talking about it than the actual matter at work. Like I said, they have little exposure to Azure but have value add elsewhere. I want to get rid of this so I don't have to explain this in the future.
PS Microsoft: If you're going to modify Windows Server <XYZ> into Windows Azure <A.B> , you should also modify the code that verifies product integrity.

A: I'm pretty sure this only shows up with OS family 1 (Windows Server 2008 SP2). If you were to change osFamily="2"(Windows Server 2008 R2) in your ServiceConfiguration.cscfg and update your deployment, you shouldn't see that on the desktop. This is where the setting lives:
<ServiceConfiguration serviceName="GenuineTest" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceConfiguration" osFamily="2" osVersion="*">

I just double-checked this with a few of my deployments running osFamily="2". I also RDP'd into one of mine running osFamily="1" and the "This copy of Windows is not genuine" message is there.
Depending on your configuration management practices, it might not be practical to simply change an OS version and redeploy. For demo purposes, it might be worth pushing up a simple single-instance VM (worker or web role - doesn't really matter) running osFamily="2" and RDP-ing into it to show that the desktop has no warning on it.
For more info on OS families, see this page.


text:
Q: Finding Limit point of complex sequence Show that $$a_n:=2^{-n/2}(1+i)^n\frac{1+n}{n}$$ has $i$ as one of its limit points.
To show that one of its limit points is in fact $i$ i thought that i have to find a subsequence with $\lim_{k\to\infty} a_{n_k}=i$. I plotted the first 1000 elements of the sequence and guess that the subsequence with $8k+2, k\in\mathbb{N}$ should be the appropriate one. But I am unfortunately stuck. I wanted to convert the sequence into polar coordinates but didn't really know how to evaluate the absolute value of $a_n$ let alone the angle, because I don't know how to separate the imaginary and real part here.

A: You have$$a_n=\frac{1+n}n\left(\frac{1+i}{\sqrt2}\right)^n=\frac{1+n}ne^{\pi in/4},$$since $e^{\pi i/4}=\frac{1+i}{\sqrt2}$. So,$$a_{8k+2}=\frac{8k+3}{8k+2}i\to_{k\to\infty}i.$$


text:
Q: Is there a relation between number of divisors and ability to express a number as a perfect square. Is there a way to relate the number of ways of expressing an integer as a difference of squares to the number of divisors it has?  Particularly, in the case of perfect squares.

A: For a number to be a perfect square, each prime factor appears with an even power.
Thus the total number of divisors are $$ (2k_1 +1)( 2k_2 +1)...(2k_n +1)$$ which is an odd integer.


text:
Q: Error in GROUP BY clause. Unable to parse query text I have a complex SQL statement that I fall upon an error. They prompted me this error: Error in GROUP BY expression. Can't parse query text.
I pasted this SQL statement which causes this error. Can anyone advise me where went wrong? Any ideas???
SELECT        AllocationDate, LocationName, StationName, Hour1, Hour2, Hour3, Hour4, Hour5, Hour6, Hour7, Hour8, Hour9, Hour10, Hour11, Hour12, EmpName, ShiftTime,
                     BreakTime, SignIn, SignOut
FROM            (SELECT        z.AllocationDate, z.LocationName, z.StationName, a.Hour1, b.Hour2, c.Hour3, d .Hour4, e.Hour5, f.Hour6, g.Hour7, h.Hour8, i.Hour9, j.Hour10, k.Hour11,
                                                l.Hour12, m.EmpName, m.ShiftTime, m.BreakTime, m.SignIn, m.SignOut
                      FROM            (SELECT DISTINCT AllocationDate, LocationName, StationName
                                                FROM            satsschema.viewmain
                                                WHERE        (StationName IS NOT NULL)) z LEFT OUTER JOIN
                                                    (SELECT DISTINCT AllocationDate, LocationName, StationName, Hour1
                                                      FROM            satsschema.view00000100) a ON z.LocationName = a.LocationName AND z.StationName = a.StationName AND
                                                z.AllocationDate = a.AllocationDate LEFT OUTER JOIN
                                                    (SELECT DISTINCT AllocationDate, LocationName, StationName, Hour2
                                                      FROM            satsschema.view01000200) b ON z.LocationName = b.LocationName AND z.StationName = b.StationName AND
                                                z.AllocationDate = b.AllocationDate LEFT OUTER JOIN
                                                    (SELECT DISTINCT AllocationDate, LocationName, StationName, Hour3
                                                      FROM            satsschema.view02000300) c ON z.LocationName = c.LocationName AND z.StationName = c.StationName AND
                                                z.AllocationDate = c.AllocationDate LEFT OUTER JOIN
                                                    (SELECT DISTINCT AllocationDate, LocationName, StationName, Hour4
                                                      FROM            satsschema.view03000400) d ON z.LocationName = d .LocationName AND z.StationName = d .StationName AND
                                                z.AllocationDate = d .AllocationDate LEFT OUTER JOIN
                                                    (SELECT DISTINCT AllocationDate, LocationName, StationName, Hour5
                                                      FROM            satsschema.view04000500) e ON z.LocationName = e.LocationName AND z.StationName = e.StationName AND
                                                z.AllocationDate = e.AllocationDate LEFT OUTER JOIN
                                                    (SELECT DISTINCT AllocationDate, LocationName, StationName, Hour6
                                                      FROM            satsschema.view05000600) f ON z.LocationName = f.LocationName AND z.StationName = f.StationName AND
                                                z.AllocationDate = f.AllocationDate LEFT OUTER JOIN
                                                    (SELECT DISTINCT AllocationDate, LocationName, StationName, Hour7
                                                      FROM            satsschema.view06000700) g ON z.LocationName = g.LocationName AND z.StationName = g.StationName AND
                                                z.AllocationDate = g.AllocationDate LEFT OUTER JOIN
                                                    (SELECT DISTINCT AllocationDate, LocationName, StationName, Hour8
                                                      FROM            satsschema.view07000800) h ON z.LocationName = h.LocationName AND z.StationName = h.StationName AND
                                                z.AllocationDate = h.AllocationDate LEFT OUTER JOIN
                                                    (SELECT DISTINCT AllocationDate, LocationName, StationName, Hour9
                                                      FROM            satsschema.view08000900) i ON z.LocationName = i.LocationName AND z.StationName = i.StationName AND
                                                z.AllocationDate = i.AllocationDate LEFT OUTER JOIN
                                                    (SELECT DISTINCT AllocationDate, LocationName, StationName, Hour10
                                                      FROM            satsschema.view09001000) j ON z.LocationName = j.LocationName AND z.StationName = j.StationName AND
                                                z.AllocationDate = j.AllocationDate LEFT OUTER JOIN
                                                    (SELECT DISTINCT AllocationDate, LocationName, StationName, Hour11
                                                      FROM            satsschema.view10001100) k ON z.LocationName = k.LocationName AND z.StationName = k.StationName AND
                                                z.AllocationDate = k.AllocationDate LEFT OUTER JOIN
                                                    (SELECT DISTINCT AllocationDate, LocationName, StationName, Hour12
                                                      FROM            satsschema.view11001200) l ON z.LocationName = l.LocationName AND z.StationName = l.StationName AND
                                                z.AllocationDate = l.AllocationDate LEFT OUTER JOIN
                                                    (SELECT        a.EmpName, CONCAT(b.StartTime, ' - ', b.EndTime) AS ShiftTime, CONCAT(a.EmpTime, ' - ', ADDTIME(a.EmpTime, '0 1:0:0.000000'))
                                                                                AS BreakTime, a.Break, a.EmployeeOnBreak, '' AS SignIn, '' AS SignOut
                                                      FROM            satsschema.employeeslot a, satsschema.ufis b
                                                      WHERE        a.UFISEmpGroup = b.UFISID
                                                     GROUP BY EmpName) m) Morning
WHERE        (AllocationDate = @AllocationDate) AND (LocationName = @LocationName) AND (StationName <> '') AND (Break = 1)
GROUP BY StationName, LocationName, AllocationDate

A: I think you are mixing a lot of concepts.
You can't use a group by without an aggregation function like Min, Max, Avg, etc.
If you want to use Group By, you have to tell what to do with these non aggregated fields:
Hour1, Hour2, Hour3, Hour4, Hour5, Hour6, Hour7, Hour8, Hour9, Hour10, Hour11, Hour12, EmpName, ShiftTime, BreakTime, SignIn, SignOut
I think that what you want is an ORDER BY and not a GROUP BY.

A: Only Aggregate function or grouped columns can be selected in outer query, if you wanna do this.
You can use that columns in group by.
...
GROUP BY AllocationDate, LocationName, StationName, Hour1, Hour2, Hour3, Hour4, Hour5, Hour6, Hour7, Hour8, Hour9, Hour10, Hour11, Hour12, EmpName, ShiftTime,
                     BreakTime, SignIn, SignOut
Thanks.


text:
Q: CarrierWave resize_and_pad method always uses white I've scratched my head over this for quite a while. I have a screenshot uploader class which uploads to AWS. The issue lies with resize_and_pad as the image is correctly resized and padded however regardless of what Hexcode I enter the background is always padded with white.
How can I get the padding to be black instead of white?
class ScreenshotUploader < CarrierWave::Uploader::Base
  require 'carrierwave/processing/rmagick'
    include CarrierWave::RMagick
    process resize_and_pad: [200, 100, "#000000"]
  end
end

A: resize_and_pad takes in 4 parameters, you're missing one parameter: gravity.

process resize_and_pad : [200,100,"#000000",Magick::CenterGravity]

should do it.
Here's the official doc: link

A: I had to switch to the Mini_Magick library instead of Rmagick and everything worked as expected.
require 'carrierwave/processing/mini_magick'
class ScreenshotUploader < CarrierWave::Uploader::Base
   include CarrierWave::MiniMagick
   process resize_and_pad: [200, 100, "#000", "Center"]
end


text:
Q: ASP.NET - hiding BoundField input I have a simple connection to a database achieved through a DetailsView control in ASP.NET. One of the fields is a password so I'd like its content to be hidden while typing. My first thought was TextBox's TextMode="Password" but that failed miserably since BoundField class doesn't implement it. I'm guessing it must be done programmatically through an event-handler but I simply don't know how.
Here's the markup I've written so far, if needed:
<body>
    <form id="form1" runat="server">
    <div class="register" runat="server">
        <asp:DetailsView ID="InsertData" runat="server" HorizontalAlign="Center"
            Height="100px" Width="170px"
            AutoGenerateRows="False" DataSourceID="usersConnectionString"
            DefaultMode="Insert" OnItemCommand="Button_click" OnItemInserted="Insert_click">
            <Fields>
                <asp:BoundField DataField="userName" HeaderText="Name"
                    SortExpression="userName" />
                <asp:BoundField DataField="userPassword" HeaderText="Password"
                    SortExpression="userPassword" />
                <asp:BoundField DataField="userEmail" HeaderText="Email"
                    SortExpression="userEmail" />
                <asp:CommandField ShowInsertButton="True" />
            </Fields>
        </asp:DetailsView>
        <asp:SqlDataSource ID="usersConnectionString" runat="server"
            ConnectionString="<%$ ConnectionStrings:usersConnectionString %>"
            InsertCommand="INSERT INTO user(userName, userPassword, userEmail) VALUES (@userName, @userPassword, @userEmail)">
            <InsertParameters>
                <asp:Parameter Name="userName" Type="String" />
                <asp:Parameter Name="userPassword" Type="String" />
                <asp:Parameter Name="userEmail" Type="String" />
            </InsertParameters>
        </asp:SqlDataSource>
        <asp:Label ID="Message_label" ForeColor="red" Visible="false" runat="server" Text="[messageLabel]"></asp:Label>
    </div>
    </form>
</body>

A: The best thing to do in this is to make an ItemTemplate and within that, have a textbox control and set its input mode/type to be Password.
The ItemTemplate allows you to add normal/custom user controls to your liking outside of the standard BoundField columns


text:
Q: angular wizard ng-view and angularui modal I am building a wizard in angular using the angular-ui bootstrap modal component.
In my main page, I am already using ng-views for navigation.
The goal is to create a modal wizard on one of these pages. As far as I can see,
nested ng-views are not supported. If possible, I would like to keep each step of
the wizard as an external resource.
A terrible way to accomplish this at the moment is something to this effect:

Step1 header

Step2 header

Step3 header

Step1 body

Step2 body

Step3 body

Step1 footer

Step2 footer

Step3 footer

Obviously, the above is unacceptable and will create maintenance nightmares.
Is there a clean approach to accomplishing the same effect?

A: Using ng-include worked like a charm, thanks.

A: You can find a tutorial about creating a wizard-style app using ng-view and ngRouter here.
I believe this approach is much better since you can have individual controllers per step that inherit the scope from the host form thus keeping all the data but separating the logic.


text:
Q: jquery creating repeteable inner divs dynamically this is a little bit complicated question. I want to achieve the following behaviour (creating sections dynamically): I'm sending the whole example: E.g. I have parent div and child div inside this parrent. In each div can be some placed some controls (inputs, buttons,...). I have following requirements:

*

*each section can be repeteable (i mean creating it dynamically) max times (maxRepetition)

*sections can be nested inside another section (in this example there are only two levels of immersion: parent->child, but it can be also parent->child1->child2->...) and each of these sections must accept requirement 1.

I have spend a lot of time how to achieve this, but not sucesfully. If somebody can help me I will very gratefull.

<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

                    <input id="field1" type="text" width="100">

                                        <input id="field2" type="text" width="100">

                    Add
                    Remove

Add
Remove

A: instead of reading the html of sections you can make a template for parent section and a template for child section then adding action to get html of parent/child template with new IDs then append it to your page. like the following

                            <input id="field1" type="text" width="100">

                                                    <input id="field2" type="text" width="100">

 Remove child

                                Add child

                            <input id="field1#index#" type="text" width="100">

            Remove child

        Add child

you may find the result doesn't like you want but you can use the same technique.


text:
Q: Keep excel table formatting after refreshing the table I have VBA code that refreshes an Excel table using a sproc
With ActiveWorkbook.Connections("Connection").OLEDBConnection
Values = QueryStr
.CommandText = Values
End With

Once the refresh has completed I need to apply some formatting (trhough VBA code), the problem with this is that the code executes without waiting for the refresh to end, therefore the  VBA macro fails, is there a way I could tell the macro to wait until the refresh has completed?
Thanks

A: Try setting the BackgroundQuery property to False.
Code:
With ActiveWorkbook.Connections("Connection").OLEDBConnection
    .BackgroundQuery = False '- Change here
    Values = QueryStr
    .CommandText = Values
End With

If i'm not mistaken.. this'll prevent the updates from running in the background, so it'll have to complete before the rest of your code executes.


text:
Q: X3D Volume Rendering using PNG file instead of NRRD file So I was wondering if it's at all possible to use a PNG file in place of an NRRD file when rendering volume in X3D? I know there's something in the API called TextureAtlas that I think might be what I'm looking for but I can't seem to find a working example anywhere online. Any help would be greatly appreciated.

A: So it turns out the X3D player I was using, that being instantplayer by instantreality, does not support the TextureAtlas node in the first place. So it appears the only player that might support the different nodes I need is X3DOM, seeing as how I was able to find an example in a slideshow online.


text:
Q: LESS/CSS: Is it possible to wrap a class around the outside of another without HTML? If my HTML looks like this:

        …

…is it possible to omit the outside div from the HTML and do something like this (with LESS):
section {
           enclose-with(.purely-aesthetic-wrapper);
         }

Sorry if it's an obvious question but I'm not having much luck finding the answer.

A: Short answer is no, it's not possible.
LESS is css pre-processor and it has nothing to do with HTML/DOM-tree


text:
Q: How did Picard send a binary message to Data in the future? In the Star Trek TNG episode "Times Arrow", parts one and two, recall the following:

*

*Data's head was found in an excavation on Earth that dates from the 19th century (it actually is Data's head).

*Data, Picard, Crusher, Worf, and others go back in time to the 19th century to investigate.

*Guinan (her 500-year younger self) was living in San Francisco in the 19th century.

*This is where Guinan first meets Picard, but not where Picard first meets Guinan.

*It turns out that alien time travelers are sucking energy out of people on Earth from the 19th century.

*In the process, Data is caught in an altercation which essentially blows his head off.

Here's where things get especially interesting...

*

*In an effort to stop these aliens, all of the away team along with Samuel Clemens, except Picard and Guinan end up back in the future to try to destroy the aliens time travel site on their planet.

*Picard, still in the 19th century finds out from one of the aliens that if the Enterprise in the future fires upon the alien time travel site, the energy from the ship's phasers will only serve to increase the aliens' power.

*Commander LaForge manages to reassemble the 500 year old Data head, after removing a suspicious piece of metal lodged in one of Data's cranial ports. "How did that get in there?" LaForge asks.

*We are then taken back in time to see Picard is responsible for putting the metal piece in there. He also enters a binary message into Data's static memory warning the Enterprise not to fire on the alien site.

*Data (reassembled) receives this message, and the crew make a plan to destroy the alien site by making a tweak to the ship's weapons.

*Before destroying the site, Samuel Clemens goes back in time and allows Picard to return to the 24th century

Everybody wins! What an awesome episode!
But here's the rub
From Picard's perspective, he simply entered the binary message into Data's head, and then was immediately rescued. I should think that Picard would have had to have lived a lifetime in the 19th century, then died, and then 500 years later, Data's head would be found. At this point, the static memory in Data's head warning the Enterprise would be there legitimately and the episode could continue as normal.
So how does entering the binary message into Data's static memory seemingly transcend the space time continuum and make it to the future?

A: Welcome to the Grandfather Paradox. Start with the Wikipedia article.
There are at least four ways to handle this:

*

*Picard's actions form a self-determining loop. That is, the origins of his actions are contained entirely with the loop. The classic along these lines is Heinlein's All You Zombies.

*When Picard altered Data's memory, he created a parallel universe (timeline) in which the data exists/existed/will exist. When the team returned from the past, they entered this new timeline. In the old timeline, they never returned.

*When Picard altered Data's memory, he created a history which overwrote the original history which caused him to go back in time. The original history, in which Data's memory was not modified, ceases to "exist", as far as the word applies.

*There's no problem. The away team went back in time without having performed a detailed examination of Data's head. So it had always been modified, and Picard's actions had always occurred. Again, as far as the word "always" applies.
An excellent discussion of the peculiarities of time travel (from a purely speculative viewpoint, of course) is Larry Niven's The Theory and Practice of Time Travel

A: Data's head begins life with Data's body. At some point, the whole body goes back in time. The head is severed and left behind. Picard (also left behind) plays with it to encode a message. Picard is retrieved by his colleagues in the future. 500 years later, the head is found again and brought back on board the Enterprise. It's plugged back into the body (which took a "shortcut" by not being left behind). Data relays the message, and the crew retrieve Picard.
There's only one path that the head took. It can be a little difficult to get your head around (lol) simply because (from his perspective) Picard was rescued centuries before his SOS message would be received, and because Data's head and body got back to the 24th Century via extremely different means. The head took the long way around. But Picard's fiddling with it didn't need to create an alternate timeline, or bypass a paradox, or make Picard wait (?) or anything like that. It was simply a man playing with his buddy's head.
            olden days                     23rd century
t ════════════════════════════════════════════════════════════→

    Guinan ┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄→

    Clements ┄┄┄┄┄┄┄┄┄┄ †
                                       Data  Team (ex. Data)
                                         ↓      ↓
       ╭─────────────────────────────────╯      │
       │   ╭────────────────────────────────────╯
       ↓   │
       ¦   ↓
       ¦   ╰┄ Team (ex. Picard)
       ¦        ¦
       ¦        ╰───────────────────────────────────∎┄┄┄┄╮
       ¦                                                 ↓
       ╰┄┄┄┄→ Data's body                                ¦
                ↓                                        ¦
                ├───────────────────────────────────∎┄┄┄┄┤
                ¦                                        ¦
              Data's                                     ¦
            head (with message)                          ¦
                ¦                                        ¦
                ├┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄⁕┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄⁕
                ¦             Head discovered            ¦
                ¦                               Data recombined
                ¦                                Msg discovered
             Picard                                      ¦
                ¦                                        ╰┄╮
                ╰┄┄┄╮                                      ¦
                    ¦                                      ¦
                    ¦                                  Rescue
                    ¦                                   team
                    ¦                                      ↓
                    ¦ ╭────────────────────────────────────╯
                    ¦ │
                    ¦ │
                    ¦ │
                    ╰┄↓
                    Picard and
                    rescue team
                         │
                         ╰───────────────────────────────────∎┄┄┄→

Where solid lines (─) indicate unnatural time travel, and dotted lines (┄) indicate the more conventional way of simply sitting there until years have passed. Rightwards is absolute chronology; downwards is subjective chronology (i.e. events in the order portrayed in the episode and experienced by the characters).
You can see that Data's head, message an' all, just makes it to the future in the usual manner. Picard and the rescue team and Data's body are jumping around all over the place, making it more confusing, but the head is the one part of the puzzle that can't possibly cause anything more than the predestination paradox incited by its being found in the 23rd Century right as the episode's narrative begins.
The key salient point is that Data's head was always there, in San Francisco, with a message encoded in it. Since the beginning of the series, and since way before that. It's just that we (and the crew) didn't know that until the events of this episode (which ironically caused the whole issue in the first place!).

I should think that Picard would have had to have lived a lifetime in the 19th century, then died, and then 500 years later, Data's head would be found.

That would be a paradox. Picard did a thing. That thing had an effect: his crewmates obtaining that information. That he was rescued immediately thereafter is an effect of their time travelling. If he somehow also experienced a timeline in which he just sat there for years because his message had not got through and his crewmates no longer decided to go back in time to rescue him, then that would be a problem.

So how does entering the binary message into Data's static memory seemingly transcend the space time continuum and make it to the future?

When you write a message on a piece of paper, it's still there the next day. That's the normal flow of information through the passage of time. Presumably you are not transcending the space-time continuum in order to allow your message to make it to the future. :)

A: picard doesn't have to live a life in the past, he only has to have placed his butterfly for events to continue to unfold as they should. Once the message is received in the future, and the aliens are stopped, picard can go back to the future at any time. The artifacts of being in the past, although lucky to have made it as far as that point in the future are already predetermined as a past event from picard's perspective. I.e. he already knew they found data's head and thus the vehicle for his message to the future was secured.


text:
Q: How expensive is os.Getenv? I have a piece of code that's called every few seconds and makes use of an environment variable:
for {
    myVar := os.Getenv("MY_VAR")
    //Do something
    time.Sleep(3 * time.Second)
}

But how costly are repeat calls to os.Getenv?
The value of the environment variable will not change during runtime, so I could set it as a package level variable:
package blah

var myVar = os.Getenv("MY_VAR")

But this does hurt testability of the code.
Should I set it as a package level variable? Or is os.Getenv benign enough?
EDIT:
I've benchmarked the call to os.Getenv but is it reliable?
package main_test

import (
    "os"
    "testing"
)

var result string

func BenchmarkEnv(b *testing.B) {
    var r string
    for n := 0; n < b.N; n++ {
        r = os.Getenv("PATH")
    }
    result = r
}

goos: darwin
goarch: amd64
BenchmarkEnv-8      20000000            78.7 ns/op
PASS

A: You can benchmark os.Getenv and see how fast it is.
By looking at its implementation here, it costs:

*

*A read-lock;

*Lookup in global map;

*Linear search of char '='.


text:
Q: PHP else if methods isn't working? Hello I am trying to implement after they pay it checks how much they paid and inputs different variables in sql database with if methods.
The problem:
The problem is all the if methods return to this first option(inserts paid=1, and 30days) not sure what the problem is, is my if method broken?what's wrong please explain! thanks!
if(number_format($amount, 2) == 8.00)
{
    $mysqli = new mysqli(******);
    $stmt = $mysqli->prepare("UPDATE `as_users` SET paid='1', reg_date=CURRENT_TIMESTAMP, end_date=DATE_ADD(CURRENT_TIMESTAMP(), INTERVAL 30 DAY) WHERE username = ?");
    $stmt->bind_param('s', $username);
    $stmt->execute();
} elseif (number_format($amount, 2) == 10.00)
{
    $mysqli = new mysqli(******);
    $stmt = $mysqli->prepare("UPDATE `as_users` SET paid='2', reg_date=CURRENT_TIMESTAMP, end_date=DATE_ADD(CURRENT_TIMESTAMP(), INTERVAL 30 DAY) WHERE username = ?");
    $stmt->bind_param('s', $username);
    $stmt->execute();
} elseif (number_format($amount, 2) == 100.00)
{
    $mysqli = new mysqli(******);
    $stmt = $mysqli->prepare("UPDATE `as_users` SET paid='2', reg_date=CURRENT_TIMESTAMP, end_date=DATE_ADD(CURRENT_TIMESTAMP(), INTERVAL 365 DAY) WHERE username = ?");
    $stmt->bind_param('s', $username);
    $stmt->execute();
}

Edit: I tried with $amount and also tried using the names of the array from dropdown menu I have
array("Basic Package-Monthly", "8.00", "Month", "1", "0", "0"),
array("Premium Package-Monthly", "10.00", "Month", "1", "0", "0"),
array("Premium Package-Annually", "100.00", "Year", "1", "0", "0"),

A: Why worry about the conditional statement, let the switch handle it. Leverage your prepared statement fully.
$mysqli = new mysqli('******');
$paid = false;
$recurring = false;

switch(number_format($amount, 2)):
    case '8.00':
        $paid = 1;
        $recurring = 30;
        break;
    case '10.00':
        $paid = 2;
        $recurring = 30;
        break;
    case '100.00':
        $paid = 2;
        $recurring  = 365;
        break;
endswitch;

$stmt = $mysqli->prepare("UPDATE `as_users` SET paid=?, reg_date=CURRENT_TIMESTAMP, end_date=DATE_ADD(CURRENT_TIMESTAMP(), INTERVAL ? DAY) WHERE username = ?");
$stmt->bind_param('dis', $paid, $recurring, $username);
$stmt->execute();

A: try to use
number_format($amount, 2, '.', '') instead of number_format($amount, 2) for returning  english notation without thousands separator.
i.e

english notation without thousands separator

$number = 1234.56;
$english_format_number = number_format($number, 2, '.', '');

1234.56

and to compare two float values use BC math function
$b = 10.00;
$a = number_format($amount, 2, '.', '');
    bccomp($a, $b)==0  // returns true if both values are 10.00


text:
Q: JDK Version inconsistent My os is Ubuntu 16.04 LTS.
$ cat /etc/profile   # part content of this file
JAVA_HOME=/usr/local/java/jdk1.8.0_101
JRE_HOME=$JAVA_HOME/jre
PATH=$PATH:$JAVA_HOME/bin:$JRE_HOME/bin
export JAVA_HOME
export JRE_HOME
export PATH

$ echo $JAVA_HOME
/usr/local/java/jdk1.8.0_101

$ java -version
java version "1.7.0_79"
Java(TM) SE Runtime Environment (build 1.7.0_79-b15)
Java HotSpot(TM) 64-Bit Server VM (build 24.79-b02, mixed mode)

$ ls /usr/local/java/
jdk1.7.0_79/  jdk1.8.0_101/

Why is my java version still jdk7?

A: Ubuntu has ability to work with multiple java versions. In your case, it just means that it has both JDK 7 and JDK 8 installed in your system but is using JDK 7.
To switch from one java version to another, you can use sudo update-alternatives --config java. This will list all JDKs installed in your system, just enter the number corresponding to JDK 8 and it should switch to JDK 8.

A: Run which java in your command shell.  That will tell you where the java command you are running is coming from.
I suspect that is will tell you "/usr/bin/java" ... because this:
PATH=$PATH:$JAVA_HOME/bin:$JRE_HOME/bin

puts your new bin directories onto the end of the search path, not the beginning.
However, the better way to do this would be to use alternatives as suggested by another Answer.  (With a custom installation in "/usr/local" this will require some fiddling around to get "alternatives" to understand the alternative.)


text:
Q: VBA/EXCEL: extract numbers from one cell that contained multiple values with comma http://i.stack.imgur.com/53tz0.jpg is the images.
Hello I would like to modify this code, so it understands multiple values. the best I came was the barcode scanner, I'm a novice in vba but I really enjoy it. this is a fun project that I do so please help me. Thanks guys.
Private Sub Worksheet_Change(ByVal Target As Range)

    Const SCAN_CELL As String = "A1"
    Const RANGE_BC As String = "A5:A500"
    Dim val, f As Range, rngCodes As Range

    If Target.Cells.Count > 1 Then Exit Sub
    If Intersect(Target, Me.Range(SCAN_CELL)) Is Nothing Then Exit Sub

    val = Trim(Target.Value)
    If Len(val) = 0 Then Exit Sub

    Set rngCodes = Me.Range(RANGE_BC)

    Set f = rngCodes.Find(val, , xlValues, xlWhole)
    If Not f Is Nothing Then
        With f.Offset(0, 2)
            .Value = .Value + 1
        End With
    Else
        Set f = rngCodes.Cells(rngCodes.Cells.Count).End(xlUp).Offset(1, 0)
        f.Value = val
        f.Offset(0, 1).Value = "enter description"
        f.Offset(0, 2).Value = 1
    End If

    Application.EnableEvents = False
    Target.Value = ""
    Application.EnableEvents = True

    Target.Select
End Sub

A: To get multiple values stored in one cell that are separated by a comma or any special character you can use the vba function Split.
For example, let's say we have a cell C5 that have the following four numbers separated by a comma :
122.20,358.55,155.58,758.33

Here is how you can use the Split function to return an array storing each number from cell C5:
msgbox(split(range("c5"),",")(0))    'This will return 122.20
msgbox(split(range("c5"),",")(1))    'This will return 358.55
msgbox(split(range("c5"),",")(2))    'This will return 155.58
msgbox(split(range("c5"),",")(3))    'This will return 758.33

Hope this helps


text:
Q: Can anyone please explain what is happening in this code? This code in Scheme is used to output a list in which the element of the input lists are repeated n times. I do not understand what is happening in the code.
(define (echo-lots lst n)
  (define (helper lst1 n1)
    (if (= n1 0)
        '()
        (cons lst1 (helper lst1 (- n1 1)))))
  (if (null? lst)
      '()
      (append (helper (car lst) n) (echo-lots (cdr lst) n)))

A: First, note that helper does not use any of the parameters of echo-lots.
That means that you can move the definition outside and figure it out in isolation:
(define (helper lst1 n1)
    (if (= n1 0)
        '()
        (cons lst1 (helper lst1 (- n1 1)))))

> (helper 1 3)
'(1 1 1)
> (helper #f 4)
'(#f #f #f #f)
> (helper '(a b c) 2)
'((a b c) (a b c))

It makes a list whose elements are the first parameter repeated the number of times given by the second parameter.
(It's not difficult to prove this formally, if you're in the mood for that.)
Note also that the first parameter's name is misleading - it does not have to be a list.
Let's improve the naming:
(define (repeat item n)
    (if (= n 0)
        '()
        (cons item (repeat item (- n 1)))))

Now echo-lots is clearer:
(define (echo-lots lst n)
  (if (null? lst)
      '()
      (append (repeat (car lst) n)
              (echo-lots (cdr lst) n))))

and it's easier to see that it makes a list of n copies of the first element of lst - (repeat (car lst) n) - and appends that to a list consisting of n copies of each of the remaining elements - (echo-lots (cdr lst) n).


text:
Q: Making Ajax call I have a requirement and I am stuck.
I need to create a web tool.
1.So I have created a Web project in eclipse.
2.Created a jsp file with (html,css,js )
3.Now a click on a radio button should give call a java class and display it in the same
page.So I need to make an ajax call.
how do I make an ajax call in my jsp?
how do I create a servlet and link my java class.
I do not want any coding help here, just if someone can give me an approach, I would really appreciate it.
thanks


text:
Q: Idiomatic way to conditionally pass parameters to a command in a shell script? I need to pass specific options to a program based on the value of the variable $BAD_SCENARIO, which is more or less a flag (1 or 0 or empty). I came up with
program $([ "$BAD_SCENARIO" = "1" ] && echo "--emergency-cleanup" || echo "--normal-cleanup") \
        $([ "$BAD_SCENARIO" = "1" ] && echo "--notify-admin" || echo "")

which seems pretty verbose. Is there a better way to do it?

A: Use bash arrays. Use if.
args=()
if [ "$BAD_SCENARIO" = "1" ]; then
   args+=(--emergency-cleanup --notify-admin)
else
   args+=(--normal-cleanup)
fi
program "${args[@]}"


text:
Q: Meaning of "furniture" What does Mary Karr mean by the word furniture in the sentence: "But when you're a kid and something big is going on, you might as well be furniture for all anybody says to you"?

A: The writer means that you're treated as a part of the background, and not a person deserving of attention, consideration, or conversation. We sit on chairs and lean on tables, without paying much attention to them, without wondering how they're understanding or reacting to conversations or activities taking place in their midst. Similarly, she's saying that adults treat kids as not seeing, thinking, feeling, idea-having beings when "something big is going on."


text:
Q: Прошу помочь с расчетом по формуле Только начал изучать Питон. Написал простенькую программку по аналогии примерам из книжки.
При всей неправильности, по моему мнению, формулы full_price считается правильно, хотя на мой взгляд в формула должна выглядеть таким образом:
full_price = price + nalog + reg_fee + agency_fee + price_distance
Может кто-нибудь пояснить, как так выходит???
Вот текст программы:
print ( "Вас приветствует программа Автодиллер!"  )
name = input ( "Введите Ваше имя: " )
print ( "\n" )
print ( (name), "сейчас я посчитаю стоимость купленного Вами автомобиля с учётом налога, который составляет 13% от суммы " )
print ( "автомобиля, регистрационного сбора, который составляет 5% от суммы автомобиля, агентского сбора в 25 долларов США и " )
print ( "цены доставки Вашего автомобиля до указанного места назначения в зависимости от указанного Вами количества километров, " )
print ( "с учетом того, что расстояние доставки, равное 100 километрам стоит 10 долларов США \n" )
price = float ( input ( "Введите цену Вашего автомобиля в долларах США (USD): " ))
distance = float ( input ( "Введите расстояние до места доставки в километрах: " ))
nalog = (price/100)*13
reg_fee = (price/100)*5
agency_fee = (price+25)
price_distance =  (distance*0.1)
full_price = nalog + reg_fee + agency_fee + price_distance
print ( "\n" )
print ( (name) + ", стоимость Вашего заказа в долларах США составляет: ", full_price, "USD"  )
input ( "\nНажмите Enter, чтобы выйти." )
# Что-то странное в формуле явно не хватает price, но иначе результат увеличивается на величину price и результат получается неверным!!!

A: У вас price в agency_fee: agency_fee = (price+25).
По условию:

агентского сбора в 25 долларов

То есть agency_fee = цена автомобиля + агентский сбор


text:
Q: regex match if string contain all the words or a condition im making a simple word game with php and regex, how can we search that if a string have to require two or more words?
lets say
"cat"
"dog"
"play" x 2

if
"cat dog play play" pass
"hello a cat dog playing a play" not pass, only 1 "play"
"cat" not pass, no dog and 2x play
"i want a cat and a dog play with me and play with grandfather" pass
how can we match it with regex?

A: The regex you're looking for is:
/(?=.*?\bcat\b)(?=.*?\bdog\b)(?=(.*?\bplay\b){2})^.*$/

Explanation: I believe words cat, dog and play (twice) can appear in the text in any order but they must all be present in the sentence to qualify. Above regex is using positive lookahead to make sure the presence of above conditions.
Here is the online working demo of above RegEx

A: Try preg_match_all(/cat.+dog(.+play){2}/i,$str,$out);


text:
Q: Finding the $n^{th}$ term of a particular recursive sequence. Just recently, I encountered this problem.

Prove or disprove that the $n^{th}$ term of the sequence
$$a_0=0$$
$$a_1=1$$
$$\vdots$$
$$a_k=2\bigg(a_{k-1}+2^{k-1}-2^{k-2}-\bigg\lfloor \frac{2^{k-2}-1}{3}\bigg\rfloor\bigg)-1$$
is given by
$$a_n=\frac{(3n+1)\cdot2^n-(-1)^n}{9}.$$

In an attempt to disprove the problem, I tried to solve for the value of $a_k$ for $k=0,1,\ldots,9$. However, the result of the computations tend to show that the formula for the $n^{th}$ term of the sequence above seems to be correct. So my task now is to prove that the formula for the $n^{th}$ term of the sequence is correct. However, I do not know how to begin.
Any suggestion/answer on how to solve the problem? In general, are there any available method on how to find the $n^{th}$ term of a recursive sequence such as the one above?

A: $a_k=2a_{k-1}+2(2^{k-1}-2^{k-2})-2\lfloor\frac{2^{k-2}-1}{3}\rfloor-1=2a_{k-1}+2^{k-1}-1-2\lfloor\frac{2^{k-2}-1}{3}\rfloor$.
We want to prove that $a_n=\frac{(3n+1)2^n-(-1)^n}{9}$ so assume that this is true for any $n<k$ (this is the induction hypothesis). Now we will prove it is also true for $k$ which finishes our proof.
$a_k=\frac{(3k+1)2^k-(-1)^k}{9}$ $\Leftrightarrow$ $\frac{(3k+1)2^k-(-1)^k}{9}=2a_{k-1}+2^{k-1}-1-2\lfloor\frac{2^{k-2}-1}{3}\rfloor=\frac{2((3(k-1)+1)2^{k-1}-(-1)^{k-1})}{9}+2^{k-1}-1-2\lfloor\frac{2^{k-2}-1}{3}\rfloor$ (we replaced $a_{k-1}$ using our induction hypothesis)
So we have $3k\times2^k+2^k-(-1)^k=2(3k\times2^{k-1}-2^k)-2(-1)^{k-1}+9\times2^{k-1}-9-18\lfloor\frac{2^{k-2}-1}{3}\rfloor$ Simplfying, we get
$2^k-(-1)^k=2^{k-1}+2^{k+2}-2^{k+1}-2(-1)^{k-1}-9-18\lfloor\frac{2^{k-2}-1}{3}\rfloor$ $\Leftrightarrow$ $9+18\lfloor\frac{2^{k-2}-1}{3}\rfloor=2^{k-1}+2^k+(-1)^k-(-1)^{k-1}$
If $k$ is even then $18\lfloor\frac{2^{k-2}-1}{3}\rfloor=6(2^{k-2}-1)$ so we have $9+6(2^{k-2}-1)=2^{k-1}+2^k+(-1)^k-2(-1)^{k-1}$ $\Leftrightarrow$ $3=3$
If $k$ is odd, $18\lfloor\frac{2^{k-2}-1}{3}\rfloor=6(2^{k-2}-2)$ so from the same analysis we get the result.
So we win! $a_n=\frac{(3n+1)2^n-(-1)^n}{9}$


text:
Q: How to use tab to go to a certain input? Currently when the user presses tab in the qty text box it does not tab to the add line image.
I want to add some jQuery in which would make it so that when the user presses the tab key within the qty text box it tabs to the add image where the user can click enter.
<td>
    <input type="text" name="qty" id="qty" maxlength="3" class="txt" style="width: 80px;" />
</td>
<td>
    <input type="image" src="/gfx/btn_addline.jpg" name="Add" value="Add" id="add"/>
</td>

Jquery affecting qty:
 $("#qty").keydown(function (event) {
            //alert(event.keyCode);
            if (event.keyCode == 13) {
                $("#add").click();
                return false;
            }
        });
   $("#qty").keydown(function (event) {
            // Allow only backspace and delete
            if (event.keyCode == 46 || event.keyCode == 8) {
                // let it happen, don't do anything
            }
            else {
                // Ensure that it is a number and stop the keypress
                if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) {
                    event.preventDefault();
                }
            }
        });

A: Assuming I've understood your question correctly, you should just use the tabindex attribute, which doesn't require any JavaScript:
<input type="text" tabindex="1"> <!--First input-->
<input type="text" tabindex="2"> <!--Press tab, you will end up here-->

Update (see comments)
If you already use tabindex to control tab order elsewhere on your page, just use higher indexes here. For example, if indexes 1-10 are used on other elements, use 11 and 12 here:
<input type="text" tabindex="11"> <!--First input-->
<input type="text" tabindex="12"> <!--Press tab, you will end up here-->

Update 2 (see updated question)
You are preventing the tab key from doing anything in your keydown event handler. Change to the following (add another condition that checks for the tab key):
if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9) {
    // let it happen, don't do anything
}

This will work without the need for tabindex, assuming your two inputs are in order in your code and there are no inputs between them. If there are, use tabindex as well.
As a side note, you should use event.which instead of keyCode, since jQuery uses it to normalise browser inconsistencies.

A: i think this will do the trick
$("#qty").keyup(function(event){
  if(event.keyCode=='9') { //9 is the tab key
    $("#add").focus();
  }
});

A: $("#qty").keyup(function(event){
  if(event.keyCode=='9') { //9 is the tab key
    $("#add").focus();
    $("#add").select();
  }
});

Can you try focus and select together for Image field.


text:
Q: Java String Contains I know that there are other questions like this and I did have a look at them but it did not work for me.
String one= "ROLEAWARDS ROLEMOVIES ROLENOMINATIONS";
String two = "ROLENOMINATIONS ROLEAWARDS ROLEMOVIES";
if(one.contains(two) || two.contains(one))
{
    System.out.println("Contains");
}
else
    System.out.println("Doesn't Contain");

This is my code and even though one contains two and two also contains one, it always prints that string one doesn't contain string two

A: You could do something like:
String one= "ROLEAWARDS ROLEMOVIES ROLENOMINATIONS";
String two = "ROLENOMINATIONS ROLEAWARDS ROLEMOVIES";
String oneArray[] = one.split("\\s+");
String twoArray[] = one.split("\\s+");
Arrays.sort(oneArray);
Arrays.sort(twoArray);
if(Arrays.equals(oneArray, twoArray))
{
    System.out.println("Contains");
}
else
    System.out.println("Doesn't Contain");
}

A: That's because you're comparing the whole String, and apparently you seem to be thinking it checks every substring split at the space which honestly doesn't work that way (it would be unintuitive too).
So,
String one= "ROLEAWARDS ROLEMOVIES ROLENOMINATIONS";
String two = "ROLENOMINATIONS ROLEAWARDS ROLEMOVIES";

String[] oneSplit = one.split(" ");
String[] twoSplit = two.split(" ");
boolean contains = false;
for(int i = 0; i < oneSplit.length; i++)
{
    for(int j = 0; j < twoSplit.length; j++)
    {
        if(oneSplit[i].contains(twoSplit[j])
        {
            contains = true;
            break;
        }
    }
}
if(contains)
{
    System.out.println("Contains");
}
else
{
    System.out.println("Doesn't Contain");
}

A: The contains() method returns true if and only if this string contains the specified sequence of char values. And in your code, the sequence of characters in each string is different from the other hence why in your code it returns false and prints that string one doesn't contain string two. The key thing here is the sequence of characters in each string.

A: .contains() function did not check they have common words or not.
  It's check whether your one string is subset of other.
  in your case both strings are not subset of each other
    String one= "ROLEAWARDS ROLEMOVIES ROLENOMINATIONS";
    String two= "ROLEMOVIES";
    if(one.contains(two) || two.contains(one))
    {
        System.out.println("Contains");
    }
    else
        System.out.println("Doesn't Contain");

Now it will print "Contains".
Plz read here in detail about .contain()

A: those two string are not same.
String one= "ROLEAWARDS ROLEMOVIES ROLENOMINATIONS";
String two = "ROLENOMINATIONS ROLEAWARDS ROLEMOVIES";
 if(one.contains(two) || two.contains(one))
        one.contains(two) will be  true if two is a subset of one
        two.contains(one)   will be  true if one is a subset of two

So the result is correct . as none of them is a subset of another.


text:
Q: Collect static error while deploying django project to heroku I am trying to finish a youtube tutorial by Dennis Ivy and while deploying to heroku get the following error. Already hooked static and database to AWS.
remote: -----> $ python manage.py collectstatic --noinput
remote:        Traceback (most recent call last):
remote:          File "manage.py", line 15, in <module>
remote:            execute_from_command_line(sys.argv)
remote:          File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
remote:            utility.execute()
remote:          File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute
remote:            self.fetch_command(subcommand).run_from_argv(self.argv)
remote:          File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 328, in run_from_argv
remote:            self.execute(*args, **cmd_options)
remote:          File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 369, in execute
remote:            output = self.handle(*args, **options)
remote:          File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle
remote:            collected = self.collect()
remote:          File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 113, in collect
remote:            handler(path, prefixed_path, storage)
remote:          File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 338, in copy_file
remote:            if not self.delete_file(path, prefixed_path, source_storage):
remote:          File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 248, in delete_file
remote:            if self.storage.exists(prefixed_path):
remote:          File "/app/.heroku/python/lib/python3.7/site-packages/storages/backends/s3boto3.py", line 562, in exists
remote:            self.connection.meta.client.head_object(Bucket=self.bucket_name, Key=name)
remote:          File "/app/.heroku/python/lib/python3.7/site-packages/botocore/client.py", line 316, in _api_call
remote:            return self._make_api_call(operation_name, kwargs)
remote:          File "/app/.heroku/python/lib/python3.7/site-packages/botocore/client.py", line 599, in _make_api_call
remote:            api_params, operation_model, context=request_context)
remote:          File "/app/.heroku/python/lib/python3.7/site-packages/botocore/client.py", line 645, in _convert_to_request_dict
remote:            api_params, operation_model, context)
remote:          File "/app/.heroku/python/lib/python3.7/site-packages/botocore/client.py", line 677, in _emit_api_params
remote:            params=api_params, model=operation_model, context=context)
remote:          File "/app/.heroku/python/lib/python3.7/site-packages/botocore/hooks.py", line 356, in emit
remote:            return self._emitter.emit(aliased_event_name, **kwargs)
remote:          File "/app/.heroku/python/lib/python3.7/site-packages/botocore/hooks.py", line 228, in emit
remote:            return self._emit(event_name, kwargs)
remote:          File "/app/.heroku/python/lib/python3.7/site-packages/botocore/hooks.py", line 211, in _emit
remote:            response = handler(**kwargs)
remote:          File "/app/.heroku/python/lib/python3.7/site-packages/botocore/handlers.py", line 223, in validate_bucket_name
remote:            if not VALID_BUCKET.search(bucket) and not VALID_S3_ARN.search(bucket):
remote:        TypeError: expected string or bytes-like object
remote:
remote:  !     Error while running '$ python manage.py collectstatic --noinput'.
remote:        See traceback above for details.
remote:
remote:        You may need to update application code to resolve this error.
remote:        Or, you can disable collectstatic for this application:
remote:
remote:           $ heroku config:set DISABLE_COLLECTSTATIC=1
remote:
remote:        https://devcenter.heroku.com/articles/django-assets
remote:  !     Push rejected, failed to compile Python app.
remote:
remote:  !     Push failed
remote: Verifying deploy...
remote:
remote: !       Push rejected to zakirzeynalov-crm1.
remote:
To https://git.heroku.com/zakirzeynalov-crm1.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/zakirzeynalov-crm1.git'

This is the whole settings file:
import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'cz=&%f*9(d*zo$_55p=(p)(eki#p$pb^0159-)8k^6$9c3l&_b'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

ALLOWED_HOSTS = ['zakirzeynalov-crm1.herokuapp.com', '127.0.0.1']

# Application definition

INSTALLED_APPS = [
    'accounts.apps.AccountsConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'django_filters',

    'storages',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',

    'whitenoise.middleware.WhiteNoiseMiddleware',

    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'crm1.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'crm1.wsgi.application'

# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
db_pass = os.environ.get('db_pass')

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'database_1',
        'USER': 'zakirzeynalov',
        'PASSWORD': db_pass,
        'HOST': 'database-1.csx4yzqz2jb9.eu-central-1.rds.amazonaws.com',
        'PORT': '5432',
    }
}

# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

STATIC_URL = '/static/'

MEDIA_URL = '/images/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static')
]

MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images')

#SMTP Configuration

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = '*********'
EMAIL_HOST_PASSWORD = '*********'

AWS_S3_HOST = 's3.eu-central-1.amazonaws.com'
AWS_S3_REGION_NAME = 'eu-central-1'

crm_aws_id = os.environ.get('crm-aws-id')
crm_aws_key = os.environ.get('crm-aws-key')
crm_bucket_name = os.environ.get('crm-bucket-name')

AWS_ACCESS_KEY_ID = crm_aws_id
AWS_SECRET_ACCESS_KEY = crm_aws_key
AWS_STORAGE_BUCKET_NAME = crm_bucket_name
AWS_S3_FILE_OVERWRITE = False
AWS_DEFAULT_ACL = None
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'

This is the structure of my project(crm1 is main app, accounts secondary. Both contain standard thing inside.):
--crm1 --crm1
       --accounts
       --static --images
                --css
       --manage.py
       --procfile
       --requirements.txt
       --runtime

Tried to solve, but couldn't manage. Any ideas are much appreciated.

A: from docs :
http://whitenoise.evans.io/en/stable/django.html
you dont have STATICFILES_STORAGE =
add to your settings.py:
STATICFILES_STORAGE =
'whitenoise.storage.CompressedStaticFilesStorage'

EDIT:
it looks like you are using Whitenoise. Whitenoise allows django to serve its static files. It is different approach if you want to serve them from AWS.
So, you need to remove Whitenoise in order to utilize django-storages. Remove it from settings, middleware, wsgi.py, etc.