text:
Q: Case statement combining two separate fields into one new field EDIT:
Let me try again. There are two main tables in use here. One is called General, which I need to use to join to another table called Customer. Customer has COLUMNS, such as first name, last name, age, etc. There is only 1 record for each query, but that record may contain two customers. I want to group the new CASE column, with the ages of both c1 and c2 in the proper grouping.
So my problem below is, I can use CASE to create a new column (great), for each customer if I want to individually, but I need to GROUP BY only one new CASE, because I want the groupings to not include say a customer2 who is a 40 year age in a 20-30 grouping, which happens if customer 1 is in that grouping. Does this make sense? I don't see how this is possible without somehow creating a new table, but I don't want to modify the DB at all. Sorry if this doesn't make sense, but I inherited this and trying to solve this has been driving me crazy. The only way I can do this now is excel and moving the values manually and then using a pivot table. Here is the crux of the code:
SELECT
gn.general,
c1.custage1 AS 'Customer1 Age',
c2.custage2 AS 'Customer 2 Age',
CASE
WHEN c1.custage BETWEEN 20-30 THEN '20-30'
WHEN c2.custage BETWEEN 20-30 THEN '20-30'
END AS 'AGEGROUP'
FROM GENERAL gn
LEFT JOIN CUSTOMER ON c1.general = g.general AND c1.general = "CUST1"
LEFT JOIN CUSTOMER ON c2.custage = g.general AND c2.general = "CUST2"
Then in my table I added a parent group, grouping by AGEGROUP, which looks great, but doesn't break up the c2.custage into it's correct category. I know the logic is flawed, just can't think of how to resolve this. Still learning obviously.
Thanks for any feedback in advance.
I have 2 customers on one sale, one has c.custage1 and one has custage2. Trying to group both ages into one new column and show totals, so for example:
CASE
    WHEN c.custage1 BETWEEN 20-30 THEN '20-30'
    WHEN c.custage2 BETWEEN 20-30 THEN '20-30'
END AS 'AGEGROUP'

But this isn't working. I'd like to give group summaries of both customer ages as one. I'd prefer to not add any new columns to the tables. Thanks!

A: Please try to spell out the word 'and'
CASE
    WHEN c.custage1 BETWEEN 20 and 30 THEN '20-30'
    WHEN c.custage2 BETWEEN 20 and 30 THEN '20-30'
END AS AGEGROUP


text:
Q: Overflow-x doesn't work with absolutely positioned divs So I am creating a slideshow and I am facing a problem. I have some divs, which positions are absolute and I give left: 100%; to them. This nicely works on full screen, but when I resize the screen absolute position breaks overflow-x: hidden; given to body and html tags. How to fix this?
Here is the code

html,
body {
  margin: 0 auto;
  overflow-x: hidden;
}

.slides {
  width: 100%;
  height: 100vh;
  position: absolute;
}

.slide-img {
  width: 100%;
  height: 100%;
}

#slide-2 {
  left: 100%;
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Marseille</title>
  <link rel="stylesheet" href="css/main.css">

A: You have to set the left parameter for all four (or actually three) absolutely positioned DIVs, other wise DIV #3 and 4 will (which still have left: 0) be shown inside the viewport and cover DIV #1.
In the snippet below I set the left paramter to 25/50/75% for DIVs 2-4 to demonstrate that it works (you need to set those to at least 100% or more, depending on how you slide them into the viewport).

html, body {
  margin: 0 auto;
  overflow-x: hidden;
}

.slides {
  width: 100%;
  height: 100vh;
  position: absolute;
}

.slide-img {
  width: 100%;
  height: 100%;
}

#slide-2 {
  left: 25%;
}
#slide-3 {
  left: 50%;
}
#slide-4 {
  left: 75%;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Fitting a GAM with a count response variable across multiple years I am trying to fit a GAM where the response variable is a count. For my particular problem, I have counts for a species, across a number of different years. So it would seem to me that the best thing to do would be to generate a mean across the three years, and use this as the response variable. However this doesn't work when the GAM is configured to use a poisson distribution; presumably as this distribution only works with the integers?
Reproducible code as follows:
set.seed(0)
dat <- data.frame(count_y1 = rpois(100,1),
                  count_y2 = rpois(100,1),
                  count_y3 = rpois(100,1),
                  pred1 = rnorm(100, 10, 1),
                  pred2 = rnorm(100, 0, 1),
                  pred3 = rnorm(100, 0, 1),
                  pred4 = rnorm(100, 0, 1))

library(dplyr)
dat <- dat %>%
         rowwise() %>%
         mutate(count_mn = mean(c(count_y1, count_y2, count_y3)))

If I set up the GAM as follows:
model <- gam(count_mn ~ s(pred1) + s(pred2) + s(pred3) + offset(pred4),
             data = dat,
             family = poisson(link="log"),
             method = "REML",
             select = TRUE)

(in my real world problem I have an offset that handles a variable survey area for where the species count was taken). This gives the following output:
Error in if (abs(old.score - score) > score.scale * conv.tol) { :
  missing value where TRUE/FALSE needed
In addition: There were 50 or more warnings (use warnings() to see the first 50)

If I now assign quasipoisson to family, which I understand is used for zero-inflated and continuous response data, I get a model fit:
Family: quasipoisson
Link function: log

Formula:
count_mn ~ s(pred1) + s(pred2) + s(pred3) + offset(pred4)

Estimated degrees of freedom:
1.640 0.102 1.754  total = 4.5

REML score: 54.81147

So my question would be, is it possible to fit the model across the three count years , using a poisson distribution?

A: You could use a sum across years, not a mean.  The sum of Poisson variables is Poisson; the mean isn't.
set.seed(0)
dat <- data.frame(count_y1 = rpois(100,1),
                  count_y2 = rpois(100,1),
                  count_y3 = rpois(100,1),
                  pred1 = rnorm(100, 10, 1),
                  pred2 = rnorm(100, 0, 1),
                  pred3 = rnorm(100, 0, 1),
                  pred4 = rnorm(100, 0, 1))

library(dplyr)
dat <- dat %>%
         rowwise() %>%
         mutate(count_sm = sum(c(count_y1, count_y2, count_y3)))

and now your gam fits fine
model <- gam(count_sm ~ s(pred1) + s(pred2) + s(pred3) + offset(pred4),
             data = dat,
             family = poisson(link="log"),
             method = "REML",
             select = TRUE)
summary(model)

You could also add another offset equal to log(3) so that the rest of the linear predictor is now a model for log(E[sum]/3) rather than log(E[sum])


text:
Q: serve arbitrary static content on the fly with cherrypy I am trying to create a media server using cherrypy and cant get cherrypy to serve up files in any directory that isn't set at startup in the config. I don't want to expose the drives root directory I would prefer to expose a directory at a time as I need it. Is there away to do this?
here is the relevant snippet of my current code.
@cherrypy.expose
def serve_mp3(self, mp3_path):
    #cherrypy.config.update({"media":{
    #"tools.staticdir.on" : True,
    #"tools.staticdir.root" : "C:\\Documents and Settings\\sdc\\My Documents\\My Music",
    #"tools.staticdir.dir" : "",
    #"tools.staticfile.root" : "C:\\Documents and Settings\\sdc\\My Documents\\My Music"
    #}})
    static_handler = cherrypy.tools.staticdir.handler(section="/media", dir="C:\\Documents and Settings\\sdc\\My Documents\\My Music")
    cherrypy.tree.mount(static_handler, '/media')
    mp3 = mp3_path.rsplit("\\",1)[1]
    return "media/" + urllib.quote(mp3)

Thanks go to cyraxjoe the mess above wound up being re-factored as
    @cherrypy.expose
    def serve_mp3(self, mp3_path):
      mp3_path = urllib.unquote(mp3_path)
      return(cherrypy.lib.static.serve_file(mp3_path, content_type="audio/mpeg", disposition=None, name=None))

which worked just fine for serving an audio tag. I know as it exists this is basically front door access to my hdd but this is just a first step and the final result will be driven by a data base

A: I think that you should use the functions to serve static files directly instead of the handler, you are fighting with the tool. With the direct call of the functions you can serve any arbitrary path or file object if you like.


text:
Q: How to log every GET call in MVC 4? I'm using Mozilla firefox browser for running my application & saw something in firebug developer tool in [Net] tab which shows how many requests have been raised to load current displayed page. Please check below images with highlighted area:Image 1:
Image 2:

In Image 2, its showing the complete url for image file. I want to log all such highlighted GET calls for images, css & js files. Can somebody help me?

A: javascript can't detect that. This images and font files are probably requested by the browser because it is in a CSS file. The only way to detect that in javascript should be to parse every CSS in the page to find those URL.
But in firebug, you can filter the request by selecting a filter in the top of the Net tool. Just click on "Images" for example and you'll see only requests for images.
If you want to detect it server side. Note that some browser don't make a request at all if they want to use their cache. But if they want to request an image, you can definitively see the request server-side. It depends of your server technologies.


text:
Q: jQuery slidetoggle rotation animation I have problematic jQuery function. I want to have a slidetoggle which will animate rotation of an arrow next to slide toggle text. Now arrow rotation animation is played only the first time ant also its not animating rotation back (while is slidetoggle closing)
I am starting with web programming and I cant find answer for my question so i will be glad for every help.
That arrow is not rotating back while is the list closing

$(1.2.html).ready(function() {
  $("click").click(function() {
    $("ul").slideToggle("slow");
    $(".arrow").animate({
      deg: 180,
    }, {
      speed: "slow",
      step: function(now) {
        $(this).css({
          transform: 'rotate(' + now + 'deg)'
        })
      }
    });
  })
});
.arrow {
  float: right;
}

p {
  float: left;
}

ul {
  display: none;
}

Toggle

hidden1

hidden2

A:

$('document').ready(function() {
  $(".click").click(function() {
    $("ul").slideToggle("slow");
    $('.arrow').toggleClass('goLeft')
  })
});
.arrow {
  float: right;
   transition : all 0.8s ease-in
}

p {
  float: left;
}

ul {
  display: none;
}
.goLeft {
  -webkit-transform:rotate(180deg);
   transition : all 0.8s ease-in
}

Toggle

hidden1

hidden2

This does it for you, also on codepen https://codepen.io/abeshi-emmanuel/pen/eYOZREY


text:
Q: Как исключить файл из VCS в PyCharm или других продуктах JetBrains? В проект под VCS (допустим - Git) добавлен файл (в дереве проекта отображается зеленым), коммит еще не произведен. Вопрос: как исключить файл из VCS (чтобы он отобразился красным) не удаляя с диска?
Единственное решение, которое я нашел, это скопировать этот файл внешними средствами на уровень выше проекта, удалить его в проекте средствами самой IDE (иначе она запоминает принадлежность файла VCS даже в отсутствии самого файла) и вернуть файл обратно опять внешними средствами, только тогда он высвечивается красным. Но это - абсурд, должен быть штатный способ для этого. Если существует операция "Add to VCS", то должна существовать и обратная ей. Тем более, что это никак не затрагивает саму VCS, если этот файл еще не разу не был закоммичен.
Непосредственно сейчас столкнулся с этой проблемой в PyCharm, но, видимо, эта проблема общая для всех продуктов JetBrains.

A: конечно же в JetBrains существует функция, которая удаляет файл из системы контроля версий. Эта функция называется Revert.
Вы можете вызвать её двумя способами:
а) Выделите файлы, которые вы не хотите коммитить и нажмите Ctrl+Alt+Z . Они "покраснеют", как вы и хотите.
б) Нажмите правой кнопкой мыши на нужном файле. Затем откройте меню Git и нажмите Revert.


