text:
Q: Is there a R function for AES mapping to plot the mean of X variable instead of sum? Hi I would like to ask for the aes mapping, if I want to have the mean of wages based on age group but I do not want to adjust the data table, is there a function I can call in the ggplot to have the mean wages based on their age group?

ab_final <- ab %>%
  group_by(agegroup,haveKids,educationLevel) %>%
  summarise(Wage = mean(Wage), Expenses = mean(Expenses)) %>%
  mutate(Wage = ifelse(haveKids, -Wage, Wage), Expenses = ifelse(haveKids,Expenses,-Expenses))
head (ab_final)

agegroup
haveKids
educationLevel
Wage
Expenses

18-25
FALSE
Bachelors
73428.
18582.

18-25
FALSE
Graduate
90757.
21441.

18-25
FALSE
HighSchoolOrCollege
36027.
15956.

18-25
FALSE
Low
36598.
19367.

18-25
TRUE
Bachelors
-98265.
-24964.

18-25
TRUE
Graduate
-111545.
-25002.

p <- ggplot(ab_final, aes(x = Wage, y = agegroup, fill = haveKids)) +
  geom_col() +
  scale_x_continuous(breaks = seq(-60000, 60000, 30000),
                     labels = paste0("$",as.character(c(seq(60, 0, -30), seq(30, 60, 30))),"k")) +
  labs (x = "Annual Average Wage (USD)", y = "Age Group", title='Ohio Annual Average Wages based on Age Group') +
  theme_bw() +
  theme(axis.ticks.y = element_blank()) +
  scale_fill_manual(values = c("TRUE" = "lightblue", "FALSE" = "lightpink"))

p

The output gives me the sum of wages based on the different age group.
dput(ab_final)

structure(list(agegroup = c("18-25", "18-25", "18-25", "18-25",
"18-25", "18-25", "18-25", "18-25", "26-30", "26-30", "26-30",
"26-30", "26-30", "26-30", "26-30", "26-30", "31-35", "31-35",
"31-35", "31-35", "31-35", "31-35", "31-35", "31-35", "36-40",
"36-40", "36-40", "36-40", "36-40", "36-40", "36-40", "36-40",
"41-45", "41-45", "41-45", "41-45", "41-45", "41-45", "41-45",
"41-45", "46-50", "46-50", "46-50", "46-50", "46-50", "46-50",
"46-50", "46-50", "51-55", "51-55", "51-55", "51-55", "51-55",
"51-55", "51-55", "51-55", "56-60", "56-60", "56-60", "56-60",
"56-60", "56-60", "56-60", "56-60"), haveKids = c(FALSE, FALSE,
FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE,
TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE,
TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE,
FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE,
FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE,
TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE,
TRUE, TRUE), educationLevel = c("Bachelors", "Graduate", "HighSchoolOrCollege",
"Low", "Bachelors", "Graduate", "HighSchoolOrCollege", "Low",
"Bachelors", "Graduate", "HighSchoolOrCollege", "Low", "Bachelors",
"Graduate", "HighSchoolOrCollege", "Low", "Bachelors", "Graduate",
"HighSchoolOrCollege", "Low", "Bachelors", "Graduate", "HighSchoolOrCollege",
"Low", "Bachelors", "Graduate", "HighSchoolOrCollege", "Low",
"Bachelors", "Graduate", "HighSchoolOrCollege", "Low", "Bachelors",
"Graduate", "HighSchoolOrCollege", "Low", "Bachelors", "Graduate",
"HighSchoolOrCollege", "Low", "Bachelors", "Graduate", "HighSchoolOrCollege",
"Low", "Bachelors", "Graduate", "HighSchoolOrCollege", "Low",
"Bachelors", "Graduate", "HighSchoolOrCollege", "Low", "Bachelors",
"Graduate", "HighSchoolOrCollege", "Low", "Bachelors", "Graduate",
"HighSchoolOrCollege", "Low", "Bachelors", "Graduate", "HighSchoolOrCollege",
"Low"), Wage = c(73427.6242255194, 90756.8740271891, 36027.1045766046,
36597.8823458904, -98265.2264842072, -111544.761238973, -40888.1302113056,
-29690.7404136359, 63434.2899782702, 79826.8839356714, 32912.6351345271,
28951.8407896055, -67638.6009175875, -98570.8320239257, -46688.2105971457,
-2365.18889956123, 73507.9183782092, 83276.4013393718, 35053.1036609163,
35918.5441251045, -105208.124255318, -100419.654285681, -48013.5199894127,
-31465.9994442994, 73863.5692259624, 91219.6688660635, 37944.7293875051,
24295.1828359983, -71489.157887881, -113628.534898322, -40874.9689695586,
-15048.4351165345, 63622.1379383326, 76162.2011422263, 35856.5165542073,
35290.3184801558, -90556.4678989271, -139740.754762728, -47300.5763646887,
-2351.94028134572, 57111.653529917, 88916.5286764648, 34743.1169364354,
33034.2740885343, -102954.526388641, -110730.908830255, -44183.0808505653,
-2431.62242073533, 75520.2374263526, 97118.4509577243, 40206.2010005338,
15303.2183724372, -100459.961036613, -118603.619362369, -47062.636642258,
-18136.0117958843, 68441.752176008, 78569.1358672976, 33696.7694674256,
39621.6228202485, -96083.9762853549, -113037.604308105, -39670.0761714582,
-76544.9368650725), Expenses = c(18581.7882554702, 21441.1145218955,
15955.8190788926, 19366.6794157381, -24963.6038601631, -25001.8628498845,
-18052.2160481047, -12745.725568342, 19825.5493832019, 21067.8133641346,
15513.3625856376, 12853.4842200847, -26688.4009083829, -25557.0157549876,
-19718.5033101881, -152.186005570974, 21576.3976579329, 22632.772851812,
14712.230494066, 20079.6454981138, -24514.3995124845, -31520.0721153124,
-17579.291010834, -15501.7362071054, 20980.2291762055, 21389.5574110701,
15308.3678040099, 16557.8188855836, -24639.7689642704, -26130.2577363506,
-15954.9566546377, -7768.13947033146, 20491.8443246166, 17922.4189300169,
16909.3747309647, 13233.3579986897, -23432.693758128, -22597.7448653988,
-20468.0995939873, -123.331037209483, 22093.8122932499, 19918.1372430818,
16884.6652423487, 15485.6086554647, -23946.2595731495, -22228.0345344589,
-20282.1042419724, -171.43286214832, 19531.7423065772, 20657.0373190312,
16615.5145240842, 6467.10392954871, -26143.4628401692, -22481.8353859449,
-19962.9682370225, -9238.12956845112, 21714.2834145535, 23397.9260820337,
15825.4708571827, 18634.178657809, -23591.149852639, -25458.1674870612,
-16577.2976554664, -24842.1579584659)), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -64L), groups = structure(list(
    agegroup = c("18-25", "18-25", "26-30", "26-30", "31-35",
    "31-35", "36-40", "36-40", "41-45", "41-45", "46-50", "46-50",
    "51-55", "51-55", "56-60", "56-60"), haveKids = c(FALSE,
    TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE,
    FALSE, TRUE, FALSE, TRUE, FALSE, TRUE), .rows = structure(list(
        1:4, 5:8, 9:12, 13:16, 17:20, 21:24, 25:28, 29:32, 33:36,
        37:40, 41:44, 45:48, 49:52, 53:56, 57:60, 61:64), ptype = integer(0), class = c("vctrs_list_of",
    "vctrs_vctr", "list"))), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -16L), .drop = TRUE))

A: I am not sure if I understand your question correctly, but you can use the stat_summary with fun to calculate the mean like,   stat_summary(geom = "col", fun.y = mean), using the following code:
p <- ggplot(ab_final, aes(x = Wage, y = agegroup, fill = haveKids)) +
  stat_summary(geom = "col", fun.y = mean) +
  scale_x_continuous(breaks = seq(-60000, 60000, 30000),
                     labels = paste0("$",as.character(c(seq(60, 0, -30), seq(30, 60, 30))),"k")) +
  labs (x = "Annual Average Wage (USD)", y = "Age Group", title='Ohio Annual Average Wages based on Age Group') +
  theme_bw() +
  theme(axis.ticks.y = element_blank()) +
  scale_fill_manual(values = c("TRUE" = "lightblue", "FALSE" = "lightpink"))

p

Output:

A: This is a stab in the dark since I do not understand the negative salaries...  Perhaps you should consider converting agegroup, haveKids and educationalLevel to factors.
ab$agegroup <- as.factor(ab$agegroup)
ab$haveKids <- as.factor(ab$haveKids)
ab$educationLevel <- as.factor(ab$educationLevel)

pFinal <- ggplot(ab_final, aes(x=agegroup, y=Wage/1000, color=haveKids, label=educationLevel)) +

  geom_jitter(width=.2, alpha=.5, size=2) +
  scale_color_manual(values=c("brown", "steelblue")) +

  ## scales = "free"   each facit has its own scale ****
  #  facet_grid(rank ~ discipline, scales="free") +
  theme_bw() +
  theme(legend.position="none") +
facet_grid(educationLevel ~ agegroup, scales="free") +
  theme_bw() +
  theme(legend.position="none") +
  labs(title = "Salaries by age group and educational level", y="")
ggplotly(pFinal)


text:
Q: Left CTRL key is not working after updating to 18.04 After I updated to Ubuntu 18.04 my left Ctrl key is not working neither is the shortcut using fn fn to turn on/off touchpad. I have Asus K55UQ.

A: Try Resetting keyboard shortcuts in Settings > Devices > Keyboard.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python throwing multiple argument error when there is only one I'm calling a method in another class and I'm getting the following error.  This is the class that declares & defines the method:
from web import Web
import ast

class WebCrawler:
    web = Web()

    def crawl(self):
        root = self.root()
        URL = ast.literal_eval(self.get(root))
        return URL

And this is the class that calls it:
from web import Web
from crawler import WebCrawler

web = Web()
crawler = WebCrawler()
urls = crawler.crawl(web)

print(urls)

But the error is this:
Traceback (most recent call last):
  File "/home/onur/Desktop/web-crawler/test-run.py", line 6, in <module>
    urls = crawler.crawl(web)
TypeError: crawl() takes 1 positional argument but 2 were given

A: Instance methods are implicitly passed the instance as the first argument (self). That means crawler.crawl(web) gets turned into WebCrawler.crawl(crawler, web).
I'm not sure how to fix it since I'm not familiar with these modules, but I would guess that crawl is supposed to take an argument, since WebCrawler doesn't have a root method:
def crawl(self, arg):
    root = arg.root()
    ...


text:
Q: Why does my node.js express code not call console.log()? How come "homepage requested" never gets output to the terminal console when I run server.js and go to localhost:8000? index.html renders fine
server.js
var express = require("express");
var path = require('path');
var index = require('./routes/index');

var app = express();

var port = 8000;
app.set("views", path.join(__dirname, 'views'));
app.set("view engine", "ejs");
app.engine("html", require("ejs").renderFile);

app.use(express.static(path.join(__dirname, 'client')));

app.use('/', index);

app.listen(port, function() {
  console.log("server started on port", port);
});

index.js
var express = require('express');
var router = express.Router();

router.get('/', function(req, res, next) {
  console.log('homepage requested'); // never executes
  res.render('index.html');          // always executes
});

module.exports = router;

A: console.log('homepage requested') will print the message in the terminal, not in the browser. If you run your server with command line node index, and then open your page, in the terminal you will see the message.