text:
Q: Docker compose: unable to connect to Postgres I have Go as my API and PostgreSQL as my database.
I can run my backend using the docker container when executed in development environment. However, when I run my dockerfile and docker-compose. The database is not connecting to postgres.
Dockerfile
    FROM golang:alpine
    RUN mkdir /backend
    ADD . /backend/
    WORKDIR /backend
    COPY go.mod .
    COPY go.sum .
    COPY .env .
    RUN go mod download
    RUN go build -o main .
    EXPOSE 3002
    CMD ["./main"]

docker-compose.yml
version: '3.3'

services:

  postgres:
    image: "postgres"
    ports:
      - "5432:5432"
    env_file:
      - .env
    volumes:
      - ./postgres/:/var/lib/postgresql/data/
    restart: always
    networks:
      - "backend.network"

  nginx:
    image: nginx:latest
    volumes:
      - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
    depends_on:
      - backend
      - postgres
    ports:
      - "8080:8080"
    links:
      - 'postgres'
      - 'backend'
    networks:
      - "backend.network"

  backend:
    build: "."
    ports:
      - "3002:3002"
    depends_on:
      - postgres
    links:
      - postgres
    restart: "always"
    networks:
      - "backend.network"

networks:
  backend.network:

.env
DB_HOST=localhost
POSTGRES_PORT=5432
POSTGRES_USER=postgres
POSTGRES_PASSWORD=pass
POSTGRES_NAME=db

Go connection
DB, err = gorm.Open("postgres", fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", config.Config("DB_HOST"), port, config.Config("POSTGRES_USER"), config.Config("POSTGRES_PASSWORD"), config.Config("POSTGRES_NAME")))

    if err != nil {
        panic("failed to connect database")
    }

Error
failed to connect databasedial tcp 127.0.0.1:5432: connect: connection refused
exit status 1

I really don't know what's wrong with my dockerfile.

A: as @blami said:
your backend is trying to connect to "localhost" as each of your containers will have its own "localhost".
youc can use your machine host ip, or your database container ip. you can find it using docker inspect <container_name>

A: As @blami pointed out, the DB_HOST should be "postgres". Also, you are passing the .env file to the postgres image but not to the backend one (it may be using default values). If it keeps failing please comment the error you get.
Finally I would recommend to use a builder image to compile your server and then copy it to a smaller image using alpine (if you want to go a step further you can build the final image from scratch), making the container size as lightweight as we can, just like this:
FROM golang:1.15-alpine as builder

COPY . /backend

WORKDIR /backend

RUN go build -o main -ldflags="-s -w" . # If you are building the image below from scratch specify the CGO_ENABLED=0 env var

-----

FROM alpine:3.12.1

COPY --from=builder /backend/main /usr/bin/

EXPOSE 3002

ENTRYPOINT ["/usr/bin/main"]

Dockerfile notes based on best practices article:

*

*Try to specify images version whenever possible as the lastest one may introduce new bugs to your app. However, it's not strictly required.

*Prefer COPY to ADD when the resource we are trying to copy is not an url.

*If the purpose of the container is purely running a server it's recommended to use ENTRYPOINT instead of CMD, which will ignore any parameters passed when running the container (if you want to use "exec" command then CMD is preferred).

Go binary note: -ldflags="-s -w" is often used to reduce the binary size by stripping the debugging information (more info here).


text:
Q: Gatkeeper prevents Photos from importing Aperture Libary I am trying to open a 160GB Aperture Library with the Photos.app
The library can be opend with aperture w/o problems.
As soon as I start opening it with Photos, Gatekeeper starts checking the files.
This seems to take very long. I did let it running for a couple of hours and quit everything.
I tried to disable Gatekeeper with
sudo spctl --master-disable

But that didn't change a thing.
It still opens the dialog and start checking the files, with no progress:

A: The library was on an external diksdrive.
I set the "Ignore Permissions" option with Command-I for that drive.
Restartet the Mac and opened the library with Photos and the import was done in several minutes.


text:
Q: Play video or gif for 10 seconds, pause, click button, play for 3 seconds and jump to another timestamp in video & play for set duration I feel there's a very simple solution to this either using something like the youtube iframe api or something with jQuery / javascript or even css with animated gifs in lieu of video...? idk
I'm looking for you guys to help me confrm that it's actually possible.. any proposed solutions or starting points would be greatly appreciated.
Essentially I'd like to configure a central video div on an html page that has interactivity in the way of buttons that can provide the functionality to jump to a specific time stamp in the video then play for a specific duration and stop, but upon selecting a different button it will continue to play the video from where it paused previously for about 3-5 seconds and then jump to the section of the video identified by the button that was just clicked.
Think opening animation, Pause
user selects button, video plays to show reversal of opening animation
then video jumps to timestamp on the video that user just selected and plays for a set time
then pauses and waits for user to select different button...
.. rinse and repeat for multiple interaction points.
This needs to be mobile friendly, which I don't think will be an issue once I get a proof of concept sorted.
Thanks in advance all!


text:
Q: How to setup PyCharm to develop AWS Lambda function on local machine? I am looking forward to developing some AWS lambda functions in python using PyCharm. How can I setup my IDE to develop and test the function locally? Can experts guide how to set it up? Any links or relevant tutorials will be really helpful.

A: Directly  go through the page->
https://medium.com/@bezdelev/how-to-test-a-python-aws-lambda-function-locally-with-pycharm-run-configurations-6de8efc4b206
pip install python-lambda-local
python-lambda-local -f lambda_handler lambda_function.py event.json

A: As of the announcement at the re:Invent 2018 keynote, Jetbrains now offers the AWS Toolkit which allows local and remote development of Lambda functions.
Despite some lingering issues it works quite well.
User exan has provided the link on AWS' site here
There is also a blog post when using PyCharm on MacOS
Toolkit page on Jetbrains website
UPDATE April 2019: Jetbrains has been very responsive and active in fixing any issues. Issues with credentials and templates seem resolved and it's quite a joy to work with.


text:
Q: Issue with Microsoft Access We have 2 legacy systems - One in C++ and other in C#  that connect to the same access database. The access database is not password protected and we use the following connection string to connect to the databases
Provider=Microsoft.Jet.OLEDB.4.0; Persist Security Info=False ;Data Source= AlarmHistory.mdb

C# application polls a table in the database every 10 seconds. Once in while , the C# application crashes with the error message -
System.Data.OleDb.OleDbException: Cannot start your application. The workgroup information file is missing or opened exclusively by another user.

The log analysis revealed that both the applications are not accessing the database simultaneously ... Any  idea on what could cause such a situation... Please Help

A: They might not be accessing the database at exactly the same time, but that error message indicates that they (or something else) is accessing the lock file at the same time. Is the poll opening and closing the connection each time? You could move the open and close to outside the timer so that the connection is opened and remains open for the life of the application.


text:
Q: Convolution and laplace transform of an ODE I was wondering if it was possible to use convolution to solve
$$y'' +3ty'-6y=\sin(t)$$
How would you use convolution on the $3y't$ part, or is that even allowed?

A: Well, we know that:
$$\mathscr{L}_t\left[\text{n}\cdot t\cdot\text{y}\space'\left(t\right)\right]_{\left(\text{s}\right)}=\text{n}\cdot\mathscr{L}_t\left[t\cdot\text{y}\space'\left(t\right)\right]_{\left(\text{s}\right)}\tag1$$
Now, using the 'frequency-domain derivative' property of the Laplace transform:
$$\text{n}\cdot\mathscr{L}_t\left[t\cdot\text{y}\space'\left(t\right)\right]_{\left(\text{s}\right)}=-\text{n}\cdot\frac{\text{d}}{\text{d}\text{s}}\left\{\mathscr{L}_t\left[\text{y}\space'\left(t\right)\right]_{\left(\text{s}\right)}\right\}\tag2$$
Now, using the 'derivative' property of the Laplace transform:
$$-\text{n}\cdot\frac{\text{d}}{\text{d}\text{s}}\left\{\mathscr{L}_t\left[\text{y}\space'\left(t\right)\right]_{\left(\text{s}\right)}\right\}=-\text{n}\cdot\frac{\text{d}}{\text{d}\text{s}}\left(\text{s}\cdot\text{Y}\left(\text{s}\right)-\text{y}\left(0\right)\right)=-\text{n}\cdot\left(\text{s}\cdot\text{Y}\space '\left(\text{s}\right)+\text{Y}\left(\text{s}\right)\right)\tag3$$


text:
Q: CakePHP 2.x: Alaxos ACL Plugin- configure the admin route i am a cakephp beginner , have not much exposure to cakephp.
I have followed installation step for Alaxos ACL plugin foe cakephp 2.0 from -alaxos site .. there second step is configuring admin routing .
that i have done by adding
Router::connect('/admin/acl', array('plugin' => 'acl', 'controller' => 'acl', 'action' => 'admin_index', 'admin' => true));

to my Cake/Routing/Router.php file and configuring  app/Config/core.php: by adding following line
 Configure::write('Routing.prefixes', array('admin'));

i am not sure whether this is the correct way of doing it...
On accessing the plugin http://localhost/cakeacl/admin/acl it gives error
 **Private Method in AclController

Error: AclController::admin_index() cannot be accessed directly.**
Please help me ..Thanks in advance...

A: try to put only the following in the app/Config/core.php and remove the Router configurations.
Configure::write('Routing.prefixes', array('admin'));

A: Have you tried this guide http://book.cakephp.org/1.3/view/1543/Simple-Acl-controlled-Application from the official site yet?


text:
Q: form_tag , form_remote_tag - action not being called In my new Team form, user can select players, from a select listbox, to associate with team and can also create new players. Clicking on the 'New Player' button opens a popup form with the following code
When i use the form tag (see below), clicking on the submit button uses the correct action.
<%= form_tag(:controller => "teams", :action => "createPlayers") do %>
Player Name: <%= text_field_tag(:name, nil) %>
<%= submit_tag("Create New Player") %>

However am planning on using ajax to update the select list for players. When i use 'form_remote_tag' instead of 'form_tag' and i click on the submit button, the 'createPlayers' action is not called. In fact nothing happens..
I would be grateful if someone can tell me why using 'form_remote_tag' does not call the 'createPlayers' action when the submit button is pressed.
Many many thanks for any suggestion provided.
Cheers

A: <% form_remote_tag :url => { :controller => 'xyz', :action => :you method } do %>
<%=text_field_tag : %>
<%= submit_tag "" %>
<% end %>
something like that


text:
Q: Hive Activity failing with ADF using BYOC HDInsight cluster (Linux) I am getting below Error while trying to execute ADF Hive Activity. When I run Hive query directly on HDInsight cluster, it works fine. but while running in ADF Hive Activity it is failing. I did lot's of trial and error but issue still persist. Does anyone got idea what could be issue?
WARNING: Use "yarn jar" to launch YARN applications.
17/02/09 06:09:45 INFO impl.TimelineClientImpl: Timeline service address: http://headnodehost:8188/ws/v1/timeline/
17/02/09 06:09:46 INFO impl.TimelineClientImpl: Timeline service address: http://headnodehost:8188/ws/v1/timeline/
17/02/09 06:09:46 WARN ipc.Client: Failed to connect to server: hn0-xxxxx.xxxxx133hn2u3kb1xxx0vlmsre.jx.internal.cloudapp.net/10.0.0.17:8050: retries get failed due to exceeded maximum allowed retries number: 0
java.net.ConnectException: Connection refused
    at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
    at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:744)
    at org.apache.hadoop.net.SocketIOWithTimeout.connect(SocketIOWithTimeout.java:206)
    at org.apache.hadoop.net.NetUtils.connect(NetUtils.java:531)
    at org.apache.hadoop.net.NetUtils.connect(NetUtils.java:495)
    at org.apache.hadoop.ipc.Client$Connection.setupConnection(Client.java:649)
    at org.apache.hadoop.ipc.Client$Connection.setupIOstreams(Client.java:744)
    at org.apache.hadoop.ipc.Client$Connection.access$3000(Client.java:397)
    at org.apache.hadoop.ipc.Client.getConnection(Client.java:1521)
    at org.apache.hadoop.ipc.Client.call(Client.java:1431)
    at org.apache.hadoop.ipc.Client.call(Client.java:1392)
    at org.apache.hadoop.ipc.ProtobufRpcEngine$Invoker.invoke(ProtobufRpcEngine.java:229)
    at com.sun.proxy.$Proxy19.getNewApplication(Unknown Source)
    at org.apache.hadoop.yarn.api.impl.pb.client.ApplicationClientProtocolPBClientImpl.getNewApplication(ApplicationClientProtocolPBClientImpl.java:221)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.hadoop.io.retry.RetryInvocationHandler.invokeMethod(RetryInvocationHandler.java:258)
    at org.apache.hadoop.io.retry.RetryInvocationHandler.invoke(RetryInvocationHandler.java:104)
    at com.sun.proxy.$Proxy20.getNewApplication(Unknown Source)
    at org.apache.hadoop.yarn.client.api.impl.YarnClientImpl.getNewApplication(YarnClientImpl.java:220)
    at org.apache.hadoop.yarn.client.api.impl.YarnClientImpl.createApplication(YarnClientImpl.java:228)
    at org.apache.hadoop.mapred.ResourceMgrDelegate.getNewJobID(ResourceMgrDelegate.java:188)
    at org.apache.hadoop.mapred.YARNRunner.getNewJobID(YARNRunner.java:231)
    at org.apache.hadoop.mapreduce.JobSubmitter.submitJobInternal(JobSubmitter.java:153)
    at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1290)
    at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1287)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:415)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1724)
    at org.apache.hadoop.mapreduce.Job.submit(Job.java:1287)
    at org.apache.hadoop.mapred.JobClient$1.run(JobClient.java:575)
    at org.apache.hadoop.mapred.JobClient$1.run(JobClient.java:570)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:415)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1724)
    at org.apache.hadoop.mapred.JobClient.submitJobInternal(JobClient.java:570)
    at org.apache.hadoop.mapred.JobClient.submitJob(JobClient.java:561)
    at org.apache.hadoop.streaming.StreamJob.submitAndMonitorJob(StreamJob.java:1014)
    at org.apache.hadoop.streaming.StreamJob.run(StreamJob.java:135)
    at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:76)
    at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:90)
    at org.apache.hadoop.streaming.HadoopStreaming.main(HadoopStreaming.java:50)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.hadoop.util.RunJar.run(RunJar.java:221)
    at org.apache.hadoop.util.RunJar.main(RunJar.java:136)