A: It has to do with the way you use app.use(express.static(path.join(__dirname, 'client')));
If you take it out you should be able to see the console.log
It appears that if no mount path in the app.use and it sees a route with "/" (home route) it just serves up the static file from the express.static. It doesn't continue with any consoles.
A possible workaround for getting the console.log is to do a URL check in the app.use and that will only print out the home page.
app.use("/", (req, res, next) => {
    if (req.url == "/") {
        console.log("just hompage")

    }
    return next()

}, express.static(path.join(__dirname, "client/build")))

I think part of the reason why this is happening is that express.static ends the response. and you can't console anything after that. I think you don't even need the app.get("/") or router.get("/") because it by default if there is no mount path it work on "/" route. So it sends file automatically.
I think express.static runs on every route hit to check for static files.

A: In my case, I found that it was writing my console log, but then generating a lot of other messages afterwards, so I had to scroll the terminal back. At first I thought it meant the server was restarting after a file save or crash, so I didn't bother to scroll back, which is why I started searching online. This is different from the way it behaved for me in the past, where my logs were closer to the end.

A: express won't output console.log to the terminal unless you set the DEBUG environment variable to express:*
https://expressjs.com/en/guide/debugging.html

A: You have an index file with the same name as the route.
Where you add the route,
     app.use('/', index);
This won't get called if the index.html file exists and is already served up (as the file has the same name as the route).
Change the name of index.html to index2.html.  Then do this
var express = require('express');
var router = express.Router();

router.get('/', function(req, res, next) {
    console.log('homepage requested'); // never executes
    res.render('index2.html');          // always executes
 });

module.exports = router;

Your console should now show your message.


text:
Q: Keeping rotated divs from expanding on page resize I have two divs that are rotated and should maintain the same distance as the page expands, as well as not grow. However, as they are currently setup, they expand and the space between them grows. I need them to maintain their distance and width as the page expands and not sure why they aren't as they're currently set:

Left

Right

.masthead-wrapper {
  z-index: 0;
  width: 100%;
  margin-bottom: 10px;
  .masthead-content {
    position: relative;
    display: flex;
    width: 1172px;
    background-color: #fff;
    margin: 0 auto;
  }
  .masthead-two-boxes-angled-wrapper {
    height: 400px;
    margin: 0 auto;
    display: flex;
    z-index: 0;
    transform: rotate(-45deg);
    .left {
      width: 45%;
      background-color: #eee;
      height: 100%;
      margin: 0 auto;
      top: -20px;
      position: relative;
    }
    .right {
      width: 40%;
      background-color: #eee;
      height: 100%;
      margin: 0 auto;
      bottom: 20px;
      position: relative;
      box-shadow: 0 -22px 29px 10px #cecece;
    }
  }
}

JSFIDDLE: Link

A: They are responding as the screen width changes because your width set on the .masthead-wrapper is a percentage. Changing it to a pixel width will prevent the resizing from happening. However, with a pixel width you may have to set up different breakpoints to adjust for how you want the left and right boxes to appear on desktop, tablet, and mobile.
Example:
.masthead-wrapper {
    z-index: 0;
    width: 100%;
    margin-bottom: 10px;

    /* Tablet */
    @media (min-width: 480px) {
        width: 400px;
    }

    /* Desktop */
    @media (min-width: 960px) {
        width: 600px;
    }
}

Also, you have a class being styled that is not referenced in the HTML (.masthead-content). You can remove this completely unless you need it for some other reason. Hope this helps.
Updated fiddle: http://jsfiddle.net/meq31d0x/25/


text:
Q: What string of characters should a source send to disambiguate the byte-encoding they are using? I'm decoding bytestreams into unicode characters without knowing the encoding that's been used by each of a hundred or so senders.
Many of the senders are not technically astute, and will not be able to tell me what encoding they are using. It will be determined by the happenstance of the toolchains they are using to generate the data.
The senders are, for the moment, all UK/English based, using a variety of operating systems.
Can I ask all the senders to send me a particular string of characters that will unambiguously demonstrate what encoding each sender is using?
I understand that there are libraries that use heuristics to guess at the encoding - I'm going to chase that up too, as a runtime fallback, but first I'd like to try and determine what encodings are being used, if I can.
(Don't think it's relevant, but I'm working in Python)

A: A full answer to this question depends on a lot of factors, such as the range of encodings used by the various upstream systems, and how well your users will comply with instructions to type magic character sequences into text fields, and how skilled they will be at the obscure keyboard combinations to type the magic character sequences.
There are some very easy character sequences which only some users will be able to type. Only users with a Cyrillic keyboard and encoding will find it easy to type "Ильи́ч" (Ilyich), and so you only have to distinguish between the Cyrillic-capable encodings like UTF-8, UTF-16, iso8859_5, and koi8_r. Similarly, you could come up with Japanese, Chinese, and Korean character sequences which distinguish between users of Japanese, simplified Chinese, traditional Chinese, and Korean systems.
But let's concentrate on users of western European computer systems, and the common encodings like ISO-8859-15, Mac_Roman, UTF-8, UTF-16LE, and UTF-16BE. A very simple test is to have users enter the Euro character '€', U+20AC, and see what byte sequence gets generated:

*

*byte ['\xa4'] means iso-8859-15 encoding

*bytes ['\xe2', '\x82', '\xac'] mean utf-8 encoding

*bytes ['\x00', '\xac'] mean utf-16be encoding

*bytes ['\xac', '\x00'] mean utf-16le encoding

*byte ['\x80'] means cp1252 ("Windows ANSI") encoding

*byte ['\xdb'] means macroman encoding

*iso-8859-1 won't be able to represent the Euro character at all. iso-8859-15 is the Euro-supporting successor to iso-8859-1.

*U.S. users probably won't know how to type a Euro character. (OK, that's too snarky. 3% of them will know.)

You should check what each of these byte sequences, interpreted as any of the possible encodings, is not a character sequence that users would likely type themselves.  For instance, the '\xa4' of the iso-8859-15 Euro symbol could also be the iso-8859-1 or cp1252 or UTF-16le encoding of '¤', the macroman encoding of '§', or the first byte of any of thousands of UTF-16 characters, such as U+A4xx Yi Syllables, or U+01A4 LATIN SMALL LETTER OI. It would not be a valid first byte of a UTF-8 sequence. If some of your users submit text in Yi, you might have a problem.
The Python 3.x documentation, 7.2.3. Standard Encodings lists the character encodings which the Python standard library can easily handle. The following program lets you see how a test character sequence is encoded into bytes by various encodings:
>>> for e in ['iso-8859-1','iso-8859-15', 'utf-8', 'utf-16be', 'utf-16le', \
... 'cp1252', 'macroman']:
...     print e, list( euro.encode(e, 'backslashreplace'))

So, as an expedient, satisficing hack, consider telling your users to type a '€' as the first character of a text field, if there are any problems with encoding. Then your system should interpret any of the above byte sequences as an encoding clue, and discard them. If users want to start their text content with a Euro character, they start the field with '€€'; the first gets swallowed, the second remains part of the text.


text:
Q: Change position to the default main menu of a theme Maybe the question is silly, but I just start to look into Drupal and I cannot find any relatives information on the web.
I have installed a theme (corporate clean) that use a inline main navigation just after the logo and before the gallery.
I would like to change that menu position. Move the main menu on the left side.
But everytime I give to navigation or main menu block the 'navigation' position, I see a new block filled in with the same main menu links.
Instead I want the first link be relocated in the left side.
How could I do that?
(btw the theme has even a navigation block, but it cannot understand how it work exactly..)
thanks

A: The menu is usualy inserted in the page.tpl.php you can move it around in this file.
Alternatively you can go to admin/appearance/settings/yourTheme and turn off "Main menu" and "Secondary menu" and use the Menu block module to position menus where you want them.

A: Do you mean you want the main menu (that is initially in the "navigation" area, like horizontally) in a new column on the left side, like vertically?
If yes, just go in administration>structure>blocks and drag your "Main Menu" in "First Lateral Bar" area (under Content, in Coporate Clean theme). Save and check the result.
If not, do you want your Main menu just like it is now but aligned left instead of right? If yes, just play with CSS.


text:
Q: When does an atomic topos have this property? If $f:\mathbb{E}\to\mathbf{Set}$ is an atomic (or locally connected if you prefer) Grothendieck topos, when is it the case that the direct image functor $f_*:\mathbb{E}\to \mathbf{Set}$ is faithful?

A: There is only one possible direct image functor $\Gamma : \mathcal{E} \to \mathbf{Set}$, namely the one represented by the terminal object of $\mathcal{E}$. In particular, $\Gamma : \mathcal{E} \to \mathbf{Set}$ is faithful if and only if $1$ is a separator. But $1$ is a separator if and only if $\mathcal{E} \simeq \mathbf{Set}$ or $\mathcal{E} \simeq \mathbb{1}$.


text:
Q: Error after installing mod_xmlrpc in ejabberd I am working on a java project in which i have to communicate with the ejabberd (create/delete a jabber user etc.. ) xmpp server. From the different suggestions available in the internet I understood that xml rpc one method to achieve that.
I tried to install the mod_xmlrpc as per the suggesions in this thread. Error while starting ejabberd with xml_rpc
But I had failed to start the ejabberd after configuration of mod_xmlrpc. The ejabberd log says,
=ERROR REPORT==== 2015-03-15 20:23:27 ===
C(<0.42.0>:gen_mod:75) : Problem starting the module mod_adhoc for host "example.com"
 options: []
 exit: {noproc,
       {gen_server,call,
           [ejabberd_iq_sup,
        {start_child,["example.com",mod_adhoc,process_local_iq]},
        infinity]}}

=ERROR REPORT==== 2015-03-15 20:23:27 ===
C(<0.42.0>:gen_mod:80) : ejabberd initialization was aborted because a module start failed.