17/02/09 06:09:46 INFO client.ConfiguredRMFailoverProxyProvider: Failing over to rm2
17/02/09 06:09:50 INFO mapred.FileInputFormat: Total input paths to process : 1
17/02/09 06:09:51 INFO mapreduce.JobSubmitter: number of splits:1
17/02/09 06:09:51 INFO mapreduce.JobSubmitter: Submitting tokens for job: job_1486536013226_0707
17/02/09 06:09:51 INFO mapreduce.JobSubmitter: Kind: mapreduce.job, Service: job_1486536013226_0706, Ident: (org.apache.hadoop.mapreduce.security.token.JobTokenIdentifier@7a399295)
17/02/09 06:09:53 INFO impl.YarnClientImpl: Submitted application application_1486536013226_0707
17/02/09 06:09:53 INFO mapreduce.Job: The url to track the job: http://hn1-xxxxx.xxxxx133hn2u3kb1xxx0vlmsre.jx.internal.cloudapp.net:8088/proxy/application_1486536013226_0707/
17/02/09 06:09:53 INFO mapreduce.Job: Running job: job_1486536013226_0707
17/02/09 06:10:11 INFO mapreduce.Job: Job job_1486536013226_0707 running in uber mode : false
17/02/09 06:10:11 INFO mapreduce.Job:  map 0% reduce 0%
17/02/09 06:10:31 INFO mapreduce.Job: Task Id : attempt_1486536013226_0707_m_000000_0, Status : FAILED
Error: java.lang.RuntimeException: PipeMapRed.waitOutputThreads(): subprocess failed with code 2
    at org.apache.hadoop.streaming.PipeMapRed.waitOutputThreads(PipeMapRed.java:322)
    at org.apache.hadoop.streaming.PipeMapRed.mapRedFinished(PipeMapRed.java:535)
    at org.apache.hadoop.streaming.PipeMapper.close(PipeMapper.java:130)
    at org.apache.hadoop.mapred.MapRunner.run(MapRunner.java:61)
    at org.apache.hadoop.streaming.PipeMapRunner.run(PipeMapRunner.java:34)
    at org.apache.hadoop.mapred.MapTask.runOldMapper(MapTask.java:453)
    at org.apache.hadoop.mapred.MapTask.run(MapTask.java:343)
    at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:168)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:415)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1724)
    at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:162)

Container killed by the ApplicationMaster.
Container killed on request. Exit code is 143
Container exited with a non-zero exit code 143

A: I got this working. Actually, .Net Activity was failing in Data Factory and it was using Linked service as HDInsight cluster (I was using Linux based Cluster). I changed Linked service to Azure Batch Account linked service and this pipeline works as expected.


text:
Q: Difference Between WCF Service, WCF RIA Services, and WCF Data Service What is the difference between WCF Service, WCF RIA Services and WCF Data Services?

A: WCF is a communication infrastructure for services in general. WCF RIA services automatically generates client and server proxy objects to facilitate application development, and depends upon WCF to do the actual communication. ADO.Net data services has been renamed to WCF Data Services, and provides OData services over WCF.

A: Here is a nice article explaining WCF (ADO.Net) Data Services vs WCF Ria Data Services
http://jack.ukleja.com/wcf-data-services-vs-wcf-ria-services/

A: This one is by Collin Blair
http://forums.silverlight.net/t/103015.aspx/1
You question is analogous to asking what the difference between a plain hamburger patty and a hambuger which is why it is hard to get a straight answer. Getting a good answer is also hampered by the fact that RIA Services will not be "feature complete" until at least PDC so any answer you get will be based on expectations and speculation. Finally, RIA Services is plural for a reason, there are multiple classes in RIA Services which do different things. Here is my answer based on the roadmaps and my understanding of the goals of the RIA Services team.
RIA Services is a library of client and server components that bolt on to ADO.NET Data Services. When the full stack of RIA Services is used the difference between RIA Services and plain WCF are as follow:
The client side data objects are generated using reflection at compile time based on the actual server side objects instead of a service contract. This allows RIA Services to provide a much richer client side object model by including any business rules and relationships between objects. However, this does mean that RIA Services gives up some flexibility compared to plain WCF. For example, the RIA Services serializaer does not currently support some data types which WCF would be able to handle.
RIA Services, like ADO.NET Data Services, supports serializing LINQ queries between the client and the server. This means that the client can create the LINQ query and have it run server side.
RIA Services, unlike plain ADO.NET Data Services, does not automatically generate CRUD at runtime. For people familiar with SQL Server, I describe ADO.NET Data Services as supporting regular triggers (aka query interceptors) while RIA Services requires INSTEAD OF triggers.

A: The following answer is not by me, but still answer a part of the question that is left unanswered.
I copy-pasted this answer from here https://social.msdn.microsoft.com/Forums/en-US/687426d9-709f-4e73-8c4c-dd3630f006e7/wcf-data-service-or-wcf-service?forum=adodotnetdataservices

WCF Services are operation centric - the main thing you do with these
  is define operations (functions). Data comes as a secondary thing in a
  way. On the other hand they can work over lot of different
  transports/protocols. You have the ability to stricly define what the
  client can and can not do. Client can't really make up new
  queries/operations, the server must implement everything the client
  needs.
WCF Data Services are data centric - the main thing you do with these
  is define a data model to be exposed. Operations on the data are
  "predefined" (Create/Delete/Update/Read). It only supports HTTP
  protocol and uses REST. You usually allow clients to decide what they
  want to do (in some boundaries). One of the main differences from WCF
  Service is that the client can issue a query against the data model
  (think SQL like stuff) which the client constructs. This means that
  the server doesn't need to know exactly what the client needs up
  front, the client will be able to tell it runtime.
Vitek Karas [MSFT]


text:
Q: How to find maximum of an inverse of a matrix? If there is a square $~n\times n~$ matrix $~H~$ where ALL the elements of $~H_{i,j}~$ are variables between two bounds, $~H_{i,j})_{min}~$ and $~H_{i,j})_{max}~$. Is there any relation to maximize $~H^{-1}~$ based on maximum or minimum (or other) value of $~H~$?
For example if we put the lower bounds of $~H_{i,j}~$ in $~H~$:
$$\pmatrix{H_{1,1})_{min}&H_{1,2})_{min}&\cr H_{2,1})_{min}&H_{2,2})_{min}}$$
which in that case norm of $~H~$ is minimum, can we say $~H^{-1}~$ is maximum. Is this sentence true? Is there any lemma or theorem?
I need to maximize $~H^{-1}~$ where the arrays of $~H~$ are variables, but I cannot find any rule in mathematics for this.
Example: Consider following matrix:$$H=\pmatrix{2a^2+5&-a\times cos(b)&\cr 4c^3&2b\sqrt{d}}$$ where $$2\le{a}\le{3}$$$$1\le{b}\le{4}$$$$1.5\le{c}\le{2}$$$$3\le{d}\le{4}$$How the variables $~a,b,c,d~$ should be selected to maximize $~H^{-1}~$? Is the answer minimum values of $~a,b,c,d~$? How do we deal with it generally when the matrix is $~n\times n~$?
Thank you in advance.

A: $$\pmatrix{1+\epsilon&1\cr 1&1}^{-1}=\pmatrix{\frac1{\epsilon}&-\frac1{\epsilon}\cr-\frac1{\epsilon}&1+\frac1{\epsilon}}$$


text:
Q: Slow distance search between postcodes My original question is here: Slow location search
I've have spent a fair bit of time on the code to get a better understand of what exactly the code is / should be doing. The code:
SELECT (fieldnames),
( 3959 * acos( cos( radians( $lat ) ) * cos( radians( `lat` ) ) * cos( radians( `lng` ) - radians( $lng ) ) + sin( radians( $lat ) ) * sin( radians( `lat` ) ) ) )  AS distance
FROM details
inner JOIN postcodes ON details.postcode = postcodes.outcode AND payment='y' AND expired='n' HAVING " . implode(" AND ", $searches)."  ORDER BY details.asking_price

The postcode is being taken from the users input calculating the long and lat and checking the distance from the postcodes table (postcode, long, lat).
Implode is checking if there are any other variable that need to be added to the search.
I have read many different posts but I cant find any that tell me why my search is taking over 10 seconds to perform.
It is something to do with how the distance is being calculated as if I search without distance, the time taken isn't a problem.
Its taking roughly 7/8 seconds to perform the search, down from about 15 seconds from the other post. I've thought about limiting the amount of results just to what are being displayed on that page (20).


text:
Q: Recursively printing out the sections and subsections of an outline Recursion is the one thing I have loads of trouble with. For this assignment we are supposed to print out an outline of sections and sub-sections. Take the following as an example.
Section 1
 Section 1.A
   Section 1.A.1
   Section 1.A.2
 Section 1.B
   Section 1.B.1
   Section 1.B.2
Section 2
 Section 2.A
   Section 2.A.1
   Section 2.A.2
 Section 2.B
   Section 2.B.1
   Section 2.B.2

This example has a depth of 3 and height of 2.
Here is my code thus far, which doesn't come anywhere near the correct output.
void printDepth(int depth, int width, int minusDepth, int minusWidth) {
    int i = 0;
    if(depth == 0)
        printf("Section XX\n");

    else {
        printf("\t");
        printDepth(depth -1, width, minusDepth, minusWidth);
    }
}

Here is the call from main()
int minusDepth = 0;
int minusWidth = 0;
printDepth(depth, width, minusDepth, minusWidth);

However, for a depth = 4 and width = 5 this only prints out:
\t\t\t\tSection XX
I'm really not sure how to proceed. Recursion is the bane of my existence.

A: #include <stdio.h>

void printDepth(int deep, int depth, int height, char *table) {
    if(deep == depth)
        return ;

    int i, j;
    char bak = table[deep];
    for(i = 0; i < height; ++i){
        printf("%*s%s", deep*2, "", "Section ");
        for(j = 0; j <= deep; ++j){
            if(j)
                putchar('.');
            putchar(table[j]);
        }
        putchar('\n');
        printDepth(deep+1, depth, height, table);
        table[deep]++;
    }
    table[deep] = bak;//restore
}

int main(void){
    char table[] = "1A1";//Effective range up to 1-9 and A-Z
    printDepth(0, 3, 2, table);
    return 0;
}

A: You need a loop that prints the sections at the current depth and executes height (which I call width instead) recursions.  You also need to pass a string containing the current prefix of the section string.
#include <stdio.h>
#include <assert.h>
#include <math.h>

#define MAX_DEPTH 100
#define MAX_WIDTH  99  // NOTE: if you increase this then section's decl in printDepth needs to be updated too

void printDepth_r(int currDepth, int depth, int width, char *section, char *sub)
{
  if (currDepth == depth)  // recursion base case
    return;

  for (int i = 0; i < width; ++i)
  {
    // TODO: write to sub the subsection determined by (currDepth, width)

    fprintf(stdout, "%*sSection %s\n", currDepth * 2, "", section);

    // TODO: append "." to sub for descendant recursions

    printDepth_r(currDepth + 1, depth, width, section, sub + /* TODO: num chars written to sub */);
  }
}

int printDepth(int depth, int width)
{
  char section[MAX_DEPTH * (2 + 1) + 1];  // NOTE: 2 == 1 + (int) (log(99) / log(10));

  assert(sizeof(section) >= MAX_DEPTH * (1 + (int) (log(MAX_WIDTH) / log(10)) + 1) + 1);

  if (depth > MAX_DEPTH || width > MAX_WIDTH)
    return -1;

  printDepth_r(0, depth, width, section, section);

  return 0;
}

int main(int argc, char **argv)
{
  printDepth(3, 2);

  return 0;
}

Note that we pass the same values of depth, width and section to all of our recursions.  So, if we wanted to reduce the amount of stack space the recursion eats at every level, then we could pull these out into a structure and pass 1 struct pointer to these 3 constants instead.  Or, even better, we could store these values in thread local storage.  Either way would allow deeper recursions before overflowing your stack.


text:
Q: Возвращаемое значение пропущено: "strcmp" У меня есть класс DVDdrive. В этом классе есть конструктор с параметрами. В теле конструктора лежит 3 strcmp. Там 3 предупреждения: Возвращаемое значение пропущено: "strcmp". Если попробовать запустить, то мне вернется в последние 3 параметра pc "Sony" с кучей символов "М", вместо того, что прописано по коду ("LG", "USB 2.0", "24x/24x/24x").
Хотя, вот, работаю с массивом чаров в соседних классах - и там все работает..
Не могу понять логику. В чем может быть проблема?
#include <iostream>
using namespace std;

// это омй класс
class DVDdrive {
private:
    char manufacturer[20];
    char interfce[20];
    char speed_formula[20];
public:
    DVDdrive(const char* manu, const char* inte, const char* sf) {
        strcmp(manufacturer, manu);
        strcmp(interfce, inte);
        strcmp(speed_formula, sf);
    }
    void show_DVDdrive(void);
};
void DVDdrive::show_DVDdrive(void) {
    cout << "Производитель -->> " << manufacturer << endl;
    cout << "Интерфейс -->> " << interfce << endl;
    cout << "Скоростная формула -->> " << speed_formula << endl;
}

// это тоже мой класс
class videocard {
private:
    int GPU;
    int MemorySize;
    char CoolingSystem[20];
public:
    videocard(int g, int ms, const char* cs) {
        GPU = g;
        MemorySize = ms;
        strcpy(CoolingSystem, cs);
    }
    void show_videocard(void);
};
void videocard::show_videocard(void) {
    cout << "Частота GPU -->> " << GPU << endl;
    cout << "Система охлаждения -->> " << CoolingSystem << endl;
    cout << "Объем памяти -->> " << MemorySize << " Гб" << endl;
}

class screen {
public:
    screen(const char* t, long c, int x, int y) { //
        strcpy(type, t);
        colors = c;
        x_resolution = x;
        y_resolution = y;
    }
    void show_screen(void);
private:
    char type[30];
    long colors;
    int x_resolution;
    int y_resolution;
};
void screen::show_screen(void) {
    cout << "Тип экрана: " << type << endl;
    cout << "Количество цветов: " << colors << endl;
    cout << "Распределительная способность: " << x_resolution << " x " << y_resolution << " y " << endl;
}

class mother_board {
public:
    mother_board(int p, int s, int r) {
        processor = p;
        speed = s;
        RAM = r;
    }
    void show_mother_board();
private:
    int processor;
    int speed;
    int RAM;
};
void mother_board::show_mother_board(void) {
    cout << "Процессор: " << processor << endl;
    cout << "Частота: " << speed << endl;
    cout << "ОЗУ: " << RAM << " Мб" << endl;
}

class computer : public screen, public mother_board, public videocard, public DVDdrive {
public:
    computer(const char* n, int h, float f, const char* s, long c, int x, int y, int p, int sp, int r, int g, int ms, const char* cs, const char* manu, const char* inte, const char* sf) : screen(s, c, x, y), mother_board(p, sp, r), videocard(g, ms, cs), DVDdrive(manu, inte, sf) {
        strcpy(name, n);
        hard_disc = h;
        floppy = f;
    }
    void show_computer(void);
private:
    char name[50];
    int hard_disc;
    float floppy;
};
void computer::show_computer(void) {
    cout << "Тип компьютера: " << name << endl;
    cout << "Жесткий диск: " << hard_disc << " Мб" << endl;
    cout << "Дискета: " << floppy << " Мб" << endl;
    show_mother_board();
    show_screen();
    cout << "\nИнформация, которую я добавляю в класс computer (методичка) со своего класса videocard::::\n";
    show_videocard();
    cout << "\nИнформация, которую я добавляю в класс computer (методичка) со своего класса DVDdrive::::\n";
    show_DVDdrive();
}

int main()
{
    setlocale(0, "");
    computer pc("Sony", 1024, 1.44, "SVGA", 64000000, 780, 1024, 686, 66, 1024, 255, 8, "активная", "LG", "USB 2.0", "24x/24x/24x");

    pc.show_computer();
    return 0;
}


text:
Q: Windows Phone Web Exception 404 not found but server gets requests As the title says I am trying to run a Windows Phone App which is supposed to communicate with a Restful API(running on localhost). My server is actually getting my Http requests but Visual Studio keeps throwing this error:
"The remote server returned an error: NotFound."
    private void connect_tap(object sender, System.Windows.Input.GestureEventArgs e)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.BeginGetResponse(GetResponseCallback, request);
    }

    void GetResponseCallback(IAsyncResult result)
    {
        HttpWebRequest request = result.AsyncState as HttpWebRequest;
        if (request != null)
        {

                WebResponse response = request.EndGetResponse(result);
                Stream streamResponse = response.GetResponseStream();

                StreamReader streamRead = new StreamReader(streamResponse);
                string read = streamRead.ReadToEnd();

                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show(read);
                    NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
                });

                streamResponse.Close();
                streamRead.Close();
                response.Close();
        }
    }

This is the full error:

{System.Net.WebException: The remote server returned an error: NotFound. ---> System.Net.WebException: The remote server returned an error: NotFound.
     at System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
     at System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClasse.b__d(Object sendState)
     at System.Net.Browser.AsyncHelper.<>c__DisplayClass1.b__0(Object sendState)
     --- End of inner exception stack trace ---
     at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
     at System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
     at IonisSphere.Connect.GetResponseCallback(IAsyncResult result)
     at System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClass1d.b__1b(Object state2)}

The Web Exception occurs at the EndGetResponse() call. I removed the try/catch around to see the error but when it's there it always goes in the catch section and nothing happens.
I don't understand what is it not finding since my server gets my requests ...
It works fine with Postman by the way. I also tried with a POST method but got exactly the same result.
I'm stuck with this since a few days and I couldn't find anyhing helpful on the internet. I am quite new on Windows Phone and I know this is propably a stupid mistake but thanks in advance for the ones who will try to teach me =)


text:
Q: Does $K^{1/2} (t,s)$ inherit the continuity of $K(t,s)$? Assume that $K(t,s)$ is a (1) symmetric, (2) continuous, and (3) positive definite kernel on $[0,1] \times [0,1]$. The spectral decomposition of $K(t,s)$ is:
$$
K (t,s) = \sum_{i=1}^\infty \lambda_i \phi_i (t) \phi_i (s)
$$
with $\{ \phi_i (t): i \in \mathbb{N}\}$ orthonormal and $\lambda_1 > \lambda_2 > \cdots > 0$. Then define
$$
K^{1/2} (t,s) = \sum_{i=1}^\infty \sqrt{\lambda_i} \phi_i (t) \phi_i (s) .
$$
$K(t,s)$ is continuous on $[0,1] \times [0,1]$, is $K^{1/2} (t,s)$ also continuous? Furthermore, if $K \in C^{k}([0,1]^2)$ for some known $k \geq 1$, can we say something about $K^{1/2}$, for example, does $K^{1/2} \in C^{r}([0,1]^2)$ for some $r$ related to $k$?

A: No.
For example, the Green function for $-\Delta$ (the 1-D Laplace operator) in the interval $(0, 1)$ with Dirichlet boundary condition is continuous (it is $\min(x (1 - y), (1 - x) y)$), but the Green function for the square root of this operator is unbounded: it has logarithmic singularity near the diagonal. This follows, for example, from formula (2.4) in this paper by R. Song and Z. Vondraček. (For further information, see here).