and the erlang log says,
=CRASH REPORT==== 15-Mar-2015::20:23:27 ===
  crasher:
    initial call: supervisor:ejabberd_listener/1
    pid: <0.270.0>
    registered_name: []
    exception exit: {undef,
            [{ejabberd_xmlrpc,socket_type,[],[]},
             {ejabberd_listener,'-bind_tcp_ports/0-fun-0-',1,
                 [{file,"ejabberd_listener.erl"},{line,63}]},
             {lists,foreach,2,[{file,"lists.erl"},{line,1323}]},
             {ejabberd_listener,init,1,
                 [{file,"ejabberd_listener.erl"},{line,52}]},
             {supervisor,init,1,
                 [{file,"supervisor.erl"},{line,239}]},
             {gen_server,init_it,6,
                 [{file,"gen_server.erl"},{line,304}]},
             {proc_lib,init_p_do_apply,3,
                 [{file,"proc_lib.erl"},{line,239}]}]}
      in function  gen_server:init_it/6 (gen_server.erl, line 328)
    ancestors: [ejabberd_sup,<0.42.0>]
    messages: []
    links: [#Port<0.3747>,<0.234.0>,#Port<0.3744>]
    dictionary: []
    trap_exit: true
    status: running
    heap_size: 987
    stack_size: 27
    reductions: 1215
  neighbours:

=SUPERVISOR REPORT==== 15-Mar-2015::20:23:27 ===
     Supervisor: {local,ejabberd_sup}
     Context:    start_error
     Reason:     {undef,
             [{ejabberd_xmlrpc,socket_type,[],[]},
              {ejabberd_listener,'-bind_tcp_ports/0-fun-0-',1,
              [{file,"ejabberd_listener.erl"},{line,63}]},
              {lists,foreach,2,[{file,"lists.erl"},{line,1323}]},
              {ejabberd_listener,init,1,
              [{file,"ejabberd_listener.erl"},{line,52}]},
              {supervisor,init,1,[{file,"supervisor.erl"},{line,239}]},
              {gen_server,init_it,6,
              [{file,"gen_server.erl"},{line,304}]},
              {proc_lib,init_p_do_apply,3,
              [{file,"proc_lib.erl"},{line,239}]}]}
     Offender:   [{pid,undefined},
          {name,ejabberd_listener},
          {mfargs,{ejabberd_listener,start_link,[]}},
          {restart_type,permanent},
          {shutdown,infinity},
          {child_type,supervisor}]

Since I am a newbie to the ejabberd & erlang world I am finding it hard to track the root cause. Please help me to identify the root cause of this crash.
BTW is there any other method for communicating with ejabberd (create/delete a jabber user etc..) from java services ?

A: The erlang log says that it can't find the function socket_type with no argument in the module ejabberd_xmlrpc. As it is a valid call, and both the module and function exist in the application ejabberd, this means that something went wrong during installation (compilation fails, wrong path ???)


text:
Q: How to use Travis CI with some files in gitignore? I have a Flask app that has its configurations in a file called settings.py. I've put this file in .gitignore because the project is in a public repo. Travis-CI was working before I added tests into my project even though settings.py was in .gitignore. After adding tests to the project, the build started failing with the following output:
Debugged import:

- 'settings' not found.

Original exception:

ImportError: No module named 'settings'

My .travis.yml file looks like this:
language: python
python:
  - "3.4"
  - "3.5"

# command to install dependencies
install:
  - pip install -r requirements.txt
# command to run tests
script: python tests.py

Does this mean that in order to use travis-ci, we have to include all necessary files in the repo? Or is there a workaround? The repo on GitHub can be found here.

A: @dirn's comment of using a default settings.py file and then overriding some settings with encrypted environment variables on Travis is a good idea, certainly worth it if there are only a couple of differences.
However, if you can't be bothered or it's too complicated breaking up your settings, you could install the Ruby Travis command line client gem, which is useful for quite a few things.
With the client on your machine you can use Travis' file encryption feature to encrypt your whole settings.py file, and then commit the encrypted version (which will have an .enc file extension) to GitHub. Travis will then be able to decrypt the file during the CI run, as long as you add the right commands to the .travis.yml file, say in a before_install step. Detailed instructions are on the file encryption page.

A: I did a trick in .travis.yml
After commit and before Travis build, create the ignored file like this:
before_install:
- cp .ignored.file.copy ignored.file

This way, the build will succeed without the actual gitignore-ed file.


text:
Q: Reach A Target number only using other two numbers I am having two numbers L and R, L means left and R means Right.
I have to get to a certain number(F) using L and R.
Every time i have to start with zero as initial.
Example :
L : 1
R : 2
F : 3
SO minimum number of steps needed to get to F is 3.
Ans : First R, Second R, Third L.
IN this way i need to find the minimum number of ways to do it.
My approach:

Quo = F/R;
Remain : F%R;

x*R-Y*L = Remain
==> (x*R - Remain)/L = Y
this equation is break when (x*R - Remain)%L = 0, so we find x and y from the equation above.
So final Steps would be Quo + x(No. of right steps) + y( no. of left steps).

For Above Example :
Quo = 3/2 = 1;
Remain = 3%2 =1;

Y = (x*2 -1)/1
(x*2 -1)%1 is zero for x=1;
Now increase x from zero,

So x is 1, y is 1

Final Ans = Quo (1) + x (1) + y(1) = 3.

My code :
#include <iostream>
using namespace  std;

int main()
{
        int F,R,L;
        cin >> F;
        cin >> R;
        cin >> L;

        int remain = F%R;
        int quo = F/R;

        int Right = 0;
        int left = 0;
        int mode = 1;
        while( mode !=0)
        {
            Right++;
         mode = (R*Right - remain)%L;
         left = (R*Right - remain)/L;

        }
        int final = quo + Right + left;
        cout << final;
}

But i Don't think it is the good approach as i am putting x in loop which can be pretty costly
Can you please suggest me a good approach to do this question ?

A: In the given below equation
 x*R - Remain = 0modL
 where R, L and Remain are fixed.

It can be written as
((x*R)mod L - Remain mod L) mod L = 0

If Remain mod L = 0, then x*R should be multiple of L which makes x to 0modL.
Means x can be 0, nR where n is Integer.
So, simply, you can try x between 0 and L-1 to find x.
So, your loop can run from 0 to L-1 which will keep your loop finite.
Please note that this mod is different from %. -1 mod L = L-1 whereas -1%L = -1
There is another approach.
x*R mod L - Remain mod L = 0 mod L

leads to
x*R mod L = Remain mod L
(x* (R mod L)) mod L = (Remain mod L)

You can compute inverse of R (say Rinv) in field of L (if it does exists) and compute x = (Remain*Rinv)modL.
If inverse does not exists, it means equation cannot be satisfied.
Note: I am not mathematical expert. So, please give your opinion if anything is wrong.
See: https://www.cs.cmu.edu/~adamchik/21-127/lectures/congruences_print.pdf


text:
Q: How validate <%= file_field_tag "images[]", type: :file, multiple: true %> I have a two model
Gallery

class Gallery < ActiveRecord::Base
    has_many :pictures, :dependent => :destroy

    accepts_nested_attributes_for :pictures, :allow_destroy => true

    attr_accessible :name, :description, :pictures_attributes

    validates_presence_of :pictures
end

Picture

    class Picture < ActiveRecord::Base
      belongs_to :gallery

      has_attached_file :image,
        :path => ":rails_root/public/images/:id/:filename",
        :url  => "/images/:id/:filename"
    end

And form
    <%= form_for @gallery, :html => { :class => 'form-horizontal', multipart: true } do |f| %>
    .........
     <div class="controls">
          <%= file_field_tag "images[]", type: :file, multiple: true %>
        </div>
    .........
    <% end %>

Controller
    def create
        @gallery = Gallery.new(gallery_params)

        respond_to do |format|
          if @gallery.save

            if params[:images]
              params[:images].each { |image|
                @gallery.pictures.create(image: image)
              }
            end

            format.html { redirect_to @gallery, notice: 'Gallery was successfully created.' }
            format.json { render json: @gallery, status: :created, location: @gallery }
          else
            format.html { render action: "new" }
            format.json { render json: @gallery.errors, status: :unprocessable_entity }
          end
        end
      end
private

  def gallery_params
    params.require(:gallery).permit(:description,
                                    :name,
                                    :pictures
                                   )
  end

If I want to validate has_many pictures image blank?, I got every time a error that Pictures is blank, even I selected images.
How I validate has_many association with multiple image field?
Params
 Parameters: {"utf8"=>"✓", "authenticity_token"=>"MCkZFvsYvRndlfaqwXiw5MfhSHGoesawEAPFWzn0Ulw=", "gallery"=>{"name"=>"", "description"=>""}, "images"=>[#<ActionDispatch::Http::UploadedFile:0x007fb7ad9cb7d0 @tempfile=#<Tempfile:/var/folders/r4/jqx7vz8d48z2ky3ndpyzv9vc0000gn/T/RackMultipart20150926-38180-1xrchqg>, @original_filename="yamaha-blaster-BOARD-HEROa.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"images[]\"; filename=\"yamaha-blaster-BOARD-HEROa.jpg\"\r\nContent-Type: image/jpeg\r\n">], "commit"=>"Create Gallery"}
   (0.1ms)  begin transaction
   (0.0ms)  rollback transaction

A: Your problem lies in your use of accepts_nested_attributes_for - your model reference is to pictures whilst you're referring to images in your code.
Here's how you should do it:
#app/models/picture.rb
class Picture < ActiveRecord::Base
   belongs_to :gallery
   validates :image, presence: true

   has_attached_file :image,
        :path => ":rails_root/public/images/:id/:filename",
        :url  => "/images/:id/:filename"
end

#app/models/gallery.rb
class Gallery < ActiveRecord::Base
   has_many :pictures
   accepts_nested_attributes_for :pictures, allow_destroy: true
end

You're getting confused about the image object and the Picture model. IE you need to pass the images to the Picture model through your Gallery model:
#app/controllers/galleries_controller.rb
class GalleriesController < ApplicationController
   def new
      @gallery = Gallery.new
      @gallery.pictures.build
   end

   def create
      @gallery = Gallery.new gallery_params
      @gallery.save
   end

   private

   def gallery_params
      params.require(:gallery).permit(:description, :name, pictures_attributes: [:images])
   end
end

This means you're going to have to use f.fields_for, which can be tricky.
Here's how to do it:
#app/views/galleries/new.html.erb
<%= form_for @gallery do |f| %>
   <%= f.text_field :name %>
   <%= f.fields_for :pictures do |picture| %>
      <%= picture.file_field type: :file, multiple: true %>
   <% end %>
   <%= f.submit %>
<% end %>

This should work for you. The multiple aspect of the upload, I am not sure about.


text:
Q: JavaScript is setting variables for partial to be appended before Rails actually sets them I have a form which I use to create a list. I want to give the user the ability to create new forms for new items to be saved for future list making. I want to have a "+" button to add create a new form via JavaScript. It was working great on my test user, but things were getting cluttered so I made a new user to start fresh. When I tried to load my new list page I get his with this:
undefined method `id' for nil:NilClass

Specifically, it's pointing to this bit in my JavaScript:
$(this).parents(':eq(1)').append("<%= escape_javascript render partial: 'shared/user_item_form', locals: {f: @f, category_id: @category.id} %>");

I need to pass these variables to any new form that's going to be rendered, but these variables rely on data that is passed from the server or database or something. It seems like it's trying to run my JavaScript first, despite me declaring $(document).ready.
Here is the form in it's entirety.
Line 26 is where this problem starts, where I declared some class variables in order for them to reach my javascript down below.
Line 43 is where I render the first partial, the same one that will be duplicated when the user presses "+". When the user presses that button I want the same exact form to pop up underneath it.
https://pastebin.com/ieLYfYm4
I'm a real noob when it comes to combining JS and Rails, and I've been struggling a lot with this part of my project. I don't really understand what gets loaded first or where my JS is supposed to go. What I have hacked together seems to work fine though until now. Not sure why it was even working at any point if this now a problem. Maybe my browser stored something in the cache that was preventing this error from being raised?
Code if you can't look at the pastbin

New List

    <%= form_for @list, url: list_path, html: {class: "form-signin"} do |f| %>
        <%= f.text_field :name, placeholder: "Name your list (optional)" %>

            <% current_user.categories.each do |category| %>

                  <%= category.name %>

                <div class="dropdown-button" data-toggle="collapse" data-target="#<%= category.name %>">

                <div id="<%= category.name %>" class="collapse">

                                Add
                                Name
                                Price
                                Qnty

                        <% category.user_items.each do |item| %>
                            <%= f.fields_for l = @list.list_items.build, index: l.id do |list_item| %>
                                <% @category = category %>
                                <% @f = f %>

                                    <%= list_item.check_box :user_item_id, { checked: false }, item.id, nil %>
                                    <%= item.name %>
                                    <%= item.price %>
                                    <%= list_item.number_field :quantity,
                                                                                min: 1,
                                                                                class: "num"%>

                            <% end %>
                        <% end %>

Create a new item here:

                    <%= render partial: 'shared/user_item_form', locals: {f: f, category_id: category.id}  %>

Add More

            <% end %>

            <%= f.submit "Submit" %>

    <% end %>

A: The problem is that the javascript function addNewItemForm() at the bottom of your script is evaluated not when you invoke it, but when the page is fully rendered at first, and at that moment and at that place, when Rails tries to evaluate the following string:<%= escape_javascript render partial: 'shared/user_item_form', locals: {f: @f, category_id: @category.id} %> the @category variable is out of scope and undefined.
Actually, you need to make another server request on click of a button with corresponding params and let the server to do the work: render new partial and invoke javascript to alter HTML.
You can do that easily with the following example:

<%= link_to 'Add New Item', [:new, category, :items], remote: true %>

("remote: true" will make an ajax request).
You will get category in URL params in your controller and can instantiate it again:

@category = Category.find(params[:category_id])

and then respond with the following code (new.js.erb):

<%= j render 'shared/user_item_form', category_id: @category.id %>

(which is simply a shorthand of your line)
Here is the reference to documentation with similar example: http://guides.rubyonrails.org/working_with_javascript_in_rails.html#a-simple-example


text:
Q: Is it possible to reduce the optimization from high dimension to one dimension? I am now doing an optimization problem. Currently, I have codes in optimization min f(x_1,x_2,...,x_n). It may give x_1,x_2,...,x_n to be different in values after optimization. However, suppose I want to make that x_1=x_2=...=x_n and do the optimization again, what I expect is to find y such that f(y,y,...,y) is minimized. Setting x_1,x_2,...,x_n to be all the same as the initial input, but still, it may produce different values of x_1,x_2,...,x_n. Are there any good ways to solve the problem without rewriting the codes? Any existing functions/techniques can help me to do it? If possible, you can treat the function is not known (the codes of functions is not accessible, what I know is that for the function, when input n parameters, it gives a value).

A: As pointed out by Erwin Kalvelagen, the most general approach is to define it as equality constraints, but if it is your goal to simplify your problem, you can define a new function which accepts a single input value and forwards it to every input of your function f. Assuming you are using fmincon, the solution is:
x = fmincon(@(x) f(x, x, x, ..., x), x0, ...)


text:
Q: How to FETCH ALL RECORS and UPDATE RECORD in one to many mapping in SPRING DATA JPA? I have created two simple modal entities Book and Author and an author has many books. The mapping is working and when I save author along with book abjects from postman it gets saved according in both tables but when I hit query for fetching all authors or all books it does not respond.
Is it something related to DTOs? How can I fetch the data, I don't want to use Join Query etc.
Please guide.

A: @OneToMany has parameter FetchType(Enumeration) fetch. It be FetchType.LAZY by default, you should change it to FetchType.EAGER. If parameter fetch is FetchType.LAZY Hibernate doesn't get Book entities until you call it. If fetch is FetchType.EAGER than Hibernate gets Book entities if you didn't call it.


text:
Q: Dynamic Referencing in VBA Formula I am trying to Index/Match data only when a certain criteria is met.
I could do this with two arrays but I'm hoping there's an easy answer here.
My code is as follows:
Sub Nozeroleftbehind(lengthRow As Integer)
For i = 2 To lengthRow
    If Cells(1, i) = 0 Then Cells(1, i) = "TBD"
Next i

For i = 2 To lengthRow
    If Cells(1, i) = "#N/A" Then
        Cells(2, i) = "=INDEX(Forecast!L:L,MATCH('AA - Inbound Orders Weekly Rep'!H113,Forecast!A:A,0))"
End if
Next i

    End Sub

And then pass that sub back to the main routine.
What I am trying to get dynamic is that 'H113' cell. I can't seem to get an offset to work properly since it's already in a formula.
EDIT: Apologies, H113 moves down. Next cell would be H114.
Regards

A: Please try this code.
Sub NoZeroLeftBehind(lengthRow As Integer)
    ' 18 Oct 2017

    Dim lengthRow As Long
    Dim Tmp As Variant
    Dim C As Long

    lengthRow = 4
    For C = 2 To lengthRow
        ' bear in mind that the Cell is a Range
        ' and you want to refer to its Value & Formula property
        With Cells(1, C)
            Tmp = .Value
            ' using the Val() function will interpret a blank cell as zero value
            If Val(Tmp) = 0 Then
                .Value = "TBD"
            ElseIf IsError(Tmp) Then
                .Formula = "=INDEX(Forecast!L:L,MATCH('AA - Inbound Orders Weekly Rep'!H" & _
                           (113 + C - 2) & ",Forecast!A:A,0))"
            End If
        End With
    Next C
End Sub

A: Knowing that you want to go H113, H114:
Cells(2, i) = "=INDEX(Forecast!L:L,MATCH('AA - Inbound Orders Weekly Rep'!H" & CStr(111 + i) & ",Forecast!A:A,0))"


text:
Q: Where to put the SQL logic I have an existing SQL Server database whose structure I can't really change, although I can add stored procedures or new tables if I want. I have to write a stand-alone program to access the DB, process the data and produce some reports. I've chosen C# and Visual Studio as we're pretty much an MS shop.
I've made a start at exploring using VS 2008 to create said program. I'm trying to decide where to put some of the SQL logic. My primary aims are to keep the development as simple as possible and to perform quickly.
Should I put the SQL logic into a stored procedure and simply call the stored procedure and have SQL Server do the grunt work and hand me the results? Or am I better off keeping the SQL query in my code, creating the corresponding command and executing it against the SQL Server?
I have a feeling the former might perform better, but I've then got to manage the stored procedure separately to the rest of my code base, don't I?
UPDATE: It's been pointed out the performance should be the same if it's the same SQL code in a C# program or a stored procedure. If this is the case, which is the easiest to maintain?
2009-10-02: I had to really think about which answer to select. At the time of writing, there were 8 answers, basically split 5-3 in favour of putting the SQL logic in the application. On the other hand, there were 11 up-votes, split 9-2 in favour of putting the SQL logic in stored procedures (along with a couple of warnings about going this way). So I'm torn. In the end I'm going with the up-votes. However, if I run into trouble I'm going to come back and change my selected answer :)

A: If it is heavy data manipulation, keep it on the db in stored procedures. If the queries might change some, the better place would be in the db too, otherwise a redeploy might be required for each change.

A: Keeping the mainstay of the work in stored procedures has the advantage of flexibility - I find it easier to modify a procedure than implement a program change. Unfortunately flexibility is a double-edged sword; it's much easier to make an ill-advised change as well.

A: I suggest taking a look at LINQ to Entities, which provides an Object Relational Mapping wrapper around any SQL statements (CRUD), abstracting away the logic needed to write to the database, and allowing you to write OO code instead of using SQLConnections and SQLCommands.
OO code (the save method does not exist but you get the gist of it):
// this adds a new car to the Car table in SQL, without using ANY SQL code
Car car = new Car();
Car.BrandName = "Audi";

Car.Save(); //save is called something else and is on the
// datacontext the car is in, but for brevity sake..

SQL code as string in SqlCommand:
// open sql connection in your app and
// create Command that inserts car
SqlConnection conn = new SqlConnection(connstring);
SQlCommand comm = new SqlCommand("INSERT INTO CAR...");

// execute

A: Versioning and maintaining stored procedures is a nightmare. If you don't hit serious performance issues (that you think will be resolved using stored procedures), I think it will be better to implement logic in your c# code (linq, subsonic or anything like that).

A: With regard to your point concerning performance variation between embedding your code in .NET source or within SQL Server stored procedures, you should actually see no difference between the two methods!
This is because the same execution plan will be generated by SQL server, provided the data access T-SQL within the two different sources is the same.
You can see this in action by running a SQL Server Profiler trace and comparing the execution plans that are generated by the two different T-SQL query sources.
In light of this and back to the main point of your question then, your choice of implementation should be determined by ease of development and your future extensibility requirements. As you appear to be the sole individual who shall be working on the project then go with what you prefer, which I suspect being to keep the code centralised i.e. within a visual studio Data Access Layer (DAL).
Stored Procedures can come into their own however when you have separate development functions within your organisation/team. For example, you may have database developers on your team who can create your data access code for you and do so independently of the application, freeing you to work on other code modules.

A: Update deployment: If you need to update the procedure, you can update a stored procedure without your users eve knowing, without taking the server offline.  updating the C# means pushing out a new EXE to all your users!

A: Have a look at Entity Spaces. It's a code generation tool - but it'll do more.
There's a small amount of leg work to do in learning the tool, but once you're up and running you'll never look back. Saves hours of work. (I don't work for them BTW!)

A:
Should I put the SQL logic into a stored procedure

Well that depends on what the "SQL logic" is, doesn't it? If it's purely database-related, a stored procedure might be most appropriate. If it's 'business logic', the rules that decide how your application operates, it definitely belongs in your application.

which is the easiest to maintain?

Personally I find application-side code easier as modern languages like C# have much more expressive power than SQL. Doing any significant processing in T-SQL quickly becomes tedious and difficult to read.


text:
Q: Search tags in string I have a string, and I want to search words (tags) that begin with "#" and end with "." or "," or " " I found this online, but is limited because:
- You can find a single word in the string (although there are more words)
- "RangeOfString" does not allow multiple choices
NSString *stringText = @"test #hello #world";
NSString *result = nil;

// Determine  "#"
NSRange hashRange = [stringText rangeOfString:@"#" options:NSCaseInsensitiveSearch];
if (hashRange.location != NSNotFound)
{
    // Determine " " location according to "#" location
    NSRange endHashRange;

    endHashRange.location = hashRange.length + hashRange.location;
    endHashRange.length   = [stringText length] - endHashRange.location;
    endHashRange = [stringText rangeOfString:@" " options:NSCaseInsensitiveSearch range:endHashRange];

    if (endHashRange.location != NSNotFound)
    {
        // Tags found: retrieve string between them
        hashRange.location += hashRange.length;
        hashRange.length = endHashRange.location - hashRange.location;

        result = [stringText substringWithRange:hashRange];
    }
}

you have idea how can I do?
Thank you!

A: You can use NSRegularExpression class, like this:
NSError *error = NULL;
NSRegularExpression *tags = [NSRegularExpression
    regularExpressionWithPattern:@"[#]([^, .]+)([, .]|$)"
    options:NSRegularExpressionCaseInsensitive
    error:&error];
NSArray *matches = [tags matchesInString:str options:0 range:NSMakeRange(0, str.length)];

for (NSTextCheckingResult *match in matches) {
    NSLog(@"%@", [str substringWithRange:[match rangeAtIndex:1]]);
}

You may need to play with your regular expression to get it just right. The reference that I liked describes the grammar of the regex language supported by Apple's classes.

A: You should use NSRegularExpression, which will give you multiple matches.
The following is an untested example:
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\b(#\\S*[.,])\\b" options:NSRegularExpressionCaseInsensitive];
int numberOfMatches = [regex numberOfMatchesInString:string options:0 range:NSMakeRange(0, string.length)];
NSArray *matches = [regex matchesInString:string options:0 range:NSMakeRange(0, [string length])];

A: You will most likely want to use NSScanner.
NSString *stringText = @"test #hello #world";
NSString *result = nil;
NSCharacterSet *endingChars = [NSCharacterSet characterSetWithCharactersInString:@"., "];

NSScanner *scanner = [NSScanner scannerWithString:stringText];
scanner.charactersToBeSkipped = nil;

[scanner scanUpToString:@"#" intoString:NULL];
[scanner scanString:@"#" intoString:NULL];
[scanner scanUpToCharactersFromSet:endingChars intoString:&result];
[scanner scanCharactersFromSet:endingChars intoString:NULL];

STAssertEqualObjects(result, @"hello", nil);

At that point you just loop until [scanner isAtEnd];

NSString *stringText = @"test #hello #world";
NSString *match = nil;
NSMutableArray *results = [NSMutableArray arrayWithCapacity:2];
NSCharacterSet *endingChars = [NSCharacterSet characterSetWithCharactersInString:@"., "];

NSScanner *scanner = [NSScanner scannerWithString:stringText];
scanner.charactersToBeSkipped = nil;

while (![scanner isAtEnd]) {
    [scanner scanUpToString:@"#" intoString:NULL];
    [scanner scanString:@"#" intoString:NULL];
    [scanner scanUpToCharactersFromSet:endingChars intoString:&match];
    [scanner scanCharactersFromSet:endingChars intoString:NULL];
    [results addObject:match];
}

STAssertEquals(results.count, 2, nil);
STAssertEqualObjects([results objectAtIndex:0], @"hello", nil);
STAssertEqualObjects([results objectAtIndex:1], @"world", nil);


text:
Q: Simulink Device Driver Block not executing on arduino mega 2560 I'm working on a project which involves creating a device driver block using simulink and an s-function builder block. My driver is supposed to make my arduino mega 2560 to periodically send a message to a remote sensor and recieve back the temperature measurement of this sensor.
For the communication between my main arduino and the remote sensors I am using the RF22B 433Mhz transceiver with the Radiohead library (http://www.airspayce.com/mikem/arduino/RadioHead/index.html).
I tried my script on the arduino IDE and it works perfectly, but it won't execute on simulink.
I have installed the simulink support package for arduino and I made some simple driver blocks which involved blinking LEDs and simple stuff and it did work. However, for the script which uses the Radiohead libaray, even though I debugged all of the errors and simulink says that the model is "succesfully deployed to arduino mega 2560", it does not execute.
Does anyone have any hints on why this may be happening?
Has anyone experienced similar issues?
I did some research on this website and many others but I wasn't able to find any similar problems.
Thanks in advance


text:
Q: PHP MySQLi Lock Tables Query Sometimes Does Not Complete I am attempting to lock some tables while running some code and unlocking the tables when I am done.
Process:

*

*Run Lock Tables MySQL Query.

*Run some PHP Code.

*Run Unlock Tables MySQL Query.

While running this process, 9 times out of 10 everything runs perfectly. Sometimes, when I run my query no response comes back from MySQL and PHP just waits for a response. Since no response happens, I never get to steps 2 or 3 and the table stays locked indefinitely. I am running the exact same Lock Tables Query in every single attempt.
After some research, I found that the problem happens when a Second Server writes to the database and then the First Server tries to do a "LOCK TABLES" query. It appears that the Second Server's write does a "metadata lock". I believe this is due to MySQL having the "autocommit" feature enabled and the transaction is not yet completed. So when I attempt to lock the tables, MySQL never responds and the "show processlist;" has "Waiting for table metadata lock | LOCK TABLES ..." listed in it until I manually kill the process.
I am locking Numerous tables. Below is a similar example to my actual table query. I am using the same table multiple times with different aliases based on the queries I am attempting to prevent from accessing the tables.
$sql = "LOCK TABLES table1 as t1 WRITE
                    , table2 as t2 WRITE
                    , table3 WRITE
                    , table2 WRITE
                    , table4 WRITE
                    , table1 WRITE
                    , table5 WRITE
                    , table5 as t5 WRITE
                    , table6 as t6 WRITE
                    , table7 as t7 WRITE
                    , table7 WRITE
                    , table8 as t8 WRITE
                    , table9 t9 WRITE
                    , table10 t10 WRITE
                    , table11 t11 WRITE
                    , table12 WRITE;";

$this->mysqli = new mysqli(
    $this->credentials->server
    , $this->credentials->user
    , $this->credentials->password
    , $this->credentials->database
);

try{
    error_log('before first attempt lock tables '.$sql);
    $this->mysqli->query($sql);
    error_log('after first attempt lock tables');
} catch (Exception $e){
    error_log('Error locking tables: '.$e->getMessage());
}

error_log('After try catch.');
if($this->mysqli->error){
    error_log('lock table error: '.$this->mysqli->error);
}

When the process fails, I see "before first attempt lock tables" in my PHP  Error log. I do not see any of the other error_log() calls. After some checking, I determined it is because PHP has not received a response from MySQL.
I never get into the Catch Exception, since MySQL is not returning an error. MySQL is not returning anything unless I manually kill the MySQL Lock Tables Process.
If I don't kill the process, the PHP code never stops waiting for a response from mysql.
I am confused why the "LOCK TABLES" query is not gracefully waiting for the "metadata lock" to complete and then running. It was my understanding that more than one server was allowed to write to a database and the lock table features would work together instead of one hanging indefinitely.

A: Gag!  LOCK TABLES is essentially unnecessary if you are using ENGINE=InnoDB.  If you are still using MyISAM, convert!
After converting, you will need to understand how to put things in "transactions" (BEGIN...COMMIT) and use SELECT ... FOR UPDATE.


text:
Q: How to properly share an object between different app pages in Flutter I am new to Flutter. I have implemented an arbitrary class which has some states and need to be shared between different pages in Flutter. What I am currently doing is I defined a sqflite database helper and each page loads that object form database and before going to other pages, it saves it again to the database and navigates to other page. However, it adds many complexities and bugs.
Another possible solution could be add it to myApp() class which is called in main() function. However, since other pages do not inherit myApp(), they have no access to global_object.
class MyApp extends StatelessWidget{

// I need gloabl_object accessible in different pages
//---------------------------------------------------
MyObject global_object;
//---------------------------------------------------

  @override
  Widget build(BuildContext context){
    return MaterialApp(
      title: 'App title',
      debugShowCheckedModeBanner: false,
      theme: new ThemeData(
        // App theme
      ),
      //home: Homepage(),
      routes: { // Defining routs
        // DIFFERENT PAGES THAT NEEDS TO HAVE ACCESS TO global_object
      },
    );
}

A: Method 1: Use package get_it https://pub.dev/packages/get_it
Simple direct Service Locator that allows to decouple the interface from a concrete implementation and to access the concrete implementation from everywhere in your App.
example https://github.com/fluttercommunity/get_it/tree/master/example/lib
GetIt sl = GetIt.instance;

void main() {

  sl.registerSingleton<AppModel>(AppModelImplementation());

  runApp(MyApp());
}

After register , you can access everywhere with
var myAppModel = sl.get<AppModel>();

Method 2: Use package provider https://pub.dev/packages/provider
full example https://github.com/flutter/samples/tree/master/provider_shopper
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // Using MultiProvider is convenient when providing multiple objects.
    return MultiProvider(
      providers: [
        // In this sample app, CatalogModel never changes, so a simple Provider
        // is sufficient.
        Provider(create: (context) => CatalogModel()),
        // CartModel is implemented as a ChangeNotifier, which calls for the use
        // of ChangeNotifierProvider. Moreover, CartModel depends
        // on CatalogModel, so a ProxyProvider is needed.
        ChangeNotifierProxyProvider<CatalogModel, CartModel>(
          create: (context) => CartModel.empty(),
          update: (context, catalog, previousCart) =>
              CartModel(catalog, previousCart),
        ),
      ],
      child: MaterialApp(
        title: 'Provider Demo',
        theme: appTheme,
        initialRoute: '/',
        routes: {
          '/': (context) => MyCatalog(),
          '/cart': (context) => MyCart(),
        },
      ),
    );
  }
}

access with Provider.of<CartModel>(context);
class _CartList extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var itemNameStyle = Theme.of(context).textTheme.title;
    var cart = Provider.of<CartModel>(context);

    return ListView.builder(
      itemCount: cart.items.length,

or with Consumer<CartModel>
class _CartTotal extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var hugeStyle = Theme.of(context).textTheme.display4.copyWith(fontSize: 48);

    return SizedBox(
      height: 200,
      child: Center(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Consumer<CartModel>(
                builder: (context, cart, child) =>
                    Text('\$${cart.totalPrice}', style: hugeStyle)),


text:
Q: How to display a popup for every checked checkbox I want a pop up box to be displayed for every checkbox checked of a class. The pop up box will also have a checkbox on it. So for every checkbox checked on the pop up box the value of the checkbox should be pushed to an array.
What am I doing wrong?
$('input[name="cases"]:checked').each(function() {
  cases.push($(this).attr('itemLabel'));
  console.log("cases",cases);
  $("
Rule: "+$(this).attr('itemValue')+"
<input type='checkbox' id='applyToall' name='applyToall'/>Apply to all?

").dialog();
  if($('input[name="applyToall"]:checked')) {
    ApplyToAll.push($(this).attr('itemLabel'));
    console.log("ApplyToAll",ApplyToAll)
  }
});

JSFIDDLE: https://jsfiddle.net/drxjhgeq/


text:
Q: Java streams to map I'm having a problem with the Map<Integer, List<String>> personenPerLeeftijd, the compiler says the method, Persoon::getLeeftijd, cannot be resolved. I don't really know what else I can do, sorry for the Dutch words!
I you need any more info pls ask so
public class TestPersoon2 {
public static void main(String[] args) {

    final List<Persoon> personen = Personen.getPersonen();

    Map<String, Persoon> map =
            personen.stream().collect(Collectors.toMap(p -> p.getNaam() + "-" + p.getLeeftijd(), p -> p));
    for (String s : map.keySet()) {
        System.out.printf("%-15s -> %s\n", s, map.get(s));
    }
    Map<Integer, List<String>> personenPerLeeftijd =
            personen.stream().collect(Collectors.groupingBy(Persoon::getLeeftijd)); //THIS METHOD

    personenPerLeeftijd.forEach((k, v) -> System.out.printf("%2d: %s\n", k,
            v.stream()

            System.out.println();

    TreeMap<Integer, Long> perLeeftijd =
            personen.stream().collect(Collectors.groupingBy(Persoon::getLeeftijd, Collectors.counting()));

    perLeeftijd.forEach((k, v) -> System.out.printf("%2d -> %d\n", k, v));
}

Persoon class
public class Persoon {
private final String naam;
private final Geslacht geslacht;
private final int leeftijd;

public Persoon(String naam, Geslacht geslacht, int leeftijd) {
    this.naam = naam;
    this.geslacht = geslacht;
    this.leeftijd = leeftijd;
}

public String getNaam() {
    return naam;
}

public Geslacht getGeslacht() {
    return geslacht;
}

public int getLeeftijd() {
    return leeftijd;
}

public int leeftijdsverschil(final Persoon andere) {
    return leeftijd - andere.leeftijd;
}

@Override
public String toString() {
    return String.format("%-9s - %s - %2d", naam, geslacht, leeftijd);
}

A: As mentioned by @luk2302, the easiest solution is to use Map<Integer, List<Person>>.
    Map<Integer, List<Person>> peopleByAge = personen
            .stream()
            .collect(Collectors.groupingBy(Person::getAge)); //THIS METHOD

If you really need Map<Integer, List<String>> then there's a little more to do.
    Map<Integer, List<String>> peoplesNamesByAge = personen
            .stream()
            .collect(
                    Collectors.groupingBy(Person::getAge,
                            Collectors.mapping(Person::getName,
                                    Collectors.toList())));
    peoplesNamesByAge.forEach((k, v) -> System.out.printf("%2d: %s\n", k, v));

Here's the whole thing - I've anglicised it a little for my own sanity. :)
enum Gender {

    Male, Female;
}

public class Person {

    private final String name;
    private final Gender gender;
    private final int age;

    public Person(String naam, Gender gender, int age) {
        this.name = naam;
        this.gender = gender;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public Gender getGender() {
        return gender;
    }

    public int getAge() {
        return age;
    }

    public int getAgeDifference(final Person other) {
        return age - other.age;
    }

    @Override
    public String toString() {
        return String.format("%-9s - %s - %2d", name, gender, age);
    }
}

public void test() {
    final List<Person> personen = Personen.getPersonen();

    Map<String, Person> map
            = personen.stream().collect(Collectors.toMap(p -> p.getName() + "-" + p.getAge(), p -> p));
    for (String s : map.keySet()) {
        System.out.printf("%-15s -> %s\n", s, map.get(s));
    }
    Map<Integer, List<Person>> peopleByAge = personen
            .stream()
            .collect(Collectors.groupingBy(Person::getAge)); //THIS METHOD

    peopleByAge.forEach((k, v) -> System.out.printf("%2d: %s\n", k, v));

    Map<Integer, List<String>> peoplesNamesByAge = personen
            .stream()
            .collect(
                    Collectors.groupingBy(Person::getAge,
                            Collectors.mapping(Person::getName,
                                    Collectors.toList())));
    peoplesNamesByAge.forEach((k, v) -> System.out.printf("%2d: %s\n", k, v));

    System.out.println();

    // TreeMap<Integer, Long> perLeeftijd
    Map<Integer, Long> perLeeftijd = personen
            .stream()
            .collect(Collectors.groupingBy(Person::getAge, Collectors.counting()));

    perLeeftijd.forEach((k, v) -> System.out.printf("%2d -> %d\n", k, v));
}


text:
Q: UART reply includes previous command? I am trying to read from a UART device in a Linux environment using a C program, but I experience different results respect to communicating to the UART using screen.
The C code I use to test the UART communication is the following:
#include <stdio.h>
#include <stdlib.h>
#include <libgen.h>
#include <unistd.h>
#include <string.h>
#include <strings.h>
#include <getopt.h>
#include <stdbool.h>
#include <sys/stat.h>
#include <termios.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/file.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/select.h>
#include <signal.h>
#include <ctype.h>

bool loop;

void sigHandler(int32_t sig)
{
    if(sig == SIGINT)
    {
        printf("Catched SIGINT");
        loop = false;
    }
}

int main(int argc, char *argv[])
{
    char *devname = argv[1];
    int fd = -1;

    int nread = -1;
    int nwrite = -1;

    int ret;

    struct termios t_new = {0};
    struct termios t_old = {0};

    signal(SIGINT, sigHandler);

    fd = open(devname, O_RDWR | O_NOCTTY |O_NONBLOCK);
    if(fd > 0)
    {
        printf("TTY open ! Configuring TTY");
    }
    else
    {
        fd = -1;
        return 1;
    }

    ret = tcgetattr(fd, &t_old);
    if(ret < 0)
    {
        perror("tcgetattr ");
        close(fd);
        fd = -1;
        return 1;
    }

    t_new = t_old;
    t_new.c_cflag = (B9600 | CS8 | CREAD );
    t_new.c_oflag = 0;
    t_new.c_iflag = 0;
    t_new.c_lflag = 0;

    ret = tcsetattr(fd, TCSANOW, &t_new);

    loop = true;
    while(loop)
    {
        char s[] = "at+gmi=?\r\n";
        nwrite = write(fd, s, strlen(s));
        if(nwrite == strlen(s))
        {
            fd_set rfd;
            struct timeval tm = {.tv_sec = 0, .tv_usec = 500000};
            FD_ZERO(&rfd);
            FD_SET(fd, &rfd);

            char buffer[64] = {0};

            if(select(fd + 1, &rfd, NULL, NULL, &tm) > 0)
                nread = read(fd, buffer, sizeof(buffer));

            if(nread > 0)
                printf("Reply is: %s\n", buffer);
        }

        usleep(500000);
    }
}

But when I read the reply, it always includes the string I have sent.
I don't experience this problem using screen.
What is the best way to read from an UART in C using Linux ?
Could the multiplexed way (using select) causing the problems ?
EDIT
For completeness, the output is:
Reply is: at+gmi=?

OK

Also, sometimes I don't read anything.

A:
But when I read the reply, it always includes the string I have sent.

Since your termios configuration obliterated the local echo attributes and you're sending an AT modem command, you should try sending an ATE0 command to disable echoing by the modem.

I don't experience this problem using screen.

This observation confirms that the connected modem has its echoing enabled.
The AT command is echoed (by the modem) as you type, but you don't object to this received data in this situation (because you want to see what you type).
If the modem did not have echoing enabled, then you would be complaining that what you type in screen was not visible.
IOW echo is desired when using a terminal emulator program (such as screen), but echoing needs to be disabled when sending data by a program.

What is the best way to read from an UART in C using Linux ?

(Technically you are not reading from a "UART", but rather from a serial terminal that fully buffers all input and output.)
Code that conforms to POSIX standard as described in Setting Terminal Modes Properly
and Serial Programming Guide for POSIX Operating Systems would be far better that what you have now.
I'm surprised that it works at all (e.g. CREAD is not enabled).

Could the multiplexed way (using select) causing the problems ?

Not the echo "problem".
Your program does not do anything that requires using select() and nonblocking mode.

Also, sometimes I don't read anything.

When you write code that is not POSIX compliant, you should not expect reliable program behavior.


text:
Q: Accurate YUV 10 bits to 8 bits conversion I have YUV422 10-bits SDI from camera, and I need to accurately convert it to 8-bits.
Can I just shift right by 2 bits, or it is not good?
There is a lot of info: http://en.wikipedia.org/wiki/YUV and https://ru.wikipedia.org/wiki/YCbCr
But there is no full clearness.

A: For 8 bit: Y range is [16..235] and U/V range is [16..240]
For 10 bit: Y range is [64..940] and U/V range is [64..960]
So shifting each component value 2 bits to right will provide correct conversion of black and white points: 64==>16, 940==>235 and 960==>240. Intermediate values also will correctly converted.


text:
Q: Res.render() not rendering I have this express route that seems to be refusing to render a jade template. When I put the wrong jade template string in, I get the usual couldn't find the fie being rendered to the browser.
But when I have the right one in, nothing happens...
Also, when I put a res.status(500).send() AFTER the res.render(), I end up getting the 500 error or any other code I choose to put in there.
What's going on here?

 app.post('/stuff/new', function (req,res){

    Stuff.findById(req.body.booking_id, function(err, stuff){
      if(err){ console.log("Err", err)}

      else if (booking) {

        Thungs.findById(req.body.user_id, function(err, thung){
          user.stuff.push(req.body.things);
          user.save();
        });

        Thingers.findById(req.body.center_id, function(err, thinger){
          center.stuff.push(req.body.things);
          center.save();
        });

        stuff.prop = 'thing';
        stuff.save(function(err, result){
          if (err) { console.err("err", err) }
          else {

            res.render('booking/thank_you', {
              url: req.url,
              id: "thank_you"
            }, function(err, html){
              if (err) { console.err("ERR", err) }
              else {
                res.send(html);
              }
            });
            res.status(500).send();

          }
        });
      }
    })
  });

A: You dont need res.send(html); if you jsut want to  render template, just remove the call back from res.render() it should work fine. and also when res.status(500).send(); is showing 500 becuase the connection does not terminate after res.render() and res.send() the statements following them will execute, you can user return res.render() and return res.send() then control will not go to res.status(500).send()
hope it helps :)

A: The entire stuff.save() callback is incorrect because you're never returning the result of res.render(). Your res.render() gets executed however, since you're passing a callback to res.render() it will not automatically respond to the request.

res.render(view [, locals] [, callback])
Renders a view and sends the rendered HTML string to the client. Optional parameters:

*

*locals, an object whose properties define local variables for the view.

*callback, a callback function. If provided, the method returns both the possible error and rendered string, but does not perform an automated response. When an error occurs, the method invokes next(err) internally.

Since the res.render() function isn't blocking, your stuff.save() callback continues execution to res.status(500).send() and responds. Ultimately your view doesn't get rendered and your left getting a 500 Internal Server Error as a response.
Its important to note that it is a "best practice" in almost all scenarios to return when doing a response where you want to stop execution after responding. The only time you wouldn't want to use a return when responding is if you need to do some type of cleanup routine afterwards.
The below code correctly returns res.render() when successful and res.status(500) in the event of an error.
stuff.save(function(err, result){
  if (err) {
    console.err("err", err)

    // An error occurred, stop execution and return 500
    return res.status(500).send();
  }

  // No error occurred, attempt to render the view
  // and return the outcome of the rendering to the callback
  res.render('booking/thank_you', {
      url: req.url,
      id: "thank_you"
    }, function(err, html){
      if (err) {
        console.err("ERR", err)

        // An error occurred, stop execution and return 500
        return res.status(500).send();
      }

      // Return the HTML of the View
      return res.send(html);
    });
  }
});


text:
Q: How do I get my output from a program on to a csv file using bash? How do I get my output from a program on to a csv file using bash? It kept overwriting when I send the output of the program.
outfile="gremlin_pop"$low_pop"-"$hi_pop".csv"
echo "Initial Population,Good Gremlins,Bad Gremlins" > $outfile

for p in `seq $low_pop $step_pop $hi_pop`;
do
    echo "Experiment: " $p
    python3 gremlinSim.py $p
done

My csv file should look like this,
Initial Population,Good Gremlins,Bad Gremlins
10,10,0
20,20,0
30,30,4
40,50,4
50,61,4

The output from the program,
Experiment:  10
10 10 0
Experiment:  20
20 20 0
Experiment:  30
30 30 4
Experiment:  40
40 50 4
Experiment:  50
50 61 4

A:
It kept overwriting when I send the output of the program.

This is cause you use > to create/overwrite a file, instead of >> to add text to an file.
You should also get rid of the echo statements when you add output to that $outfile. Or ...
echo "Initial Population,Good Gremlins,Bad Gremlins" >> "$outfile"
echo "Experiment: ${p}" >> "$outfile"

Not sure why you wont edit the python script to behave like you want. Anyway, to change the output of that script you could use tr.
python3 gremlinSim.py $p | tr '[:blank:]' ',' >> "$outfile"

Output:
10,10,0
20,20,0
30,30,4
40,50,4
50,61,4

The [:blank:] represent spaces and tabstop while the , will be used as replacement.


text:
Q: Tap event only works when finger doesnt slide I am using jquery mobile with phone gap on IOS and i notice that the tap event is trigger only when you tap the screen without moving your finger left or right.
Below is my bind code.
$(".pic-cont").on("tap",{count: "not needed"},function(event){
        console.log("Clicked");
        ....

I am making a game and the user will tap things on the screen quickly and what i notice is when you tap fast your finger may slide and not register the tap event. Is there any other event i can use (like a touchdown event) so when a users finger hits the screen the event is registered right away regardless if they move finger left right up down or hold.
Thanks!

A: In case of jQuery Mobile there are few solutions, but one will work in your case.
Solution 1 - jQuery solution
Instead of tap event you should use touchstart event. It works like tap and at the same time it is a first event to trigger during the screen swipe.
Here a code example:
$(document).on('pagebeforeshow', '#index', function(){
    $(document).on('touchstart', '#index', function(){
        alert('touchstart');
    });
});

And I made you a working example: http://jsfiddle.net/Gajotres/vDqdD/
Solution 2 - jQuery Mobile solution
While touchstart is a good all around solution, it wont work on older Android devices using older jQuery Mobile versions (1.1 and below).
So if you need to create a bulletproof version you should use vmousedown event instead of touchstart.
$(document).on('pagebeforeshow', '#index', function(){
    $(document).on('vmousedown', '#index', function(){
        alert('vmousedown');
    });
});

And here's a working jsFiddle example: http://jsfiddle.net/Gajotres/vDqdD/4/

A: For a game it would be better to use the native touch events: https://developer.mozilla.org/en-US/docs/DOM/Touch_events. Using them allows you to have a much tighter control than using the convenience events such as "tap".

A: You may want to try this  Quo JS  lightweight javascript library for the accurate events. I have found this over few suggestions from SO. It worked wonderfully and very accurate.


text:
Q: SFML Game Development Book by Haller 2D Diagonal Movement The SFML Game Development book in Ch. 4 gives guidance that when you increase velocity by both directions (e.g. right and top), then the movement will be faster than in one direction.
From research, I understand that the observed behavior is that you will reach the diagonal distance in the same period as if you were moving left or right or top or down. This is wrong as the diagonal distance is longer.
The book corrects this problem by dividing by sqrt of 2:
sf::Vector2f velocity = mPlayerAircraft->getVelocity();

// If moving diagonally, reduce velocity (to have always same velocity)
if (velocity.x != 0.f && velocity.y != 0.f)
    mPlayerAircraft->setVelocity(velocity / std::sqrt(2.f));

From additional research, I found that the solution can be achieved by multiplying the velocity by the normalized vector of the velocity.
velocity = mPlayerAircraft->getVelocity();

if (velocity.x != 0.f && velocity.y != 0.f) {
    float velocityxsq = velocity.x * velocity.x;
    float velocityysq = velocity.y * velocity.y;
    float magnitude =  std::sqrt(velocityxsq + velocityysq);
    sf::Vector2f normalizedVector = velocity / magnitude;
    velocity.x = velocity.x * std::abs(normalizedVector.x);
    velocity.y = velocity.y * std::abs(normalizedVector.y);
    mPlayerAircraft->setVelocity(velocity);
}

The behavior seems to be correct by both implementations but the normalization values are not always 1/sqrt(2). The only time the calculations are the same are when the game starts and I do a diagonal movement initially. If I move any direction and then make a diagonal movement, the values differ.
Did I do the normalization incorrect?
Why does the book statically use sqrt(2)?

A: While I actually own the book, I haven't had time to read it, so the following is just a logical assumption.
The book simply assumes the velocity vector's directional components are always either -1, 0, or 1. That's about it.
You're indeed correct that the proper solution would be to normalize the vector by dividing both components using the vector's length (or magnitude).
In case of the book this is skipped, so for simplification it's possible to remove the whole calculation by basically using a compile time constant, sqrt(2.f).


text:
Q: huge table + footnote-ish thing I have a book, which is basically a 100-page table. I use xtab package to layout this book.
The book has a list of 100-ish definitions, which are referenced multiple times in the table. Think of a bank commission table, where there are many footnotes referenced multiple times, eg. 1) for this thing You need to have a gold credit card, 2) for this thing You need to have $1M in Your account, etc.
The numbering of the definitions is fixed (Say, this is a legal document). The definitions can have arbitrary numbering (like "1", "W" , "III").
What I want to be able to do, is for each of the definitions that are referenced on the page have them appear as footnotes (or something that resembles footnotes visually). Is this doable? Or at least partially doable?

A: So this lists A and i on the first page and i and w on the second, just listing once each, in the order of definition. It takes the page numbers for which cite to use on each page from the previous run so will take a couple of runs to settle down.

\documentclass{article}
\textheight.3\textheight
\paperheight.5\paperheight
\pdfpageheight\paperheight

\usepackage{longtable}
\makeatletter
\def\foopage#1#2{\global\expandafter\let\csname foopage-#1-#2\endcsname\@empty}

\let\foolist\@empty
\def\foodef#1#2{%
\g@addto@macro\foolist{{#1}}%
\@namedef{foo-#1}{#2}}

\def\foocite#1{%
\textsuperscript{#1}%
\let\reserved@a\relax
\protected@write\@auxout{}{\string\foopage{#1}{\thepage}}%
}

\def\fooloop{%
\expandafter\@tfor\expandafter\tmp\expandafter:\expandafter=\foolist\do{%
\expandafter\ifx\csname foopage-\tmp-\thepage\endcsname\@empty
\insert\footins{%
    \reset@font\footnotesize
    \interlinepenalty\interfootnotelinepenalty
    \splittopskip\footnotesep
    \splitmaxdepth \dp\strutbox \floatingpenalty \@MM
    \hsize\columnwidth \@parboxrestore
    \textsuperscript{\tmp}\csname foo-\tmp\endcsname}%
\fi
}}

% add the insert loop
\def\foopatch#1\output#2{%
\def\LT@start{#1\fooloop\output{\LT@output}}}
\expandafter\foopatch\LT@start

\def\foopatch#1\copy\LT@head\nobreak#2{%
\def\LT@output{#1\copy\LT@head\nobreak\fooloop#2}}
\expandafter\foopatch\LT@output

\begin{document}

\foodef{A}{Something about A.}
\foodef{i}{Something equally dull about i.}
\foodef{w}{In case you missed $x$ $y$ and $z$, here's $w$.}

\begin{longtable}{ll}
aaaa&bbb\\
aaaa&bbb\\
aaaa&bbb\foocite{A}\\
aaaa&bbb\\
aaaa&bbb\\
aaaa&bbb\foocite{i}\\
aaaa&bbb\\
aaaa&bbb\\
aaaa&bbb\\
aaaa&bbb\\
aaaa&bbb\foocite{i}\\
aaaa&bbb\\
aaaa&bbb\\
aaaa&bbb\\
aaaa&bbb\foocite{w}\\
aaaa&bbb\\
aaaa&bbb\\
aaaa&bbb\\
aaaa&bbb\\
aaaa&bbb\foocite{i}\\
aaaa&bbb\\
aaaa&bbb\\
aaaa&bbb\foocite{w}\\
aaaa&bbb\\
aaaa&bbb\\
\end{longtable}

\end{document}


text:
Q: Is there a conformal diffeomorphism between R3 minus a line and R2 x S1? There exists a conformal diffeomorphism between $\mathbb{R}^3$ and $S_3$ (less a point):
$$
g = dr^2+r^2\left(d\theta^2 + \sin^2\theta\ d\phi^2\right)
$$
$$
r = R \tan \frac{\alpha}{2}
$$
$$
g = \frac{R^2}{4\cos^4\frac{\alpha}{2}}\left[d\alpha^2+\sin^2\alpha\left(d\theta^2 + \sin^2\theta\ d\phi^2\right)\right]
$$
There also exists a conformal diffeomorphism between $\mathbb{R}^3$ (less a point) and the cylinder $\mathbb{R}\times S_2$:
$$
r = R\ e^{x/R}
$$
$$
g=e^{2x/R}\left[dx^2+R^2\left(d\theta^2 + \sin^2\theta\ d\phi^2\right)\right]
$$
There does not appear to be a conformal diffeomorphism between $\mathbb{R}^3$ (less a line) and the cylinder $\mathbb{R^2}\times S_1$. At least, my attempts to find one starting from $\mathbb{R^3}$ in cylindrical coordinates:
$$
g = dz^2+ d\rho^2 +\rho^2 d\phi^2
$$
and remapping $(z, \rho)$ have failed. So my questions are:
1) Is it true that there is no such diffeomorphism?
2) If so, how do you show that? I think that local invariants like the Cotton tensor have nothing to say, because both $\mathbb{R}^3$ and $\mathbb{R^2}\times S_1$ are flat, and instead there is some kind of global obstruction.
Edited:
My original question was not sufficiently precise, it asked about existence of a conformal map, but I really meant existence of a conformal diffeomorphism. As Ben pointed out, there is the conformal map
$$
\mathbb{R}^3 \to \mathbb{R}^2 \times S_1
$$
$$
(x, y, z) \mapsto (x, y, \phi= \mathrm{mod}(z, 2\pi))
$$
but that is not injective and so not a diffeomorphism.

A: The map $\phi(x,y,\theta)=(x,y,e^{i \theta})$ is a locally isometric covering map, as it is given by taking the usual covering map $\Phi(\theta)=e^{i \theta}$, $\Phi \colon \mathbb{R} \to S^1$, $2 \pi$ periodic, and throwing in $x,y$. In particular, this map is a conformal map, but not a conformal diffeomorphism. Its lift is $\tilde\phi(x,y,\theta)=(x,y,\theta+2\pi)$, a conformal diffeomorphism. The metric is $dx^2+dy^2+dz^2$ where $z=2\pi \theta$.
Update: the question is now whether $\mathbb{R}^3$ minus a line is conformally diffeomorphic to $\mathbb{R}^2 \times S^1$. It is not: $\mathbb{R}^3$ minus a line has developing map taking it to $S^3$ minus a circle. (The map is your usual conformal map to $S^3$ as given in the question above.) On the other hand, $\mathbb{R}^2 \times S^1$ admits a conformal covering map (as given in my previous remarks) by $\mathbb{R}^3$, so its developing map has image $S^3$ minus a point. The same argument proves that $\mathbb{R}^3$ minus any closed set is not conformal to $\mathbb{R}^2 \times S^1$. See Richard Sharpe's book Differential Geometry to read about developing maps of conformal geometries.

A: As Ben noted above and in the comments, my answer doesn't make any sense.  Please ignore what follows and I apologize for wasting your time.
$\textbf{IGNORE:}$
Given a conformal map $\phi: \mathbb{R}^{3}\rightarrow \mathbb{R}^{2}\times \mathbb{S}^{1},$ we may lift to a conformal map $\widetilde{\phi}: \mathbb{R}^{3}\rightarrow \mathbb{R}^{3}.$  By Liouville's theorem (https://en.wikipedia.org/wiki/Liouville%27s_theorem_(conformal_mappings)), the map $\phi$ is a Mobius transformation, in particular it is the restriction of a diffeomorphism $\mathbb{S}^{3}\rightarrow \mathbb{S}^{3}$ which maps $\infty$ to $\infty.$  But, the map $\widetilde{\phi}$ satisfies, in particular, $\widetilde{\phi}(0,0,1)=\widetilde{\phi}(0,0,n),$ as a result of the fact that it is a lift.  Here, we have normalized the deck group of the cover $\mathbb{R}^{3}\rightarrow \mathbb{R}^{2}\times \mathbb{S}^{1}$ to be generated by the action $(x,y,z)\mapsto (x,y,z+1).$
This proves that $\widetilde{\phi}$ can not be the restriction of a diffeomorphism $\mathbb{S}^{3}\rightarrow \mathbb{S}^{3}$ (or even a bijection), and therefore, there is no conformal map $\phi:\mathbb{R}^{3}\rightarrow \mathbb{R}^{2}\times \mathbb{S}^{1}.$
$\textbf{IGNORE}$


text:
Q: How to open up external packages/libraries in VS Code While working with a peer who used pycharm, I noticed he was able to open up the packages of external libraries in our app. In other words, he could dig in to the source code of that library/package. When I try to CMD + click external libraries in VS Code, this isn't possible; I can only do it with files/modules that are within my own code base. Can I enable this somewhere in the settings?
There is a Go To Definition, however, this is "empty" when I end up clicking on an external package.

A: It will work if you have the Python extension installed (as pointed out by @congbaoguier) and at least the Microsoft language server turned on.


text:
Q: Provide multiple mirrors if a file doesn't exist I want a Mirror script which determines whether or not a certain file is accessible or not. If the mirror 1 is accessible, it will present the link to mirror 1. If mirror 1 is not accessible, it will present the link to mirror 2.
This so far is perfect, however I would like more mirrors. For example, if mirror 2 is unavailable, mirror 3 will be presented. If mirror 3 is unavailable, mirror 4 will
be presented and so on. I'm just not quite sure exactly how I could make this work. Has anyone got any suggestions?  They would be highly appreciated. I've tried quite a lot of things already!
$mirror1 = "download1.exe";
$mirror2 = "download2.exe";
$header_response = get_headers($mirror1, 1);
if ( strpos( $header_response[0], "404" ) !== false )
{
    echo '
Download Mirror 1
';
}
else
{
    echo '
Download Mirror 2
';
}

A: Here's one way to do this:
$mirrors = array("download1.exe","download2.exe","download3.exe");

foreach($mirrors as $mirror) {
    $header_response = get_headers($mirror, 1);
    if (strpos( $header_response[0], "404" ) === false) {
        echo 'Download from '.$mirror.'';
        break; //removing break will show all available mirrors
    }
}

A: You could put them all into an array. Then while() the response was === false, array_shift the next one out of the array and use it. Once it's not false, you'll echo the last one that was used.


text:
Q: Bootstrap carousel works wrong I am trying to use bootstrap caraousel. I have copied example, but it works wrong. When i click arrow slide shows on left or right side of div and then change position. I also use inspinia. What's wrong?

To jest opis

pierwszego slajdu

To jest opis

drugiego slajdu

To jest opis

trzeciego slajdu

example
On the left is first slide and second on right. The red arrow show direction.

A: It may be that you are not including the libraries correctly. This works

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

To jest opis

pierwszego slajdu

To jest opis

drugiego slajdu

To jest opis

trzeciego slajdu


text:
Q: Run Spring Boot Unit tests ignoring CommandLineRunner I'm trying to write spring boot unit tests but have some problems with CommandLineRunner which runs entire app when I run unit tests.
App.class
@SpringBootApplication
@Profile("!test")
public class App implements CommandLineRunner {

  @Autowired
  private ReportService reportService;

  public static void main(String[] args) {
    SpringApplication app = new SpringApplication(App.class);
    app.setBannerMode(Banner.Mode.OFF);
    app.run(args);
  }

  @Override
  public void run(String... args) throws Exception {

    if (args.length == 0)
      reportService.generateReports();

    if (args.length > 0 && args[0].equals("-p"))
      for (Report report : reportService.showReports())
        System.out.println(report.getId() + " : " + report.getTimestamp());
  }
}

ReportServiceTest.class
@RunWith(SpringRunner.class)
@SpringBootTest(classes = App.class)
@ActiveProfiles("test")
public class ReportServiceTest {

  @Autowired
  private ReportRepository reportRepository;

  @Autowired
  private ReportService reportService;

  @Test
  public void testShowReports() {
    List<Report> expectedReports = new ArrayList<>(3);
    for(int i = 0; i< 3; i++) {
      expectedReports.add(reportRepository.save(new Report()));
    }

    List<Report> actualReports = reportService.showReports();
    assertEquals(expectedReports.size(), actualReports.size());
  }

What I need to do that CommandLineRunner will be ignored when run in tests but all ApplicationContext, JPA and so on will be initialized?
UPDATE
It seems I have found the solution:

*

*Added @Profile("!test") to App.class

*Created new AppTest.class in test directory where I initialize only SpringApplication without CommandLineRunner

*Added @ActiveProfile("test") to ReportServiceTest.class

AppTest.class
@SpringBootApplication
@Profile("test")
public class AppTest {

  public static void main(String[] args) {
    SpringApplication app = new SpringApplication(AppTest.class);
    app.setLogStartupInfo(false);
    app.run(args);
  }
}


text:
Q: Subtracting one polygon from another in MapInfo 15 I want to make a hole in a polygon.
In older versions of MapInfo I did it with ease, but how do I do it in the current version which is 15?

A: From How to remove overlapping areas from a polygon in MapInfo Pro the procedure seems to be to:

*

*Select the region from which the overlapping areas will be removed.

*Objects > Set Target (32-bit) or Spatial > Set Target (64-bit).

*Select the overlapping regions.

*Objects > Erase (32-bit) or Spatial > Erase (64-bit).

The overlapping polygons will now be erased from original layer

A: Find the DrawTools application (this links to the 32-bit versions) and use the tool "Remove from selected region" which allows you to draw a polygon and use that to delete from the currently selected object.
It basically deletes the part of the selected object that is inside the drawn polygon.
DrawTools also comes for the 64-bit versions of MapInfo Pro, and can be downloaded directly from the MapInfo Marketplace.


text:
Q: Comparisons with "Comparable" type variables in java? I'm working on a University assignment, and I have to store elements in an array of the "Comparable" type. Eg:
protected Comparable storage[];

The elements that will be stored in this array are going to be either all integers, or all strings, but they're obviously created with the "Comparable" type as opposed to being created as int, or String.
What I'm having problems doing is comparing these values. At any given point, say the array is filled with "Comparable" elements that are actually integers, how can I compare them? I get that I have to use the compareTo() method, but what would the implementation look like? I've looked at the Java document online, and it has simply confused me even more.
Just to summarize, at any given point, the array might have "Comparable" type elements that are actually all integers, or all the elements will be Strings that were also made with the "Comparable" type. There's no mixing and matching of the integer and Strings in the array, it's just one or the other. I want to know how I would make the compareTo() method so that I can easily compare two elements in the array, or any two "Comparable" elements for that matter, and return say a 1, -1, or 0 if one is greater/less than the other
Would appreciate any help. I'm completely lost.

A: You need not to implement/override the compareTo method. When you will call compareTo, this method will be called on either Integer/String class.
If you were filling the array with your own custom class type then u were required to override compareTo method,not with your current assignment requirement. Maybe u can take this challenge to learn more about Comparable in java.

A: You do not need to implement the compareTo methods for the Integer and String classes because they are already implemented and used. All you need to do is fill the array of comparables and that's it, if you call sort on them they will be properly sorted unless the array has mixed types of elements (strings and integers) which you mentioned that wouldn't be the case.
In the documentation you will find that both classes already implement comparable:
.
http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html?is-external=true
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html?is-external=true
Because these classes implement the interface according to polymorphism you can insert them in the mentioned array without any problems.
Strings are compared bases on the String class implementation of the compareTo method which according to the documentation mentioned would be using lexicographic order or they are compared lexicographically.
http://en.wikipedia.org/wiki/Lexicographical_order
Which basically means alphabetic order if all characters are lower case or all characters are upper case, and the characters with lower ascii value becoming smaller in comparison.


text:
Q: Configuring eclipse to delete logs before tomcat server startup I am using Galileo with tomcat 5.5 server. I want to delete the logs from specific folder every time I start the server. Instead of doing this manually , can i automate this process ? What I need is when i click on the start in eclipse, before start up, the logs should get deleted. How can i achieve this ?

A: I'm not sure if Eclipse is the right tool to accomplish that. In my current project server start and application deployment is managed by Ant and include a Task to erase Logs between this processes is trivial.
Ant integrates nicelly with Eclipse and Tomcat. You can do the same with Maven if you prefer


text:
Q: how to auto sorted result from vlookup(google sheet) I have this formula on google sheet
VLOOKUP(upper(J2:J),colorState!A:B,{2}*sign(row(J2:J)),FALSE)

and I want it to sort the result ascending automatically when I add new data or edit(like arrayformula)
Is there anyway or any formula to do that? (I know that there's SORT formula but I'm not sure how to use it together)
thanks.

A: I believe I understand what you need :)
Essentially what I understand is that you would like to recreate the "main" sheet but have it automatically ordered by the 'color' column when new data is added.  I don't have any idea how to do this to the raw data but you can mirror the raw data by creating another sheet (name 'mainmirror') and in cell A1 just enter this formula:
=query(main!$A:$R,"select * order by P ASC",-1)

It will take you 2 seconds to reformat with a filter view, and you'll be left with a mirror of 'main' that is always sorted by column P and should remain current as data is added.
Hopefully this is an acceptable workaround.  Other option would be to use a script but this is less tedious if it's suitable.
Side note: this method will turn your values into strings to mirror them on the duplicate sheet, so on the 'main' sheet I would recommend changing the cell format of column P to a custom number format, 00, which will ensure there's a leading 0 if there's only one digit.  this will cause the strings in the mirror to sort correctly, instead of 1,11,12,2,3,4,etc.  If you're expecting column P to have 3 digit value, make the number format 000 accordingly.


text:
Q: Definition of "allocation unit" in C++? The C++17 standard uses the term "allocation unit" several times in section 12.2.4 when discussing bit-fields but doesn't seem to define what the term means. The standard also states, "As a special case, an unnamed bit-field with a width of zero specifies alignment of the next bit-field at an allocation unit boundary."
So I have two questions regarding these concepts, using the code below as an example:

*

*What does the standard mean by the term "allocation unit"?

*What is the significance of the data type specified for unnamed bit-fields?
In the second question my assumption is that the data type means that the bit-field that follows should be aligned on the next boundary for that data type.
struct tag
{
   char X:3;
   unsigned int :0;   // start next bit-field on next unsigned int boundary?
   char Y:4;
   unsigned char :0;  // start next bit-field on next unsigned char boundary?
   long Z:32;
};

A: Almost all of the behavior of bitfields is implementation defined, so you can't look to the standard for details of how they work.
The term "allocation unit" is deliberately vague. It's definition is really by implication:

Allocation of bit-fields within a class object is
  implementation-defined. Alignment of bit-fields is
  implementation-defined. Bit-fields are packed into some addressable
  allocation unit. [emphasis added] [class.bit]/1

It's up to the implementation to tell you what "allocation unit" means. The only other requirement is that an allocation unit has to be "addressable". This is the only place where the word "addressable" is used, so you're still on your own.

A: I believe the term "allocation unit" is referring to what the size of bit-field's type is.
CPP reference on bit-fields states:

The special unnamed bit field of size zero can be forced to break up padding. It specifies that the next bit field begins at the beginning of its allocation unit:

I have modified the example from CPP reference on bit-fields to illustrate this.
#include <iostream>
struct S1 {

    unsigned char b1 : 1;
    //unsigned char :0; // #1. start a new byte
    unsigned char b2 : 1;

};

struct S2 {

    unsigned int b1 : 10;
    //unsigned int :0; // #2. start a new int
    unsigned int b2 : 10;

};

int main()
{
    std::cout << sizeof(char) << '\n';
    std::cout << sizeof(int) << '\n';
    std::cout << sizeof(S1) << '\n'; // usually prints 1
    std::cout << sizeof(S2) << '\n'; // usually prints 4

}

The sizes of S1 and S2 will be 1 and 4 respectively which are also the sizes of char and int.  This is what we would normally expect.
But if I uncomment lines #1 and #2 in the structure declarations above, the sizes of S1 and S2 will be 2 and 8  respectively. This is the consequence of the statement you have cited in the question:

As a special case, an unnamed bit-field with a width of zero specifies alignment of the next bit-field at an allocation unit boundary."

Live Demo