text:
Q: How to fetch imagesfrom json and place it in carousel? Flutter I am fetching all the details from a json file but unable to parse the images object and place it in a carousel slider.
This is my json response
{
    "status": true,
    "record": [
        {
            "adid": "44",
            "adsubcatid": "5",
            "aduserid": "37",
            "adname": "vhvhvuf",
            "adcoverimg": "http://codecell.in/girrivi/assets/adcover/scaled_image_picker4508569292934546411.jpg",
            "addesc": "vhvyv",
            "ads_price": "9090",
            "ads_location": "Bengaluru",
            "created_date": "23/10/2020",
            "user_name": "nife",
            "images": "http://codecell.in/girrivi/assets/adimgs/scaled_image_picker4508569292934546411.jpg,http://codecell.in/girrivi/assets/adimgs/scaled_image_picker45085692929345464111.jpg"
        }
    ]
}

And i need to parse this images object.
"images": "http://codecell.in/girrivi/assets/adimgs/scaled_image_picker4508569292934546411.jpg,http://codecell.in/girrivi/assets/adimgs/scaled_image_picker45085692929345464111.jpg"

This is how i'm fetching the json
String images;
Future<String> getProductDetails() async {
    String productDetailsUrl = Constant.productDetailsUrl+widget.id;
    Map<String, String> headers = {'Content-Type' : 'application/json'};

    final response = await http.get(productDetailsUrl, headers: headers);
    if(response.statusCode == 200){
      jsonResponse = json.decode(response.body);
      setState(() {
        price = jsonResponse['record'][0]['ads_price'];
        title = jsonResponse['record'][0]['adname'];
        description = jsonResponse['record'][0]['addesc'];
        location = jsonResponse['record'][0]['ads_location'];
        publishedOn = jsonResponse['record'][0]['created_date'];
        postedBy = jsonResponse['record'][0]['user_name'];
        adId = jsonResponse['record'][0]['adid'];
        postedById = jsonResponse['record'][0]['aduserid'];
        images = jsonResponse['record'][0]['images'];
      });
    }
  }

And this is how I'm placing the images in carousel
Carousel(
                  images: [
                    NetworkImage(images == null
                        ? "https://upload.wikimedia.org/wikipedia/commons/thumb/a/ac/No_image_available.svg/600px-No_image_available.svg.png"
                        : carImg)
                  ],
                  dotSize: 4.0,
                  dotSpacing: 15.0,
                  dotColor: Colors.lightGreenAccent,
                  indicatorBgPadding: 5.0,
                  borderRadius: true,
                  moveIndicatorFromBottom: 180.0,
                  noRadiusForIndicator: true,
                )

A: You can use for..in function when you want to apply a List:
images: [
  for(var img in carImg)
    return NetworkImage(images == null
       ? "https://upload.wikimedia.org/wikipedia/commons/thumb/a/ac/No_image_available.svg/600px-No_image_available.svg.png"
       : img);
]

A: I think you could something like this,
images: images == null  ?
           [ NetworkImage("LOADING IMAGE HERE") ] :
           images.split(',').map((e) =>
                                   NetworkImage(e)
                                   ).toList();

Refer: https://api.flutter.dev/flutter/dart-core/String/split.html


text:
Q: Retrieving more than 100 tweets from twitter API using nodejs I'm trying to retrieve more than 100 tweets from Twitter in nodejs. however, I keep getting an empty array. I tried this way:
const MAX_TWEETS = 200;
const TWEETS_PER_REQUEST = 100;

async function retrieveTweets(T,parameters,tweets_data,request_num){
    T.get('search/tweets', parameters, function (error, data){
        let lowest_id = null;
        let tweets = data.statuses;
        for(var i=0;i<tweets.length; i++){
            tweets_data[request_num*TWEETS_PER_REQUEST+i] = tweets[i].text;
            if(!lowest_id || lowest_id>tweets[i].id){
                lowest_id = tweets[i].id;
            }
        }
        parameters.max_id = lowest_id;
    });
}

async function twitter(){
    var config = require('./config.js');
    var Twit = require('twit');
    var T = new Twit(config);

    var parameters = { q: 'obama', count: TWEETS_PER_REQUEST, result_type: 'recent' };
    var tweets_data= new Array(MAX_TWEETS);
    await retrieveTweets(T,parameters,tweets_data,0);
    await retrieveTweets(T,parameters,tweets_data,1);
    console.log(tweets_data);
}

twitter();

and I have no idea why I keep getting an empty array. Any help would be much appreciated.
edit: I do get results from the get request but when I try to save them in the tweets_data array, I get an empty array and the results don't end up saving.

A: You're not handling the promises correctly.
The get request can return a promise, so instead of using async change the function to
function retrieveTweets(T,parameters){
    return T.get('search/tweets', parameters);
}

then in the twitter function
await retrieveTweets(T,parameters).then(data => {
 // do stuff with result
}.catch(error => {
 // do stuff with the error
}.finally(() => {
 // finish up
}


text:
Q: Get Input value from Inputbox inside ASP Gridview I have a gridview with 3 templatefield columns. When the gridview is databound, an input text box is generated in the template fields where the placeholders are.
The question is, is it possible to get the values from the input boxes in the code-behind file on post back? Or does it need to be done client side with js?
This is a slimmed down version of the gridview:
<asp:GridView ID="GV" runat="server"
    AutoGenerateColumns="False" CellPadding="3"
    DataSourceID="DS" Font-Size="X-Small" Width="100%" BackColor="White" CellSpacing="1"
    BorderColor="#333333" BorderStyle="Inset" BorderWidth="1px"
    ShowFooter="True" ondatabound="GV_DataBound"
    <AlternatingRowStyle BackColor="White" />
    <Columns>
        <asp:TemplateField>
            <HeaderTemplate>
            </HeaderTemplate>
        </asp:TemplateField>
        <asp:BoundField DataField="SKILL" HeaderText="Skill" HtmlEncode="False" SortExpression="SKILL">
        </asp:BoundField>
        <asp:BoundField DataField="COMP_GEN" HeaderText="Competencies (General)" HtmlEncode="False"
            SortExpression="COMP_GEN">
        </asp:BoundField>
        <asp:TemplateField HeaderText="Designer Score">
            <ItemTemplate>
                <asp:PlaceHolder runat='server' ID="devGenDesScore"></asp:PlaceHolder>
            </ItemTemplate>
            <FooterTemplate>
                <asp:TextBox ID="devGenDesScoreTotal_txt" name="inputs" runat="server" Width="50px"></asp:TextBox>
            </FooterTemplate>
        </asp:TemplateField>
    </Columns>
    <FooterStyle BackColor="#C6C3C6" ForeColor="Black" />
    <HeaderStyle BackColor="#005293" Font-Bold="True" ForeColor="white" BorderColor="Gray"
        BorderStyle="Solid" BorderWidth="1px" />
    <PagerStyle BackColor="#C6C3C6" ForeColor="Black" HorizontalAlign="Right" />
    <RowStyle BackColor="White" ForeColor="#253E51" />
    <SelectedRowStyle BackColor="#9471DE" Font-Bold="True" ForeColor="White" />
    <SortedAscendingCellStyle BackColor="#F1F1F1" />
    <SortedAscendingHeaderStyle BackColor="#594B9C" />
    <SortedDescendingCellStyle BackColor="#CAC9C9" />
    <SortedDescendingHeaderStyle BackColor="#33276A" />
</asp:GridView>

I've tried variations of this but can't get it to work:
TextBox compGenDesScoreTxt = GV.Rows[i].Cells[3].Controls[0] as TextBox;
int compGenDesScore = Convert.ToInt32(compGenDesScoreTxt.Text);

It throws this error on the int compGenDesScore = Convert.... line:
System.NullReferenceException: Object reference not set to an instance of an object.
This is how I generate the inputBoxes:
protected void GV_DataBound(object sender, EventArgs e)
{
    int c = GV.Columns.Count;
    int r = GV.Rows.Count;
    //Loop through each row
    for (int i = 0; i < r; i++)
    {
        //Loop through each column on that row
        for (int j = 0; j < c; j++)
        {
            //First competancy
            if (j == 2)
            {
                //Read the contents of the cell, if its blank, do nothing. If it has text, add a textbox for the score
                contents = GV.Rows[i].Cells[j].Text;
                if (contents != " ")
                {
                    PlaceHolder placeHolder = GV.Rows[i].FindControl("devGenDesScore") as PlaceHolder;
                    TextBox devGenDesScore_txt = new TextBox();
                    devGenDesScore_txt.ID = "devGenDesScore_txt";
                    devGenDesScore_txt.Style.Add("width", "50px");
                    placeHolder.Controls.Add(devGenDesScore_txt);
                }
            }
        }
    }
}

A: Have you tried this?
TextBox compGenDesScoreTxt = GV.Rows[i].Cells[3].FindControl("controlID");

A: Figured it out. It was to do with the databinding of the GV. I was using placeholders and then replacing them with input fields where needed. Instead of that, I put the input text fields straight into the template field in aspx page and set the visibility to false. Then, on the databind event I set the fields I needed to appear to true.
May help someone in the future.


text:
Q: Android centered box I have this custom view that should display a centered box in the page, with different resolutions and displays.
(i removed all the code relative to the text, etc):
public class CustomView extends View {

    public CustomView(Context context, AttributeSet attrs) {

        super(context, attrs);
    }

    @Override
    protected void onDraw(Canvas canvas) {

        Paint x = new Paint();
        x.setColor(Color.BLUE);

        Resources r = getResources();

        //dimension of display
         int displayW = r.getDisplayMetrics().widthPixels;
         int displayH = r.getDisplayMetrics().heightPixels;

         //
         int boxW = 200;
         int boxH = 300;

         //actual box dimensions
         float boxEffettivaW = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, boxW, r.getDisplayMetrics());
         float boxEffettivaH = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, boxH, r.getDisplayMetrics());

         float left = (displayW-boxEffettivaW) / 2;
         float top = (displayH-boxEffettivaH) / 2;
         float right = left + boxEffettivaW;
         float bottom = top + boxEffettivaH;

        RectF boxf = new RectF();
        boxf.set(left,top,right,bottom);
        canvas.drawRect(boxf, x);

    }

}

My issue is that the box is not centered, because of the android application title bar, and because of the notify bar. screenshot
So, how can i center my box?
I'd need to know the size of the actual app-dedicated display area, not the global display size...


text:
Q: Icons in the Text Field doesn't work Flutter Prefix and suffix icons in the Text field doesn't work.
Only an X inside a box is shown.
Icons work everywhere else.

I have imported the Cupertino package also:
import 'package:flutter/cupertino.dart';

Version:
cupertino_icons: ^1.0.3

My Code:
Container(
    height: 55.0,
    child:
    TextField(
        decoration: new InputDecoration(
            prefixIcon: new Icon(Icons.search),
            fillColor: Color(0xFFEEEEEE),
            filled: true,
            contentPadding: EdgeInsets.fromLTRB(0.0, 10.0, 0.0, 0.0),
            hintText: 'Search',
            border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(30.0),
            ),
        ),
    ),
),

I don't get any errors also.

A: For it looks like you are using the wrong Icons library. Maybe you could check to use CupertinoIcons instead of Icons.
If I am correct the Icons is material, and the CupertinoIcons is from iOS.
https://github.com/flutter/flutter/issues/73243
See the code of this issue.


text:
Q: Grails, executing a javascript by clicking on a column in a table row I have a view consisting of two lists: products and offers. You can select several rows by checking checkboxes on them and then by clicking on a link, offer lines will be created for each selected product.
Every offer line has the id of the product which I will use to list all offers created for that product in a list below the list of products.
I tried to solve that by using a javascript which should be activated when you click on a link or field in the product list.
The script sends a message to the controller that creates the list of offers for this product and then render a template in this view.
I can just use a link and call the controller and the template will be rendered but of course not the rest of the view.
So I need to have line:
<g:link action="listOffers" id="${pb.id}">${pb.volumeOffered}</g:link>

replaced with something better that can call my javascript-function.
I read somewhere you could put an -onclick="javascript-function" in the g:link tag but it doesn't work.
Below is the most important part of controller and gsp in this case.
In the List.gsp:

.....
.....
    <g:render template="ListOffers" model="[offerDetails:offerDetails]"/>

In the template _AvailableProductData.gsp:
    <g:each in="${prodBuffer}" status="i" var="pb">

                ${pb.volumeOffered}

In the template _ListOffers.gsp:

    <g:set var="entityName" value='Offers' />

<g:message code="default.list.label" args="[entityName]" />

                    <g:sortableColumn property="product" title='Product' />
                    <g:sortableColumn property="volumeOffered" title='Volume' />

                <g:each in="${offerDetails}" status="i" var="od">

                        <g:link class="edit" action="edit" resource="offerDetail" id="${od?.id}"> ${od.product?.encodeAsHTML()}</g:link>
                        ${od?.volumeOffered}

                </g:each>

            <g:paginate total="${offersCount ?: 0}" />

In the controller:
def listOffers(){
    def List<OfferDetail> offerDetails = getOfferList()
    render(template:"ListOffers", model:[offerDetails: offerDetails])
}

Added a printout to see what params contains:
def listOffers(){
    System.out.println("#--#"+params)
    def List<OfferDetail> offerDetails = getOfferList()
    render(template:"ListOffers", model:[offerDetails: offerDetails])
}

The printout is:
#--#[undefined:, controller:ordersAndStore, format:null, action:listOffers]

Following is the complete javascript section, the first one is working good but then comes the onclick version that responds and calls the controller but can not send the id. Then comes your version and another one simple but no one is working.

And the gsp-part in the template:
        <g:each in="${prodBuffer}" status="i" var="pb">

                <g:checkBox name="toOffer" value="${pb.id}" checked="false"  />
                <g:link action="edit_prodbuffer" id="${pb.id}">${pb.id}</g:link>
                ${pb.sawMill}
                ${pb.product}
                ${pb.length}
                ${pb.volumeAvailable}
                 ${pb.volumeOffered}

==================================================
I have taken an old test project which I cleaned and modified to this simple example that still don't work:
<!DOCTYPE html>

        <meta name="layout" content="main" />
        <g:set var="entityName" value="${message(code: 'author.label', default: 'Author')}" />
        <title><g:message code="default.list.label" args="[entityName]" /></title>

        <g:message code="default.link.skip.label" default="Skip to content…"/>

<g:message code="default.home.label"/>

<g:link class="create" action="create"><g:message code="default.new.label" args="[entityName]" /></g:link>

<g:message code="default.list.label" args="[entityName]" />

            <g:if test="${flash.message}">

${flash.message}

            </g:if>

                <tbody
                    <g:each in="${authorList}" status='i' var='a'>

                            <g:field  type="text" name="author" value="${a?.name}"/>

                    </g:each>

                <g:paginate total="${authorCount ?: 0}" />

I begin to be desperate, can't make this work but I must :(
I'll list the code again with some different settings and the output.
Sure something must be wrong with my code as others can make it work but what is wrong?
Part of the GSP-file where things start, there is two alternative lines one is commented here.
                <g:each in="${authorList}" status='i' var='a'>

                        <g:field  type="text" name="author" value="${a?.name}"/>

                </g:each>

-- Controller:
def listOffers() {
    System.out.println("### --- HEJ --- ### "+params)
}

-- Script A:
    function listOffers(id){
            alert('HEJ<<<<<<<<<<<<<<'+ id);
            $.ajax({
                url:'${g.createLink( controller:'author', action:'listOffers', id:"${id}" )}',
                data: [id],
                type: 'get'
            }).success( function ( data ) { $( '#offerList' ).html( data ); });
        }

-- Script B:
        $( document ).ready( function() {
            $(".off1").click( function(event){
                alert('HEJ');
            });
        });

Script B: never respond - WHY?
Output from controller using script A:
### --- HEJ --- ### [undefined:, controller:author, format:null, action:listOffers, id:null]

Modified script A -- data is empty:
        function listOffers(id){
            alert('HEJ<<<<<<<<<<<<<<'+ id);
            $.ajax({
                url:'${g.createLink( controller:'author', action:'listOffers', id:"${id}" )}',
                data: [],
                type: 'get'
            }).success( function ( data ) { $( '#offerList' ).html( data ); });
        }

Output from controller using modified version of script A:
### --- HEJ --- ### [controller:author, format:null, action:listOffers, id:null]

The alert call works ok and I get the correct value of id there.
As yo can see from the controller printout id is null and if data contains id I also get 'undefined:' as a parameter.
If I remove id from data, now data[], this 'undefined:' disappear

A: You need to change your  element like this
${pb.volumeOffered}

and Jquery function which accept id.

A: You could give each table row the ID then respond to events when the row is clicked:
Breaking this down to a simple example with JUST the parts to show how it works.
OrdersAndStoreController
class OrdersAndStoreController {

    def index() {
        [prodBuffer: [new ProdBuffer(id: 1, volumeOffered: 100), new ProdBuffer(id: 2, volumeOffered: 200)]]
    }

    def listOffers() {
        render(template:"ListOffers", model:[offerDetails: [offer1: 'offer1', offer2: 'offer2']])
    }
}

class ProdBuffer{
    Integer id
    Integer volumeOffered
}

index.gsp
<!DOCTYPE html>

<meta name="layout" content="main" />

    Volume offered

    <g:each in="${prodBuffer}" status="i" var="pb">

            ${pb.volumeOffered}

    </g:each>

_ListOffers.gsp
${offerDetails}

A: The problem was in 2 points.
First: In main.gsp I moved the string:
<asset:javascript src="application.js"/>

from the end of the file up to the head close to the css-loading.
This made the script to respond.
But then I couldn't get the data from "id" go in to params.
but by rewriting the row:
data:[this.id] to data:{id: this.id}

it worked.


text:
Q: Issue using awaitable and self made async method Why does a method returning a Task does not get executed when returning it's instance. I thought this must happen, because awaiting the method/delegate would
put it into some queue and later execute the resulting task.
So why does this Task never gets executed when calling Do()?
public void Do()
{
    SomeTask().Wait()
}

public async Task SomeTask()
{
    return new Task(() => { Console.WriteLine("Hello World!") });
}

EDIT
Or do I alwas need await Task.Run(...)?
Thank you very much!

A: You're creating a Task but never starting it, so it's impossible for it to complete.
Use Task.Run to return a "hot" (started) Task instead:
return Task.Run(() => { Console.WriteLine("Hello World!") });

Also, async keyword is unnecessary as you're not awaiting the created task.


text:
Q: VS Code Python doesn't recognize match statement When I use a match-case statement in Python in VS Code, it gives red squiggly lines and errors in the "problems" tab:

A: I got a response from one of the vscode-python devs on GitHub:

Unfortunately Jedi (and it's underlying parser, parso) has not added support for the match statement yet. Please consider switching your language server to "Default"/"Pylance" as our Pylance language server already has support.

As soon as Jedi makes a new release with match statement support we will take the update, but otherwise this is out of our hands. Since we have a language server that has support I'm a closing this issue.


text:
Q: Stripe: Use Coupons with price_id in Checkout I have a Price and a Coupon setup in Stripe.
I have tried to create both a 100% off Coupon (% based) or a 10 euro off Coupon (fixed amount).
I create a Checkout session using:
stripe.checkout.Session.create(
        success_url="https://www.google.com",
        cancel_url="https://www.google.com",

        payment_method_types=["card", "ideal"],
        line_items=[
            {
                "price": "price_12344",
                "quantity": 1
            }
        ],
        mode="payment",
        customer=customer_id,
        discounts=[{
            "coupon": "cZLa83ZZ"
        }]

but I get
Request req_7X46MB0ywlVtI2: The Checkout Session's total amount due cannot be zero in `payment` mode

however if I remove the discounts entry in the checkout session creation, this code works and successfully creates the Session.
I believe there is something wrong with the way I am using Prices, Checkout and Coupons. Any idea?


text:
Q: Query for instance_name, port number in format in SQL Server I need result in below format, with current connection port. Can someone help me?
servername\instance,3000

Thanks

A: The following shows you code you can run as c# Console app to get what you want.  If you are already in SQL Management Studio, then you just need to execute the commands directly:
static void Main(string[] args)
{
    using (var conn = new SqlConnection("Integrated Security=true; Initial Catalog=dbname;Data Source=servername"))
    {
        using (var cmd = new SqlCommand("SELECT SERVERPROPERTY('ServerName'), SERVERPROPERTY('InstanceName')", conn))
        {
            string serverName = "";
            string instanceName = "";
            cmd.CommandType = System.Data.CommandType.Text;
            conn.Open();
            var rdr = cmd.ExecuteReader();
            if (rdr.Read())
            {
                serverName = rdr.GetString(0);
                if (!rdr.IsDBNull(1))
                {
                    instanceName = rdr.GetString(1);
                }
            }
            rdr.Close();
            Console.WriteLine("Server name of this connection is: " + serverName + ".  Instance of this connection is: " + instanceName);
        }
        using (var cmd = new SqlCommand("xp_readerrorlog", conn))
        {
            cmd.CommandType = System.Data.CommandType.StoredProcedure;

            var param = cmd.CreateParameter();
            param.ParameterName = "@ArchiveID";
            param.DbType = System.Data.DbType.Int32;
            param.Value = 0;
            cmd.Parameters.Add(param);

            param = cmd.CreateParameter();
            param.ParameterName = "@LogType";
            param.DbType = System.Data.DbType.Int32;
            param.Value = 1;
            cmd.Parameters.Add(param);

            param = cmd.CreateParameter();
            param.ParameterName = "@Filter1Text";
            param.DbType = System.Data.DbType.String;
            param.Value = "Server is listening on";
            cmd.Parameters.Add(param);

            var rdr = cmd.ExecuteReader();
            while (rdr.Read())
            {
                Console.WriteLine(rdr.GetString(2));
            }
            rdr.Close();
        }
    }
    Console.ReadKey();
}

Note that if your server is using default instance (as mine does) then instance name is NULL.


text:
Q: PID re-use, edge case? I read that PID reuse is done when process is zombie and was waited for.
What happens if I forked hundreds of processes and just killed the parent without waiting for them? I know they will be children of init process but who will call wait on them? (else we are in trouble and limited with PIDs).

A:
I know they will be children of init process but who will call wait on them?

init (process with PID 1) will reap all of its child processes, including adpoted zombie processes. As it says on https://en.wikipedia.org/wiki/Zombie_process

init periodically executes the wait system call to reap any zombies
with init as parent.


text:
Q: how to change retake and use photo buttons of UIImagePickerController with images Am using camera in my app by using UIImagePickerController.I want to change the default Retake and UsePhoto buttons with images.How do i need to proceed to implement this.

A: You can create your custom view with the buttons you want to show. When you create UIImagePickerController just set the following:
picker = [[UIImagePickerController alloc] init];
picker.showsCameraControls = NO;

self.overlayView = [[[NSBundle mainBundle] loadNibNamed:@"OverlayView" owner:self options:nil] objectAtIndex:0];
self.overlayView.frame = picker.cameraOverlayView.frame;

picker.cameraOverlayView = self.overlayView; //Overlay View will be your custom view.
[self presentViewController:picker animated:YES completion:nil];


text:
Q: angular-moment TypeError: momentValue.toISOString is not a function getting the following error using the angular-moment meteor package
angular.js:12332 TypeError: momentValue.toISOString is not a function
    at updateMoment (angular-moment.js:199)
    at Object.fn (angular-moment.js:215)
    at Scope.$get.Scope.$digest (angular.js:15685)
    at Scope.$get.Scope.$apply (angular.js:15953)
    at angular-meteor-meteorCollection.js:160
    at angular.js:17711
    at completeOutstandingRequest (angular.js:5396)
    at angular.js:5668

I am using the amTimeAgo directive in a single place:

Here is my packages file:
# Meteor packages used by this project, one per line.
# Check this file (and the other files in this directory) into your repository.
#
# 'meteor add' and 'meteor remove' will edit this file for you,
# but you can also edit it by hand.

meteor-platform
accounts-ui
accounts-password
fourseven:scss
urigo:angular@=0.9.2
angular:angular
angularui:angular-ui-router
angular:angular-material
angular:angular-mocks
angular:angular-animate
angular:angular-touch
angular:angular-sanitize
angular:angular-cookies
angular:angular-server
tonekk:angular-moment

And my versions file:
accounts-base@1.2.0
accounts-password@1.1.1
accounts-ui@1.1.5
accounts-ui-unstyled@1.1.7
angular:angular@1.4.2
angular:angular-animate@1.4.2
angular:angular-aria@1.4.2
angular:angular-cookies@1.4.2
angular:angular-material@0.10.0
angular:angular-mocks@1.4.2
angular:angular-sanitize@1.4.2
angular:angular-server@1.4.0
angular:angular-touch@1.4.2
angularui:angular-ui-router@0.2.15
autoupdate@1.2.1
base64@1.0.3
binary-heap@1.0.3
blaze@2.1.2
blaze-tools@1.0.3
boilerplate-generator@1.0.3
callback-hook@1.0.3
check@1.0.5
dburles:mongo-collection-instances@0.3.4
ddp@1.1.0
deps@1.0.7
ejson@1.0.6
email@1.0.6
fastclick@1.0.3
fourseven:scss@3.2.0
geojson-utils@1.0.3
html-tools@1.0.4
htmljs@1.0.4
http@1.1.0
id-map@1.0.3
jquery@1.11.3_2
json@1.0.3
lai:collection-extensions@0.1.4
launch-screen@1.0.2
less@1.0.14
livedata@1.0.13
localstorage@1.0.3
logging@1.0.7
meteor@1.1.6
meteor-platform@1.2.2
minifiers@1.1.5
minimongo@1.0.8
mobile-status-bar@1.0.3
mongo@1.1.0
mrt:moment@1.7.0
npm-bcrypt@0.7.8_2
observe-sequence@1.0.6
ordered-dict@1.0.3
random@1.0.3
reactive-dict@1.1.0
reactive-var@1.0.5
reload@1.1.3
retry@1.0.3
routepolicy@1.0.5
service-configuration@1.0.4
session@1.1.0
sha@1.0.3
spacebars@1.0.6
spacebars-compiler@1.0.6
srp@1.0.3
templating@1.1.1
tonekk:angular-moment@1.0.2
tracker@1.0.7
ui@1.0.6
underscore@1.0.3
urigo:angular@0.9.2
url@1.0.4
webapp@1.2.0
webapp-hashing@1.0.3

Any idea why this might be happening?

A: jason's own answer provided here worked for me except it wasnt ...:angular-meteor it was
meteor add jasonaibrahim:angular-moment

after first doing a
meteor remove tonekk:angular-moment

A: Turns out the meteor package I was using (tonekk:angular-moment) was using an out of date version of angular-moment.
I solved this by creating my own meteor package using the most up to date version of angular meteor.
meteor add jasonaibrahim:angular-moment


text:
Q: Calculating fitness in Knapsack problem in Jenetics I am trying to understand how evolution and fitness function work. I implemented my own Knapsack problem, which tries to find 3 most valuable items from a given set. It is my own cost function:
  static int counter=1;
    static double MyCostFunction(boolean[] chromosome, double[] data){
        System.out.println("COST FUNCTION: "+counter++);
        double sum = 0;
        int count = 0;
        for (int i =0; i<chromosome.length; i++){
            if (chromosome[i]){
                sum += data[i];
                count ++;
            }
        }
        return  count<=3 ? sum : 0;
    }

I'm printing out just to see how many times MyCostFunction is performed.
Right now I am working with a small set of 8 items. Here it is:
public static void main(String[] args) {
        double[] data = {-15,-7, -1, -1,7,100,200,300};
        Integer[] items = new Integer[data.length];
        int i = 0;
        for (double d : data){
            items[i] = i;
            i++;
        }

        ISeq<Integer> zbiorDlaGA = ISeq.of(items);

        final ISProblem knapsack= new ISProblem(zbiorDlaGA,
                chromosome -> ISProblem.MyCostFunction(  chromosome,  data)
        );

This is the Engine that I'm using:
final Engine<BitGene,Double> engine= Engine.builder(knapsack)
                .executor( Runnable::run)
                .populationSize(5)
                .survivorsSelector(new TournamentSelector<>(3))
                .offspringSelector(new RouletteWheelSelector<>())
                .alterers(
                        new Mutator<>(1.0),
                        new SinglePointCrossover<>(0.0)
                ).build();

And that's how I'm obtaining statistics:
 final EvolutionStatistics<Double,?> statistics=EvolutionStatistics.ofNumber();

        final  Phenotype<BitGene,Double> best=engine.stream()
               // .limit(bySteadyFitness(15))
                .limit(5)
                .peek(r-> System.out.println("########CURRENT GEN: "
                        +r.generation()+
                        ": "+ r.totalGenerations()+
                        ": "+r.bestPhenotype()+
                        " ALTERED: "+r.alterCount()+
                        " INVALID: "+r.invalidCount()+
                        " GENOTYPE: "+r.genotypes()))
                .peek(statistics)
                .collect(toBestPhenotype());

        System.out.println(statistics);
        System.out.println(best);

I've got a few questions concerning some behaviours of your library that I don't really understand:
Even when I set mutation probability to 1.0 (it should change every bit, I think so) it gives me this result:
COST FUNCTION: 1
COST FUNCTION: 2
COST FUNCTION: 3
COST FUNCTION: 4
COST FUNCTION: 5
COST FUNCTION: 6
COST FUNCTION: 7
COST FUNCTION: 8
########CURRENT GEN: 1: 1: [01100000] -> 300.0 ALTERED: 24 INVALID: 0 GENOTYPE: [[10110100],[00011011],[01011101],[00111001],[01100000]]
COST FUNCTION: 9
COST FUNCTION: 10
COST FUNCTION: 11
########CURRENT GEN: 2: 2: [00011011] -> 0.0 ALTERED: 24 INVALID: 0 GENOTYPE: [[00011011],[01011101],[10100101],[01111010],[00001011]]
COST FUNCTION: 12
COST FUNCTION: 13
COST FUNCTION: 14
########CURRENT GEN: 3: 3: [10100101] -> 0.0 ALTERED: 24 INVALID: 0 GENOTYPE: [[10100101],[01011101],[01111011],[01010011],[10010101]]
COST FUNCTION: 15
COST FUNCTION: 16
COST FUNCTION: 17
########CURRENT GEN: 4: 4: [10000010] -> 293.0 ALTERED: 24 INVALID: 0 GENOTYPE: [[01011101],[01010011],[01111011],[10000010],[00001001]]
COST FUNCTION: 18
COST FUNCTION: 19
COST FUNCTION: 20
########CURRENT GEN: 5: 5: [10000010] -> 293.0 ALTERED: 24 INVALID: 0 GENOTYPE: [[10000010],[01011101],[01000100],[10111100],[10011001]]
+---------------------------------------------------------------------------+
|  Time statistics                                                          |
+---------------------------------------------------------------------------+
|             Selection: sum=0,003352000000 s; mean=0,000670400000 s        |
|              Altering: sum=0,010647600000 s; mean=0,002129520000 s        |
|   Fitness calculation: sum=0,011403300000 s; mean=0,002280660000 s        |
|     Overall execution: sum=0,033579600000 s; mean=0,006715920000 s        |
+---------------------------------------------------------------------------+
|  Evolution statistics                                                     |
+---------------------------------------------------------------------------+
|           Generations: 5                                                  |
|               Altered: sum=120; mean=24,000000000                         |
|                Killed: sum=0; mean=0,000000000                            |
|              Invalids: sum=0; mean=0,000000000                            |
+---------------------------------------------------------------------------+
|  Population statistics                                                    |
+---------------------------------------------------------------------------+
|                   Age: max=4; mean=0,560000; var=1,090000                 |
|               Fitness:                                                    |
|                      min  = -23,000000000000                              |
|                      max  = 300,000000000000                              |
|                      mean = 41,840000000000                               |
|                      var  = 10763,306666666665                            |
|                      std  = 103,746357365773                              |
+---------------------------------------------------------------------------+
[01100000] -> 300.0

Why does it calculate fitness for three individuals only? Is it somehow caching the values already calculated for the same chromosome?
And why in the first generation it is calculated 8 times?
The number of altered individuals is always 3*8, what implies that only 3 chromosomes were modified during the evolution. Why? I thought it has something to do with TournamentSelector sampleSize, but it doesn't change number of changed chromosomes.
With the probability of mutation equal to 100% and crossover prob.=100% it should change every bit in chromosome, so there will only be 2 versions of chromosome in each generation, but it doesn't work like that. Why? Does it randomly select value of bit or sets the opposite?
Does the number of bits set to true have to be a constant one(or approximately constant) in population/generation?
I am using these strange values for crossover and mutation probabilities, because I was wondering earlier why it didn't give the number of fitness calculations performed equal to populationSize*NumberOfGenerations. So I started to experiment.

A: The described behavior is as expected :)
The following facts leads to the observed outcome:

*

*During the evolution process, the population is divided into offspring and survivors.

*Only the offspring is target for the alterers (mutation operation).

*The default offspring fraction is set to 0.6, which makes an offspring count of 3 for your example.

*The fitness values of unchanged individuals is cached.

The outcome:

*

*The reason for the first five fitness evaluations is induced by the fresh, initial population of 5.

*The next three evaluations are due to the three offspring individuals, which has been mutated with 100% certainty.

*The subsequent evaluation blocks of three evaluations have the same reason.

I think this explains the output, doesn't it?
Control the number of initially set bits
If you want to control the number of initial bits of the BitChromosome, you can use the original Codec to create your own variation.
public static <T> InvertibleCodec<ISeq<T>, BitGene>
ofSubSet(final ISeq<? extends T> basicSet, final double onesProbability) {
    final InvertibleCodec<ISeq<T>, BitGene> codec = Codecs.ofSubSet(basicSet);
    return InvertibleCodec.of(
        Genotype.of(BitChromosome.of(basicSet.length(), onesProbability)),
        codec.decoder(),
        codec.encoder()
    );
}


text:
Q: How to retain Remove Ads in app purchase after app has closed I have successfully removed ads from the app with an in app purchase.
The problem is that if I close the app and reopen. The ads start up again.
I have 2 main scenes. The GameOverScene and the GameScene. The In App Purchase happens in the GameOverScene.
GameOverScene.m :
- (void)OnRemoveADS {
    [self showPurchaseAlert: IAP_Q_RemoveADS  :0];

    g_bRemoveADS = [[NSUserDefaults standardUserDefaults] boolForKey: @"REMOVEADS"];

    // For HZInterstitialAd, HZVideoAd, and HZIncentivizedAd, just check the BOOL to see if an ad should be shown
    if (!g_bRemoveADS) {
        [HZInterstitialAd show];

        [self removeBannerAds];
        [self disableAds];
        NSLog(@"Disable ads is called");
    }
}

- (void)removeBannerAds {
    HZBannerAdOptions *options = [[HZBannerAdOptions alloc] init];

    [HZBannerAd placeBannerInView:self.view
                         position:HZBannerPositionBottom
                          options:options
                          success:^(HZBannerAd *banner) {
                              if (g_bRemoveADS) { // case (2)
                                  // Just discard the banner
                                  [banner setHidden: YES];
                                  [banner removeFromSuperview];
                                  banner = nil;

                                  //_currentBannerAd = banner;

                                  NSLog(@"Banner ad removed!GameOverScene");
                              } else {
                                  // Keep a reference to the current banner ad, so we can remove it from screen later if we want to disable ads.
                                  _currentBannerAd = banner;
                              }
                              NSLog(@"Ad Shown! GameOverScene");
                          }
                          failure:^(NSError *error) {
                              NSLog(@"Error = %@",error);
                          }];
}

- (void)disableAds {
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"REMOVEADS"];
    [_currentBannerAd removeFromSuperview]; // case (3)
}

GameScene.m :
-(id) init {
    if (self = [super init]) {
        if (!g_bRemoveADS) {
            g_bRemoveADS=FALSE;
            [[NSUserDefaults standardUserDefaults] setBool:g_bRemoveADS forKey:@"REMOVEADS"];
            [[NSUserDefaults standardUserDefaults] synchronize];
        } else {
            g_bRemoveADS=TRUE;
            [[NSUserDefaults standardUserDefaults] setBool:g_bRemoveADS forKey:@"REMOVEADS"];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
    }
}

The way I'm trying to solve it is by using the same code from the GameOverScene.m in the AppDelegate.m that way when the app starts up it will remove the ads.
AppDelegate.m :
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    g_bRemoveADS = [[NSUserDefaults standardUserDefaults] boolForKey: @"REMOVEADS"];

    if (!g_bRemoveADS) {

        [HZInterstitialAd show];

        [self disableAds];
        NSLog(@"Disable ads is called");
    }
}

A: Out of my perspective you have one negation to much.
if (!g_bRemoveADS) { should be replaced with if (g_bRemoveADS) { in GameOverScene.m.
if (g_bRemoveADS) {
    [HZInterstitialAd show];

    [self removeBannerAds];
    [self disableAds];
    NSLog(@"Disable ads is called");
}

g_bRemoveADS evaluates to TRUE when the respective user-default is set. When it is set, then you call the removeBannerAds stuff etc. which seems to be the deactivation action.

A: You have to synchronise your NSUserDefaults after changing changing a value in your disableAds method with:
[[NSUserDefaults standardUserDefaults]synchronize];


text:
Q: Absolute div width inside relative div I am having problem with html/css.

*

*I have a container (position: relative;) , in my case it is div.jtk-demo-canvas

*Container has floating divs (position: absolute;) inside, in my case these are div.jtk-window

*floating divs should have (position: absolute;) as it is requirement for js plugin

Requirement:
Floating divs should have min-width of 200 and max-width of 400. I dont want to apply width to it as it should vary between 200-400 to fit its content.
But as You can see in my case last div from right is same as 2nd one but its width is lesser.
How can I Fix this ?
jsfiddle: https://jsfiddle.net/bababalcksheep/wm94sf2b/
Since I have large html code, therefore I am posting fiddle link.

A: because you gave him left:800px; and your body is width: 960px; for that your 3rd div only have 160px place

A: Try display: inline-table and position: relative to div with id 117a13213-102 (Checked in Chrome and Firefox)
FIDDLE
CODE
<div style="left: 800px; top: 105px; display: inline-table; position: relative;" id="117a13213-102" class="flowBox jtk-window">


text:
Q: JPA 2.0 Map two collections of the same type using one @JoinedTable Suppose I have the following entities:
@Entity
@Table(name = "A")
public class A implements Serializable {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Long id;

  @OneToMany
  @JoinTable(name="A_B", joinColumns = @JoinColumn(name = "A_ID"),
    inverseJoinColumns = @JoinColumn(name = "B_ID"))
  private List<B> bList1;

  @OneToMany
  @JoinTable(name="A_B", joinColumns = @JoinColumn(name = "A_ID"),
    inverseJoinColumns = @JoinColumn(name = "B_ID"))
  private List<B> bList2;

  // getters and setters

}

@Entity
@Table(name = "B")
public class B implements Serializable {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Long id;

  //some other data
  //getters and setters
}

And the @JoinTable structure would be somthing like:
A_B (a_id, b_id, discriminator);

Is it possible using some annotation to specify the discriminator column, based on which bList1 and bList2 will be populated?

A: with the code posted it is not possible because even when you could specify @Where("discriminator='list1'") and @Where("discriminator='list2'") on the collections to filter when retrieving, but hibernate still does not maintain the discriminator while insert/update.
you could try to make this work (i havent testet this):
@ManyToAny(metaColumn = @Column( name = "discriminator" ) )
@AnyMetaDef(idType = "long", metaType = "string", metaValues = {
    @MetaValue( value = "list1", targetEntity = B.class ) } )
private List<B> bList1;

@ManyToAny(metaColumn = @Column( name = "discriminator" ) )
@AnyMetaDef(idType = "long", metaType = "string", metaValues = {
    @MetaValue( value = "list2", targetEntity = B.class ) } )
private List<B> bList2;

or you just create a class for the jointable which has a discriminator value and handle it in the properties of list1 and 2.


text:
Q: Use Apache Cordova to develop OS X application I'm wondering, if it's possible to develop an OS X application using Apache Cordova. There is only iOS mentioned on their site. But I'm currently evaluating a possibility to create a cross-platform app for Windows, OS X and than mobile platforms using Visual Studio.
Your suggestion will be highly appreciated.
Thanks

A: Currently, Visual Studio doesn't provide built-in support for Mac OS X development, using Cordova. However, when you use the Visual Studio Tools for Apache Cordova (Visual Studio TACO) you're really working with a standard Apache Cordova project. This means that you could use a project like the following which adds support for Mac OS X as a platform:
https://github.com/apache/cordova-osx
To use this, you'd need to work with the Cordova command line (e.g. npm install -g cordova) tools. You would install these tools, change into the directory for your Cordova project from Visual Studio, and then you should be able to follow the steps on that GitHub repo's readme. There are caveats for now - this solution only supports full-screen "kiosk" apps on Mac OS X, rather than building a fully integrated desktop app with features like a menu bar.


text:
Q: Combining two arrays based on the first item in the array Ok, so I've got two arrays planned - which will be sorted based on a date or timestamp, as so:
array([date] => "8/12/12", [rating] => 300)

and lets say a second array looks like this:
array([date] => "8/12/12", [rating2] => 600)

I want to combine these two as such:
array([date] => "8/12/12", [rating] => 300, [rating2] => 600)

What would be the most effective way to do this?

A: You can use use + sign on the array ...
$a = array("date" => "8/12/12","rating" => 300);
$b = array("date" => "8/12/12","rating2" => 600);
var_dump($a + $b);

Output
array
  'date' => string '8/12/12' (length=7)
  'rating' => int 300
  'rating2' => int 600

A: Experiment with array_merge and the + operator
$a = array( 'key' => 'abc', 'foo' => true);
$b = array( 'key' => 'abc', 'bar' => true);
print_r( $a + $b );
print_r( array_merge( $a, $b ) );


text:
Q: Bluetooth isn't working - fedora 24 I am dealing with a rather strange problem.
I've updated my fedora 24 system and after that my bluetooth Mouse (Microsoft Designers Mouse) stoped working.
Although the device seems connected, it seems that it's not trusted, as you can see bellow
[astamato@pcen35240 ~]$ bluetoothctl
[NEW] Controller E4:B3:18:1E:2D:3B pcen35240 [default]
[NEW] Device E9:A1:2D:11:63:C4 Designer Mouse
[NEW] Primary Service
    /org/bluez/hci0/dev_E9_A1_2D_11_63_C4/service000e
    0000180f-0000-1000-8000-00805f9b34fb
    Battery Service
[NEW] Characteristic
    /org/bluez/hci0/dev_E9_A1_2D_11_63_C4/service000e/char000f
    00002a19-0000-1000-8000-00805f9b34fb
    Battery Level
[NEW] Descriptor
    /org/bluez/hci0/dev_E9_A1_2D_11_63_C4/service000e/char000f/desc0011
    00002902-0000-1000-8000-00805f9b34fb
    Client Characteristic Configuration
[NEW] Primary Service
    /org/bluez/hci0/dev_E9_A1_2D_11_63_C4/service0009
    0000180a-0000-1000-8000-00805f9b34fb
    Device Information
[NEW] Characteristic
    /org/bluez/hci0/dev_E9_A1_2D_11_63_C4/service0009/char000c
    00002a50-0000-1000-8000-00805f9b34fb
    PnP ID
[NEW] Characteristic
    /org/bluez/hci0/dev_E9_A1_2D_11_63_C4/service0009/char000a
    00002a29-0000-1000-8000-00805f9b34fb
    Manufacturer Name String
[NEW] Primary Service
    /org/bluez/hci0/dev_E9_A1_2D_11_63_C4/service0008
    00001801-0000-1000-8000-00805f9b34fb
    Generic Attribute Profile
[Designer Mouse]# info E9:A1:2D:11:63:C4
Device E9:A1:2D:11:63:C4
    Name: Designer Mouse
    Alias: Designer Mouse
    Appearance: 0x03c2
    Icon: input-mouse
    Paired: yes
    Trusted: no
    Blocked: no
    Connected: yes
    LegacyPairing: no
    UUID: Generic Access Profile    (00001800-0000-1000-8000-00805f9b34fb)
    UUID: Generic Attribute Profile (00001801-0000-1000-8000-00805f9b34fb)
    UUID: Device Information        (0000180a-0000-1000-8000-00805f9b34fb)
    UUID: Battery Service           (0000180f-0000-1000-8000-00805f9b34fb)
    UUID: Human Interface Device    (00001812-0000-1000-8000-00805f9b34fb)
    Modalias: usb:v045Ep0805d0110

In the meatime I've managed to make it trusted bu using
trust E9:A1:2D:11:63:C4

but it seems that this is not the problem... So the mouse is connected, it's paired (not always though), it is trusted but it cannot function...
Any idea on how to fix this?

A: I couldn't resolve the issue. What solved it was to upgrade from fedora 24 to fedora 25. I guess it had to do with an update on the bluetooth.