text:
Q: Recursive conditional cumulative products My data is a series of two rates, i.e. percentage changes.  I want to calculate the cumulative product of each, but reset that cumulative product to 1 every time the product for rate A is <= the product for rate B.
I'm currently using a for loop, which works fine.  I'd love a solution using purrr, but the accumulate function is limited to at most 3 arguments for the accumulating function, and I need 4.
Appreciate any suggestions, MRE is below.
library(tidyverse)

set.seed(20191008)

#create our data
df <- tibble(time = 1:100,
             #A and B represent two rates, i.e. percentage change
             A = runif(100) + 0.5,
             B = runif(100) + 0.5,
             #initialize the value of the cumulative products as 1
             CumeProdA = 1,
             CumeProdB = 1)

#Current solution uses a loop, but it's slow with large data
for(i in 2:nrow(df)){
  #If the cumulative product of A <= that of B, then reset it to 1.
  #Otherwise, continue accumulating
  df$CumeProdA[i] <- ifelse(df$CumeProdA[i - 1] * df$A[i] <= df$CumeProdB[i - 1] * df$B[i],
                            1,
                            df$CumeProdA[i - 1] * df$A[i])

  #Ditto with B
  df$CumeProdB[i] <- ifelse(df$CumeProdA[i - 1] * df$A[i] <= df$CumeProdB[i - 1] * df$B[i],
                            1,
                            df$CumeProdB[i - 1] * df$B[i])
}

#I've done similar recursive calculations using purrr::accumulate,
#but it has a limit to how many arguments you can use in a function
df %>%
  mutate(Example = accumulate(A, ~ ifelse(.x * .y < 1, 1, .x * .y)))

#The ultimate goal is to find the greatest difference in the cumulative products.
#If there's a shortcut to get to here, I'll take it!
df %>%
  summarise(min(CumeProdB - CumeProdA))


text:
Q: How to use Material UI in react version 16.5.2 I am trying to use Material UI select in react version 16.5.2 However I am unable to use useState since that hook can only be used by react 16.8.0 and above.
Is there any way to use Material UI select in 16.5.2 without using useState?
import React, { useEffect, useState } from "react";
import { withTaskContext } from "@twilio/flex-ui";
import { selectCurrentEntity } from "../helpers/channelIntegrationFramework";
import "./styles.css";
import TextField from "@material-ui/core/TextField";
import FormControl from "@material-ui/core/FormControl";
import InputLabel from "@material-ui/core/InputLabel";
import MenuItem from "@material-ui/core/MenuItem";

class VoiceCallComponent extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      functionsBaseUrl: this.props.functionsBaseUrl,
      settingsBaseUrl: this.props.settingsBaseUrl,
    };

    this.init();
  }

  init = () => {
    console.log(
      `Connector: -- VoiceCallComponent -- functionsBaseUrl: ${this.state.functionsBaseUrl} -- settingsBaseUrl: ${this.state.settingsBaseUrl}`
    );
  };

  render() {
    console.log("Connector: ====== render ========");
    const [disposition, setDisposition] = useState("");
    console.log("disposition :- ", { disposition });
    const { task } = this.props;
    return (

Notes:

          <TextField
            style={{
              textAlign: "left",
              margin: "0px",
              width: "250px",
              height: "55px",
            }}
            hintText="Message Field"
            floatingLabelText="Note"
            multiline
            rows={2}
            maxRows={5}
            value={this.state.callnotes}
            onChange={this.handleChange}
          />

          Disposition*:

          <FormControl fullWidth>
            <InputLabel id="disposition-label">Disposition*:</InputLabel>
            <select
              labelId="disposition-label"
              id="disposition-select-label"
              value={disposition}
              onChange={handleSelectChange}
              fullWidth
            >
              <MenuItem value={"11"}>Contacted</MenuItem>
              <MenuItem value={"22"}>Bad Number</MenuItem>
              <MenuItem value={"33"}>Hung up on Call</MenuItem>
            </select>
          </FormControl>

);
}
}

export default withTaskContext(VoiceCallComponent);

The above code is throwing error since I am not using react version 16.8.0.

redpajama_set_name: RedPajamaStackExchange


text:
Q: clearTimeout when tool.mouseMove event starts (PaperJs, VueJs) I have a Paper instance with a tool that just draws a path on mouseMove and deletes the segments at the start of that path if the number of segments is greater than 50. Everything works perfect this far. this is the code:
<template>
  <div>
    <canvas id="canvas" resize></canvas>
  </div>
</template>
<script>
import paper from 'paper';

export default {
  name: 'home',
  components: {
  },
  created() {
    paper.install(window);
  },
  mounted() {
    const canvas = this.$el.querySelector('#canvas');
    paper.setup(canvas);
    const path = new Path();
    path.strokeColor = '#f5bb56';
    path.strokeWidth = 2;
    this.tool = new Tool()
    this.tool.onMouseMove = event => {
      if (path.segments.length > 50) {
        path.removeSegment(0)
      };
      path.add(event.point);
      path.smooth({
        type: 'continuous'
      });
    };
    view.draw()
  },
};
</script>
<style lang="scss">
  #canvas {
    width: 100%;
    height: 100%;
  }
</style>

The problem is that now i want to start deleting segments from that path with an interval of 50 miliseconds but stop executing that when a new segment is added. I'm looking for something to set a variable into a timeout(() => {eraseFunction()}), when the event is not fired for about two seconds.
i added a clearTimeout pointing to the variable that contains it at the start of the mouseMove event and setting it at the end, so if there's a timeout running, i remove it when the mouseMove starts:
export default {
  name: 'home',
  components: {
  },
  data() {
    return {
      tool: null,
      path: null,
      erase: null,
    }
  },
  created() {
    paper.install(window);
  },
  mounted() {
    const canvas = this.$el.querySelector('#canvas');
    paper.setup(canvas);
    this.path = new Path();
    this.path.strokeColor = '#f5bb56';
    this.path.strokeWidth = 2;
    this.tool = new Tool()
    this.tool.onMouseMove = event => {
      clearTimeout(this.erase);
      if (this.path.segments.length > 50) {
        this.path.removeSegment(0)
      };
      this.path.add(event.point);
      this.path.smooth({
        type: 'continuous'
      });
      this.erase = setTimeout(() => {
        this.eraseFunction()
      }, 2000);
    };
    view.draw()
  },
  methods: {
    eraseFunction() {
      setInterval(() => {
        this.path.removeSegment(0);
      }, 500);
    }
  }
};
</script>

the problem is that the timeout is not removed and given a certain amount of time, i can´t draw new segments because they´re deleted inmediately.

A: You need to clear setInterval also. You are only clearing setTimeout. setInterval is still running an deleting your segments.

A: ClearInterval need the intervalID you want to clear. The intervalID is given by setInterval call.
You should return the result of setTimout call in eraseFunction:
eraseFunction() {
      return setInterval(() => {
        this.path.removeSegment(0);
      }, 500);
    }

And you should assign to this.erase the result of eraseFunction call, instead of the setTimeout:
setTimeout(() => {
        this.erase = this.eraseFunction()
      }, 2000);


text:
Q: apply k-Nearest Neighbors in dataset in python I have a dataset in CSV file and all data is a numeric attribute, I want to apply k-Nearest Neighbors in my dataset
I have some error in my code I don't know who I can fix it.
code:
[enter image description here][1]
[enter image description here][2]

A: seems like the instance1[x] and instance2[x] where you are applying subtraction is a string type.
You cannot subtract 2 strings, so you can modify your code like,
distance += pow( ( int(instance1[x])-int(instance2[x]) ),2)

This will read the variable as int type, thus you can subtract it.
you can replace int with float double etc also

A: Replace the line defining variable sortedVotes with
sortedVotes = sorted ( classVotes.items(), key=operator.itemgetter ( 1 ), reverse=True )

A: import numpy as np

class knn:

    def __init__ (self, x, y, k):
        self.k = k
        self.x_data = x
        self.y_data = y

    def predict(self, test):
        dist = np.sqrt(np.sum((self.x_data-test)**2,axis=1))
        closest = np.argpartition(dist, self.k)[0:self.k]
        a,b = np.unique(self.y_data[closest],return_counts=True)
        return a[np.where(b == b.max())]

x: features, y: label, k: number of neighbors
I hope this helps you!

A: Here is a numpy only function that will work
Where d is a numpy array of datapoints with shape (n_datapoints, n_features).
And q is a numpy array of query points with shape (n_queries, n_features).
and K is the number of neighbors you wish to get back.
n_features refers to the number of dimensions in your data.
def calc_k_nearest_neighbors(d, q, K=1):
    return d[((d[None, :, :] - q[:, None, :]) ** 2).sum(axis=2).argsort()[:,:K]]

There are some complicated python concepts going on in here, so if you wish to learn more, look into array broadcasting, np.argsort, and views of arrays.


text:
Q: make new Finder windows open at current folder In Windows when I browse in Explorer, if I open a new Explorer window, it is opened to the same location as the window I had selected when I hit Ctrl-N. Is there a way of doing the same with Finder? So if I'm browsed to Pictures, when I hit Command-N, the new Finder window opens showing Pictures.
Edit: to clarify, what happens now is that regardless of where I have browsed to, when I hit Command-N, the new Finder window opens in my home directory /Users/my_user/.

A: Enable show path in the view menu (not sure about the menu names but it should appear at the bottom of the finder window) then cmd + double click the folder you want to open, in this case, the last folder is your current folder.
I made an image but can't post it :\
Edit: Image example

A: Pressing Command-Control-O will open a new Finder tab/window at the same location.
For opening it in a tab, you must have enabled "Open folders in tabs instead of new windows" in Preferences/General. If you want to open it in a complete different window, just leave it disabled.

A: It is simple:
Go to "finder > preferences > general tab"
Uncheck to "Open folders in tabs instead of new window".
You're done!
⌘+double-click to the folder.

A: You could assign a shortcut to a script like this:
tell application "Finder"
    try
        target of Finder window 1
        make new Finder window to result
    on error
        make new Finder window to home
    end try
end tell

This would also change some properties:
tell application "Finder"
    try
        tell Finder window 1
            set t to target
            set b to bounds
            set cv to current view
            set sw to sidebar width
            set sv to statusbar visible
            set tv to toolbar visible
        end tell
    on error
        make new Finder window to home
        return
    end try
    make new Finder window to t
    tell result
        set bounds to {(item 1 of b) + 20, (item 2 of b) + 20, (item 3 of b) + 20, (item 4 of b) + 20}
        set current view to cv
        set sidebar width to sw
        set statusbar visible to sv
        set toolbar visible to tv
    end tell
end tell

target of Finder window 1 is the folder shown on the title bar. It doesn't depend on the selection in list view.
You can also use ⌃⌘↑ to reveal the location shown on the title bar in a new window. It doesn't work in column view if the toolbar is hidden though.

A: Finder on OS X doesn't have an option to re-open the most recent folder.
It is tracked in the Go menu, but if you look at the Finder preferences, it expects you to leave the default new window folder or select another target which will be the folder shown each time you open a new window.

A: ⌃⌘↑ and ⌃⌘O / ⌃⌘↓ invert the behavior for opening new windows for folders in some cases:

*

*If "Always open folders in a new window" is not checked: all views when the toolbar is shown, all views except column view when the toolbar is not shown.

*If "Always open folders in a new window" is checked: no views when the toolbar is shown, all views when the toolbar is not shown.

So if "Always open folders in a new window" is not checked and the toolbar is not hidden, you can use ⌃⌘↑ to open an enclosing folder in a new window or ⌃⌘O / ⌃⌘↓ to open a selected folder in a new window.

A:
what happens now is that regardless of where I have browsed to, when I
  hit Command-N, the new Finder window opens in my home directory
  /Users/my_user/

When there are no Finder windows open, a new Finder window created by clicking on Finder in the dock, from the Finder menu, or by using Command-N, will open to the folder you have set in Finder preferences.
BUT if Finder preferences are set to Always Open Folders in New Window, Command-O will open a new window for any selected folder.
(Seems to me there used to be a shortcut to close the previous window as you opened the new.)


text:
Q: Eliminating for loops in Matlab Here's a simple question.  The following nested for loop creates an array of sine-wave values.
N = 2^16;
for m = 1:10;
    for i = 1:N
        sine(m,i) = sin(2*pi*i./(8*2^m));
    end
end

It seems like I should be able to create this array without the use of the for loops, but I've tried various syntaxes and always get an error message.  Thanks in advance for any insights.

A: You could use bsxfun like this:
sine = sin(bsxfun(@times, 2*pi*(1:2^16), 1./(8*2.^(1:10))' ));

A: Try the following:
ii = 1:2^16;
m  = [1./(2.^(1:10))].'% transpose

prefactor = 2 * pi / 8;

sine = sin(prefactor * m * ii);

I perform a matrix multiplication A*B, in which a is a column vector size nrows, and B is a row vector size ncols, the resulting matrix will be of size nrows x ncols. Therefore m is a column vector and ii a row vector.

A: Try using ndgrid
N=2^16;
[M, I] = ndgrid(1:10, 1:N);
sine = sin(2*pi*I./(8*2.^M));


text:
Q: How to show undefined php variable notices in Aptana IDE? How is it possible to see notices about undefined variables in the problem window of Aptana?
I want to write clean source code and the hint for PHP notice is important for me, at first in the IDE and less in the running application as it's already "too late".
Maybe Aptana has an option to activate this to see the PHP notices, not only error and warnings?
See my screenshot, maybe its easier to understand my question. On this screen I will see PHP notices, warnings and errors.

A example of code, that create a PHP notice in webapp, in browser:
<?php

echo $undefined_var;

The var is not defined and result in this notice message:
Notice: Undefined variable: undefined_var in /var/www/wp-plugins/my-test.php on line 3

A: AFAIK Aptana (and also other Eclipse PHP editor plugins like PDT) do not report Undefined Variable warning / notices for the Problems view.
PHP itself gives this notice only, when the code is executed. So an IDE must also somewhat "execute" the code or do a more high-level static code analysis to report these kind of problems.
An IDE I know of that does this is Phpstorm, which is very good with the static code analysis part.

A: I don't think it's possible to report undefined variables in Problems view, but in latest Aptana releases you can configure a debugger (I tried XDebug) and then run it.


text:
Q: CoreData in XCode create a NSFetchRequest returning all entities from today Is there any solution to create a NSFetchRequest in the XCode view which is returning all entities from "today"? In the view you can only specify a date but not dynamically define today.

I know that I can also create a NSFetchRequest directly in the code and there I can specify the date dynamically but I was just wondering if this is also possible directly in XCode without writing any code.

A: Yes it is possible. You can specify a variable $TODAY and use it in code like so:
NSFetchRequest *fetchRequest =   [self.managedObjectModel
  fetchRequestFromTemplateWithName:@"ScanFetch"
  substitutionVariables:@{@"TODAY":[NSDate date]}];


text:
Q: TypeScript Javascript Class, two instances this get mixed when returning Promise I have a typescript app that it is mixing 'this' context inside a class.
This class is responsible to setup new Express server instance.
If I track 'this' with debugger and node --inspect-brk we can see 'this' is undefined when serverProtocol gets resolved
but it does not matter!
I've setup a little project to show what i'm facing.
$> git clone https://github.com/AdSegura/ThisLoseContext.git

$> cd ThisLoseContext/

$> npm i

$> npm run build && node dist/

What output should expect:
INIT: Server_ID: quijote_1111, PORT: 1111
-----------------------------------------
INIT: Server_ID: quijote_2222, PORT: 2222
-----------------------------------------
Callback: Server_ID: quijote_1111, PORT: 1111
ServerProtocol: Server_ID: quijote_1111; PORT: 1111
Callback: Server_ID: quijote_2222, PORT: 2222
ServerProtocol: Server_ID: quijote_2222; PORT: 2222

What is the real output:
INIT: Server_ID: quijote_1111, PORT: 1111
-----------------------------------------
INIT: Server_ID: quijote_2222, PORT: 2222
-----------------------------------------
Callback: Server_ID: quijote_1111, PORT: 2222 [ERROR]
ServerProtocol: Server_ID: quijote_1111; PORT: 2222 [ERROR]
Callback: Server_ID: quijote_2222, PORT: 2222
ServerProtocol: Server_ID: quijote_2222; PORT: 2222

The problem is in Server.ts this.serverProtocol() is mixing this.options.port
var http = require('http');
var express = require('express');
const os = require("os");

export class Server {
    /** The http server.*/
    public express: any;

    /** express httpServer */
    protected server: any;

    /** id representing server instance */
    protected server_id: any;

    /**
     * Create a new server instance.
     */
    constructor(private options: any) {
        this.server_id = this.generateServerId();
    }

    /**
     * Start the Socket.io server.
     *
     * @return {void}
     */
    init(): Promise<any> {
        console.log(`INIT: Server_ID: ${this.server_id}, PORT: ${this.options.port}`);
        return new Promise((resolve, reject) => {
            debugger;
            this.serverProtocol().then(instance => {
                debugger;
                console.log(`ServerProtocol: Server_ID: ${this.server_id}; PORT: ${this.options.port}`);
                resolve();
            }, error => reject(error));
        });
    }

    /**
     * Select the http protocol to run on.
     *
     * @return {Promise<any>}
     */
    serverProtocol(): Promise<any> {
        return this.httpServer()
    }

    /**
     * Express socket.io server.
     */
    httpServer(): Promise<any> {
        return new Promise((resolve, reject) => {

            this.express = express();
            this.express.use((req, res, next) => {
                for (var header in this.options.headers) {
                    res.setHeader(header, this.options.headers[header]);
                }
                next();
            });

            const httpServer = http.createServer(this.express);

            function cb() {
                debugger;
                console.log(`Callback: Server_ID: ${this.server_id}, PORT: ${this.options.port}`)
                return resolve.call(this, this)
            }

            this.server = httpServer.listen(this.options.port, this.options.host, () =>  cb.call(this));
        })
    }

    /**
     * Generate Server Id
     *
     * @return string hostname_port
     */
    generateServerId(): string {
        const hostname = os.hostname();
        const port = this.options.port;

        return `${hostname}_${port}`
    }

}

I'm a novice with typescript, I tried multiple targets at tsconfig but same result, this.options gets the last config {port:2222} when you instanciate two or more objects.
Thanks.
Update
I think understand this:

There is no such thing as a "local object". You do have a reference to an
  object. Two instances might have two references to the same object.

this.options point to global opt variable, BAD
const opt = { foo: 3 };

export class MyClass {
    constructor(private options: any){

        this.options = Object.assign(opt, options)
    }

    getOptions(): any {
        return this.options
    }
}

this.options point to local opt variable, GOOD

export class MyClass {
    constructor(private options: any){
        const opt = { foo: 3 };
        this.options = Object.assign(opt, options)
    }

    getOptions(): any {
        return this.options
    }
}

But as our partners said bellow, the safest methods to create new options variable are:
this.options = Object.assign({}, this.defaultOptions, config);
or
this.options = { ...this.defaultOptions, ...config };
And now we have a new object not a copy to an object outside the scope of the constructor method.
So the safest version of the code should be:

export class MyClass {
    constructor(private options: any){
        const opt = { foo: 3 };
        this.options = Object.assign({}, opt, options)
    }

    getOptions(): any {
        return this.options
    }
}

A: The issue is probably inside the EchoServer class, namely here:
 this.options = Object.assign(this.defaultOptions, config);

Thats equal to:
 this.options = this.defaultOptions;
 Object.assign(this.defaultOptions, config);

I assume you actually wanted to do:
 this.options = Object.assign({}, this.defaultOptions, config);

which creates an own options object for each instance.


text:
Q: I keep getting the error message no module named gdata I keep getting the error message no module named gdata. after I did this
 pip install --upgrade google-api-python-client

so I tried this
pip install gdata

and it installed
gdata 2.0.18

But I still keep getting the error message. If I do pip list I get
    beautifulsoup4 (4.4.1)
    dj-database-url (0.4.0)
    Django (1.9.2)
    django-bootstrap-pagination (1.6.1)
    django-crispy-forms (1.6.0)
    django-haystack (2.4.1)
    django-markdown-deux (1.0.5)
    django-pagedown (0.1.1)
    django-taggit (0.18.1)
    feedparser (5.2.1)
    future (0.15.2)
    gdata (2.0.18)
    google-api-python-client (1.5.1)
    gunicorn (19.4.5)
    html5lib (0.9999999)
    httplib2 (0.9.2)
    lxml (3.6.0)
    markdown2 (2.3.1)
    oauth2client (2.2.0)
    oauthlib (1.1.2)
    Pillow (3.2.0)
    pip (8.1.2)
    psycopg2 (2.6.1)
    pyasn1 (0.1.9)
    pyasn1-modules (0.0.8)
    requests (2.9.1)
    requests-oauthlib (0.6.1)
    rsa (3.4.2)
    setuptools (20.6.7)
    simplejson (3.8.2)
    six (1.10.0)
    tweepy (3.5.0)
    uritemplate (0.6)
    wheel (0.29.0)
    whitenoise (3.0)
    Whoosh (2.7.4)

I'm using this in a django app if that matters. What's my issue?
EDIT If if I use python shell and try to import it. I get this error message
      Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/gdata/__init__.py", line 27, in <module>
        import atom
      File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/atom/__init__.py", line 133, in <module>
        CreateClassFromXMLString)
      File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/atom/__init__.py", line 97, in mark_deprecated
        optional_warn_function.func_name = f.func_name
    AttributeError: 'function' object has no attribute 'func_name'

EDIT I just read this on git
The client library is only designed for Python 2.4 - 2.6. See Issue 229:
http://code.google.com/p/gdata-python-client/issues/detail?

id=229&q=label:Type-Defect

It also support 2.6+ but not 3.* as yet. For 3.0 support please track

http://code.google.com/p/gdata-python-client/issues/detail?id=229
So this may be my issue. This is from may 25, 2015
The documentation says up to 3.4 I'm using 3.5 so I guess it won't work


text:
Q: как найти количество элементов массива, значение и индекс которых больше 10

let x = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];

for(let i = 0;i<x.length;i++){
    if(x>10 && x[i]>10){

    }
}

A: Только не забывайте, что индекс начинается всегда с 0.
Значение 1 - будет иметь индекс 0, 2 будет иметь индекс 1 и так далее.

    let x = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
    var count = 0;
    for(let i = 0;i<x.length;i++) {
        if (i > 10 && x[i] > 10) { // i - это ключ, x[i]- цифра
            count += 1;
        }
    }
    console.log(count);

Если хотите, чтобы значение и индекс совпадали, то возьмите отсчёт count с единицы
Пример:

    let x = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
    var count = 1;
    for(let i = 0;i<x.length;i++) {
        if (i > 10 && x[i] > 10) { // i - это ключ, x[i]- цифра
            count += 1;
        }
    }
    console.log(count);

Так же можно добавить в массив любое значение в позицию индекса 0 или в if (i > 10 && x[i] > 10) { начинать отчёт от 9 if (i > 9 && x[i] > 10) {

A: Чтоб получить все элементы массива, индекс которых больше за 10, итерацию следует начинать с значения больше за 10 и тогда придется делать только 1 проверку: больше ли значение по индексу за 10.

let x = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
let count = 0;
for(let i = 11;i<x.length;i++) {
  if (x[i] > 10) {
    count += 1;
  }
}
console.log(count);


text:
Q: Hibernate inverse one to many mapping does not seem to properly handle item removal from Java list Two classes:
 <class name="SpreadsheetImportTemplate" table="spreadsheetimport_template">
   <id name="id" type="int" column="id" unsaved-value="0">
     <generator class="native" />
   </id>
   <property name="name" type="java.lang.String" column="name" not-null="true" length="100" />
   <many-to-one name="creator" class="org.openmrs.User" not-null="true" />
   <property name="created" type="java.util.Date" column="date_created" not-null="true"
   length="19" />
   <many-to-one name="modifiedBy" column="changed_by" class="org.openmrs.User" not-null="false" />
   <property name="modified" type="java.util.Date" column="date_changed" not-null="false" length="19" />

  <!-- Associations -->
  <!-- bi-directional one-to-many association to SpreadsheetImportTemplateColumn -->
  <bag name="columns" cascade="all-delete-orphan" inverse="true">
    <key column="template_id" not-null="true" />
    <one-to-many class="SpreadsheetImportTemplateColumn" />
  </bag>
</class>

<class name="SpreadsheetImportTemplateColumn" table="spreadsheetimport_template_column">
  <id name="id" type="int" column="id" unsaved-value="0">
    <generator class="native" />
  </id>

  <many-to-one name="template" class="SpreadsheetImportTemplate" column="template_id" />

  <property name="columnName" type="java.lang.String" column="column_name" length="100" not-null="true" />
  <property name="dbTableDotColumn" type="java.lang.String" column="db_table_dot_column" length="100" not-null="true"/>
  <property name="extraData" type="java.lang.String" column="extra_data" length="100" not-null="false"/>

</class>

In java both have following with respective getters and setters:
    public class SpreadsheetImportTemplate {
 Integer id;
 String name;
    Collection<SpreadsheetImportTemplateColumn> columns = new ArrayList<SpreadsheetImportTemplateColumn>();
 Date created;
 Date modified;
 User creator;
 User modifiedBy;

 public SpreadsheetImportTemplate() {
 }
     ...

public class SpreadsheetImportTemplateColumn {
 Integer id;
 SpreadsheetImportTemplate template;
 String columnName;
 String dbTableDotColumn;
 String extraData;

 public SpreadsheetImportTemplateColumn() {
 }
    ...

However, if we have a SpreadsheetImportTemplate template with some columns, and we do a template.remove(0) and then a Hibernate saveOrUpdate, the relevant SpreadsheetImportTemplateColumn does not get deleted from the database :(
Any help appreciated.
Fyi, here is the relevant SQL that creates the databases:
CREATE TABLE IF NOT EXISTS `spreadsheetimport_template` (
    `id` int(32) NOT NULL auto_increment,
    `name` varchar(100) NOT NULL,
    `creator` int(11) NOT NULL default '0',
    `date_created` datetime NOT NULL default '0000-00-00 00:00:00',
    `changed_by` int(11) default NULL,
    `date_changed` datetime default NULL,
    PRIMARY KEY  (`id`),
    KEY `User who wrote this spreadsheet template` (`creator`),
    KEY `User who changed this spreadsheet template` (`changed_by`),
    CONSTRAINT `User who wrote this spreadsheet template` FOREIGN KEY (`creator`) REFERENCES `users` (`user_id`),
    CONSTRAINT `User who changed this spreadsheet template` FOREIGN KEY (`changed_by`) REFERENCES `users` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `spreadsheetimport_template_column` (
    `id` int(32) NOT NULL auto_increment,
    `template_id` int(32) NOT NULL default '0',
    `column_name` varchar(100) NOT NULL,
    `db_table_dot_column` varchar(100) NOT NULL,
    `extra_data` varchar(100),
    PRIMARY KEY  (`id`),
    KEY `Spreadsheet template to which this column belongs` (`template_id`),
    CONSTRAINT `Spreadsheet template to which this column belongs` FOREIGN KEY (`template_id`) REFERENCES `spreadsheetimport_template` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

A: Just relevant part
SpreadsheetImportTemplate
public class SpreadsheetImportTemplate {

    private Integer id;
    public Integer getId() { return id; }
    public void setId(Integer id) { this.id = id; }

    private Collection<SpreadsheetImportTemplateColumn> columns = new ArrayList<SpreadsheetImportTemplateColumn>();
    public Collection<SpreadsheetImportTemplateColumn> getColumns() { return columns; }
    public void setColumns(Collection<SpreadsheetImportTemplateColumn> columns) { this.columns = columns; }

    /**
     * set up both sides
     */
    public void addColumn(SpreadsheetImportTemplateColumn column) {
        getColumns().add(column);

        column.setTemplate(this);
    }

}

SpreadsheetImportTemplateColumn
public class SpreadsheetImportTemplateColumn {

    private Integer id;
    public Integer getId() { return id; }
    public void setId(Integer id) { this.id = id; }

    private SpreadsheetImportTemplate template;
    public SpreadsheetImportTemplate getTemplate() { return template; }
    public void setTemplate(SpreadsheetImportTemplate template) { this.template = template; }

}

mapping
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="br.com._3589013.model.domain">
     <class name="SpreadsheetImportTemplate">
         <id name="id">
             <generator class="native"/>
         </id>
         <bag name="columns" cascade="all,delete-orphan" inverse="true">
             <key/>
             <one-to-many class="SpreadsheetImportTemplateColumn"/>
         </bag>
    </class>
    <class name="SpreadsheetImportTemplateColumn">
         <id name="id">
             <generator class="native"/>
         </id>
         <many-to-one name="template" class="SpreadsheetImportTemplate"/>
    </class>
</hibernate-mapping>

Test
public class PersistenceTest {

    private static SessionFactory sessionFactory;

    private Serializable id;

    @BeforeClass
    public static void setUpClass() {
        Configuration c = new Configuration();
        c.addResource("mapping.hbm.3589013.xml");

        sessionFactory = c.configure().buildSessionFactory();
    }

    @Before
    public void setUp() throws Exception {
        SpreadsheetImportTemplate sit = new SpreadsheetImportTemplate();
        sit.addColumn(new SpreadsheetImportTemplateColumn());

        Session session = sessionFactory.openSession();
        session.beginTransaction();

        id = session.save(sit);

        session.getTransaction().commit();
    }

    @Test
    public void removedOrphan() throws Exception {
        Session session = sessionFactory.openSession();
        session.beginTransaction();

        List<SpreadsheetImportTemplateColumn> sitcList = session.createQuery("from SpreadsheetImportTemplateColumn").list();

        assertTrue(sitcList.size() == 1);

        SpreadsheetImportTemplate sit = (SpreadsheetImportTemplate) session.get(SpreadsheetImportTemplate.class, id);
        sit.getColumns().remove(sitcList.get(0));

        session.getTransaction().commit();

        assertTrue(sit.getColumns().size() == 0);
    }

}

It works fine!

A: I could not figure it out.
I hacked a work around:
public class SpreadsheetImportDAOImpl implements SpreadsheetImportDAO {

...

public SpreadsheetImportTemplate saveSpreadsheetImportTemplate(SpreadsheetImportTemplate template) {
    // TODO: Hack - how does this get specified properly in hbm.xml files???
    // Column processing: delete columns that must be deleted, make sure template field
    // points to template
    Iterator<SpreadsheetImportTemplateColumn> columnIterator = template.getColumns().iterator();
    while (columnIterator.hasNext()) {
        SpreadsheetImportTemplateColumn column = columnIterator.next();
        if (column.isDeleted()) {
            columnIterator.remove();
            sessionFactory.getCurrentSession().delete(column);
        } else {
            column.setTemplate(template);
        }
    }
    sessionFactory.getCurrentSession().saveOrUpdate(template);
    return template;
}

...

}


text:
Q: shell_exec return null - monitoring of linux services I need monitoring services of my linux server without shell and i write a new php script, which do this function. After run, script not write status of service.
For example - if i write this command in terminal -
service nginx status |awk '{print $4}

he is return to me result:
Run...

This script:
<?php
$nginx = shell_exec("service nginx status |awk '{print $4}'");
$bd = shell_exec("service mysqld status |awk '{print $4}'");
$jabber = shell_exec("service ejabberd status |awk '{print $4}'");
$cgi = shell_exec("service php-fpm status |awk '{print $4}'");
$mem = shell_exec("service memcached status |awk '{print $4}'");
echo "Web-server nginx: $nginx";
echo "
";
echo "Server MySQL: $bd";
echo "
";
echo "Server Jabber Jabber: $jabber";
echo "
";
echo "Service php-fpm: $cgi";
echo "
";
echo "Service memcached: $mem";
?>

if do this via php, all '$' functions return empty information about status of services.
How write this script correctly? Please, help :)

A: Use the full path to the service command, since the directory it's in is not in the web server's default $PATH.


text:
Q: Paste image from clipboard javascript We have a program the wants to get an image copy into the clipboard to paste into a file on the HDD using javascript/HTA.
Does anyone done something like this before? Or How can I create an image file on the HDD from the information in the clipboard?
We are already using the following for text, but it does not work for images:
clipboardData.setData("Text", 'To Copy to clipboard');
clipboardData.getData("Text");  // To copy from clipboard

A: You can possibly read the clipboard data in some supported browsers:
Is it possible to read the clipboard in Firefox, Safari and Chrome using Javascript?
The problem is with you storing this data on the user's hard-drive. Javascript to my knowledge will not give you access to the user's hard-drive due to security reasons. One way to get around this is to send this data to a server running a php script that will then proceed to read the data and save it to the server's local storage. This php script can be set up to return the full path which was used when saving the file. Your javascript post method can then use this returned path to load it in a browser which will prompt your browser to display the download prompt. Then the user can download the file and save it to their local drive.
It very convoluted but can work.
RE: HTA
HTA only works in IE and is not very popular so you will have some problems finding code resource for the exact tasks that you require. This is some code which I found for reading and writing files to disk
<!--
// CAREFUL -- no error checking
function readFile()
{
   var fso, fileHandle, contents, yourfilename;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   fileHandle = fso.OpenTextFile(document.editor.yourfilename.value, 1);
   contents = fileHandle.ReadAll();

   if (contents)
     document.all("fileContents").value = contents;

   fileHandle.close();

 }

function writeFile()
{
   var fso, fileHandle, yourfilename;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   fileHandle = fso.CreateTextFile(document.editor.yourfilename.value, true);
   fileHandle.write(document.all("fileContents").value);
   fileHandle.close();
}

//-->

Then you will have to combine this code to use the window.clipboardData.getData functionality for getting the stored clipboard contents. I have never done HTA so I can't give you any help with that.

A: It look that is impossible to paste an image from the clipboard. We ended up using via command line an external application like Minicap ( http://www.softpedia.com/get/Multimedia/Graphic/Graphic-Capture/MiniCap.shtml ).


text:
Q: Storing Seekbar value but keep getting that I have to use final "Variable is accessed within inner class Needs to be declared final" is the the error I get at first. So I change it to final. Once I change it to final I get a different error saying "Cannot assign value to final variable". I'm kind of stuck here on what to do here. Its giving me the error on int exam_grade
    public class CalculateGradeActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.calculate_grade_view);
    seekbar();

}
public void seekbar(){
    SeekBar seek_bar1 = (SeekBar) findViewById(R.id.seekBarExam);

    final TextView text_view = (TextView) findViewById(R.id.percentageSeekbar1);

    int exam_grade;
    TextView text_view5 = (TextView) findViewById(R.id.numeric_grade_id_output);
    text_view5.setText(String.valueOf(exam_grade));

    int progress = seek_bar1.getProgress();
    text_view.setText(String.valueOf(progress));

    seek_bar1.setOnSeekBarChangeListener(

            new SeekBar.OnSeekBarChangeListener() {

                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    exam_grade = progress;
                    text_view.setText(String.valueOf(progress) + "%");

                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {

                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {

                }
            }
    );

}//ends seekbar function

}

A: Hi don't declare your textview as final, put it in the class attributes instead.
public class CalculateGradeActivity extends Activity {

    TextView text_view;
    SeekBar seek_bar1

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.calculate_grade_view);
    seek_bar1 = (SeekBar) findViewById(R.id.seekBarExam);
    text_view = (TextView) findViewById(R.id.percentageSeekbar1);
    seekbar();

}

Do the same for all views(Declare them as attributes).

A: final means it can only be assigned once.
I feel sure that textview shouldn't be final.
anyway,
try putting the declarations of exam grade and TextView in your onCreate...
     setContentView(R.layout.calculate_grade_view);
     int exam_grade;
     TextView text_view = (TextView) findViewById(R.id.percentageSeekbar1);
     seekbar();


text:
Q: Can third-order phase transitions be understood from a symmetry-breaking viewpoint? First-order phase transitions like solid-fluid can be understood as breaking of translational symmetry into lattice symmetry (also rotations into discrete rotations). The characteristic of these transitions are latent heat. In general the first derivative of the free energy diverges.
Second-order phase transitions can be phenomenologically modeled using Landau-Ginzburg formalism. Here spontaneous breaking of symmetry gives rise to different phases of matter. Spontaneous symmetry breaking predicts the values of the critical constants to a good approximation.
We also know a few examples of third-order phase transitions. To list a couple, we have the Gross–Witten–Wadia and Douglas–Kazakov large-N phase transitions. I was trying to understand if this phase transition can also be explained in terms of symmetry breaking. Are there known arguments in literature which explain third order phase transition from this viewpoint?
EDIT: I found my answer here.


text:
Q: Django password not hashed when creating new accounts I'm new to django and am trying to discover why creating new accounts via my account form do not hash the password (I assume the passwords are not hashed because I cannot log in using the password when the account is created, and this message shows under the password field in the django admin for accounts created via the form: Invalid password format or unknown hashing algorithm). I can successfully create new accounts in the django admin that do not have this un-hashed password issue.
views.py:
@unauthenticated_user
def create_account(request):
    form = AccountForm()

    if request.method == 'POST':
        form = AccountForm(request.POST)
        # should hash the password, check username/email doesnt already exist, etc
        if form.is_valid():
            user = form.save()
            return redirect('/login')
        else:
            messages.info(request, "Count not create account.")

    context = {'form': form}
    return render(request, 'accounts/create_account.html', context)

models.py:
class Account(AbstractUser):

    def __str__(self) -> str:
        return self.first_name

    pass

Create account form:
<form action="{% url 'create_account' %}" method="POST">
    {% csrf_token %}
    {{form.as_p}}
    <input type="submit" name="submit">
</form>

The form:
class AccountForm(ModelForm):
    class Meta:
        model = Account  # which model we're building a form for
        # password not hashed and requires username even if username omitted from fields
        fields = ['email', 'password', 'first_name', 'last_name', 'username']

I'm following a tutorial series where the only difference with my code is that I extend from the AbstractUser model with the Account class (so that I can change the create user form to only require an email and password instead of a username and password). Unless I'm incorrect, I thought the AbstractUser model should automatically hash passwords for you.
Where am I going wrong here?

A: As @purple mentioned, use set_password(...)--Doc method as
@unauthenticated_user
def create_account(request):
    form = AccountForm()

    if request.method == 'POST':
        form = AccountForm(request.POST)

        if form.is_valid():
            user = form.save(commit=False)  # set `commit=False`
            user.set_password(
                form.cleaned_data["password"]
            )  # call `set_password(...)` with "raw password"
            user.save()  # save the actual User instance
            return redirect('/login')
        else:
            messages.info(request, "Count not create account.")

    context = {'form': form}
    return render(request, 'accounts/create_account.html', context)

A: Use set_password method
def create_account(request):
    form = AccountForm()

    if request.method == 'POST':
        form = AccountForm(request.POST)
        # should hash the password, check username/email doesnt already exist, etc
        if form.is_valid():
            form.set_password(request.POST['password'])
            form.save()
            return redirect('/login')
        else:
            messages.info(request, "Count not create account.")

    context = {'form': form}
    return render(request, 'accounts/create_account.html', context)


text:
Q: Doctrine resultCache breaks entity removal I'm having trouble using the Doctrine ORM's result cache. The app manages creating/deleting channel entities and adding data to channels for monitoring purposes via a JSON REST interface. Caching the channel entities across requests is desirable for performance reasons as they are mostly static.
During unit testing we've found problems with the flow 1) create channel 2) add data and 3) delete channel. A new entity manager is used in the code below to simulate the separate JSON requests for testing purposes:
public function run() {
    // 1) add channel
    $this->em = self::createEntityManager();
    $channel = new Model\Channel('power');
    echo($uuid = $channel->getUuid());

    $this->setProperties($channel, array('title'=>'Meter', 'resolution'=>100));

    $this->em->persist($channel);
    $this->em->flush();
    $this->clearCache();

    // 2) add data
    $this->em = self::createEntityManager();
    $channel = $this->get($uuid);
    $this->dumpEntityState($channel, 'add ');

    $channel->addData(new Model\Data($channel, 1000000, 1));
    $this->em->flush();
    $this->dumpEntityState($channel, 'adddata ');

    // this fixes the problem
    // $this->clearCache();

    // 3) delete channel
    $this->em = self::createEntityManager();
    $entity = $this->get($uuid);
    $this->dumpEntityState($channel, 'delete ');

    if ($entity instanceof Model\Channel) {
        $entity->clearData($this->em);
    }

    $this->em->remove($entity);
    $this->em->flush();
    $this->clearCache();
}

The channel entity is retrieved by its identifier:
public function get($uuid) {
    if (!Util\UUID::validate($uuid)) {
        throw new \Exception('Invalid UUID: \'' . $uuid . '\'');
    }

    $dql = 'SELECT a, p
        FROM Volkszaehler\Model\Entity a
        LEFT JOIN a.properties p
        WHERE a.uuid = :uuid';

    $q = $this->em->createQuery($dql);
    $q->setParameter('uuid', $uuid);

    // this breaks the app
    $q->useResultCache(true);

    try {
        return $q->getSingleResult();
    } catch (\Doctrine\ORM\NoResultException $e) {
        throw new \Exception('No entity found with UUID: \'' . $uuid . '\'', 404);
    }
}

Now the problem is that once useResultCache(true) is used, deleting the entity in step 3) results in error:
Uncaught exception 'InvalidArgumentException' with message 'A detached entity can not be removed.' in \ORM\UnitOfWork.php

As soon as useResultCache() is false, the problem is gone.
How can the resultCache influence the removal of entities, especially as the result cache is cleared whenever the channel entity is updated?
UPDATE
Checking the channel entity state after adding data on a freshly retrieved entity from the existing entity manager, it's state is already DETACHED. This is also the first time the result cache comes into play.
How/why does result cache make entities DETACHED?

A: The answer is found with Doctrine: http://www.doctrine-project.org/jira/browse/DDC-446 cached entities are always "detached". If you need a managed entity you can merge it- though at a cost of an additional DB query.
Conclusion
If managed entities are needed for removal etc. it's best to not use cached query results.
Update
This behaviour has been changed in Doctrine 2.3- cached results are now always hydrated and therefore become managed.


text:
Q: Why do some OpenGL parameters take 0.0-1.0? Why do some OpenGL parameters take a value between 0.0 and 1.0 for some functions like glColor3f and glNormal3? This is a question that has always sort of bugged me; I have always had since the beginning of my 3D programming career, but originally I just went along with it like any other sheep following the herd. But why 0.0-1.0? Was it an arbitrary choice made by the the Khronos Group, or something more existential?

A: Because values less than 0 or greater than 1 don't make sense for those things.
For colors, the typical representation for display purposes is an 8-bit integer from 0 to 255, but OpenGL isn't limited to that specific representation; a GL implementation can also support things like 48-bit color (16 bits per channel), or floating-point color components.  To be independent of the underlying representation, color components in OpenGL are represented as fractions from 0% to 100%, which are expressed by the numbers 0.0 and 1.0.  The GL implementation converts those values into whichever format is actually used by the display (e.g. the typical 0-255).
Normals are supposed to be unit-length vectors, which means that the length of each component naturally can't be greater than than 1; otherwise the length of the whole vector would be greater than 1.
Note that these values don't actually have to be in the 0.0-1.0 range:

*

*For colors, your monitor can't actually display a brightness greater than 100%, but a color component greater than 1.0 can be useful if it's going to be multiplied by something (e.g. a texture or scaling factor) that'll bring it back into range.  This is commonly used for HDR rendering.

*Non-unit-length normal vectors aren't really useful for the legacy fixed-function lighting that it sounds like you're using, since they don't correspond to real-world physics, but you can specify them anyway and you'll get results that are mathematically correct (though not realistic or useful).  You can also specify non-unit-length normals and ask OpenGL to automatically scale them to unit length using GL_NORMALIZE.
Non-unit-length vectors can be useful in programs that use custom shaders to perform sophisticated lighting calculations.


text:
Q: Breaking Uniquely decipherable codes. Is it possible to decode a message that has been encoded using a Uniquely Decipherable Code without knowing the code that is used.
If it is possible, what is the time complexity?

A: No. $0\mapsto 0$, $1\mapsto 1$ and $0\mapsto 1$, $1\mapsto 0$ are two uniquely decipherable codes. How would you know if $10110100$ stands for $10110100$ or $01001011$?


text:
Q: Path Provider Using and Asset Problems I want to add an image that I added to my application from the phone's gallery to the list and call it with Image.asset as a String value.
I managed to get the image with ImagePicker. Unfortunately, there is no next. I don't know exactly how to do this.
In short: I will select an image from gallery with ImagePicker and replace it with "Image.file"
I will do it by converting it to String value with Image.asset.

A: You have to use image.file or image.memory to load an image from ImagePicker.
image.asset is for images that already exist within your app.


text:
Q: Plotting an irregularly-spaced RGB image in Python I want to plot several RGB images on one set of axes with matplotlib.  I initially tried using imshow for this, but it doesn't seem to handle two images on one set of axes with different extents (when I plot the second, it makes the first disappear).  I think the answer here is to use pcolormesh, like in How to plot an irregular spaced RGB image using python and basemap?
However, this doesn't seem to work for me - the color coming from the mappable (i.e. the data array I pass to pcolormesh, and the cmap I specify) overrides the face color I specify.  The edges of the grid do have the right color, but not the faces.
Does anyone know how to set the color of the faces directly? Ideally I'd use a pcolormesh that takes an n*m*3 array as an alternative to n*m, just like imshow...
A minimal example of how I'd like it to work:
    import numpy as np
    import matplotlib.pyplot as plt
#make some sample data
x, y = np.meshgrid(np.linspace(0,255,1),np.linspace(0,255,1))
r, g = np.meshgrid(np.linspace(0,255,100),np.linspace(0,255,120))
b=255-r

#this is now an RGB array, 100x100x3 that I want to display
rgb = np.array([r,g,b]).T

m = plt.pcolormesh(x, y, rgb/255.0, linewidth=0)
plt.show()

The problem is that the call to plt.pcolormesh fails, with
numRows, numCols = C.shape
ValueError: too many values to unpack

I guess this is because it wants a 2D array, not a 3D array with the last dimension being 3 long.

A: The solution was very simple: the one thing I needed to do that wasn't in the question I linked to was to remove the array from the mesh object.  A minimal example, in case it's helpful to others:
import numpy as np
import matplotlib.pyplot as plt

#make some sample data
r, g = np.meshgrid(np.linspace(0,255,100),np.linspace(0,255,100))
b=255-r

#this is now an RGB array, 100x100x3 that I want to display
rgb = np.array([r,g,b]).T

color_tuple = rgb.transpose((1,0,2)).reshape((rgb.shape[0]*rgb.shape[1],rgb.shape[2]))/255.0

m = plt.pcolormesh(r, color=color_tuple, linewidth=0)
m.set_array(None)
plt.show()

I guess the color_tuple line might be non-obvious: essentially we need to turn the (n, m, 3) array into an (n*m, 3) array.  I think the transpose is necessary to get everything to match up correctly.  It's also worth noting that the colors we pass in need to be floating-point, between 0 and 1.

A: How about combining all your images into one big numpy array which you then display with imshow?


text:
Q: Melhor maneira de herdar um controller e dar um override numa rotina angularjs 1.5.x Abaixo está meu código que implementa herança usando $controller. Está maneira está boa? Meu objetivo é reusar uma classe baseController que vai ter algumas rotinas em comum para controllers crud.
Fiddle: http://jsfiddle.net/1o278ntw/6/
var myApp = angular.module('myApp', []);

myApp.controller('parentController', parentController);
function parentController() {
    var vm = this;
    vm.mainRoutine = mainRoutine;
    vm.subRoutine = subRoutine;

    //1: use the vm before call subRoutine, just solved the future override
    function mainRoutine() { return vm.subRoutine(); };
    function subRoutine() { return 'parent'; };
}

myApp.controller('child1Controller', child1Controller);
child1Controller.$inject = ['$controller'];
function child1Controller($controller) {
    var vm = this;
    var base = $controller('parentController');
    angular.extend(vm, base);

    //2: override
    base.subRoutine = subRoutine;
    vm.childRoutine = childRoutine;
    vm.callParentRoutine = callParentRoutine;

    function subRoutine() { return vm.subRoutine() + ' -> child1'; };
    function childRoutine() { return 'childRoutine'; };
    function callParentRoutine() { return vm.mainRoutine(); };
}

A: Ricardo, caso for usar ui-router no seu projeto. Dê uma olhada em Nested States and Views.
Com ele você pode criar um state(rota) abstrato e criar outros states filhos herdando o $scope e resolves. Acredito que essa seja a melhor maneira.
https://github.com/angular-ui/ui-router/wiki/nested-states-%26-nested-views


text:
Q: custom woocommerce checkout form fields i have the following function adding a checkbox to the woocommerce checkout form:
woocommerce_form_field( 'email_signup', array(
    'type'          => 'checkbox',
    'class'         => array('input-checkbox'),
    'label'         => __('Newsletter Signup?'),
    ), $checkout->get_value( 'email_signup' ));

I would like to make the checkbox selected by default. Is there a way of doing it through woocommerce form_field options? Or will i need to use javascript?

A: Adding 'default' => 1 should do the trick
woocommerce_form_field( 'email_signup', array(
'type'          => 'checkbox',
'class'         => array('input-checkbox'),
'label'         => __('Newsletter Signup?'),
'checked'       => 'checked',
'default'       => 1,
), $checkout->get_value( 'email_signup' ));

A: Have you tried:
woocommerce_form_field( 'email_signup', array(
'type'          => 'checkbox',
'class'         => array('input-checkbox'),
'label'         => __('Newsletter Signup?'),
'checked'       => 'checked',
), $checkout->get_value( 'email_signup' ));

A: By including:
'checked'       => 'checked',
'default'       => 1,

in array, would do the trick.. Voila!

A: you can certainly do that, with this plugin
Also you can actually insert your very own two options for checkbox. "Yes" or "No" etc


text:
Q: How to use Doors to load levels in godot 3d just started playing around with Godot and I'm trying to figure out the best way to handle level switching in my game.
The game world is split into 3 distinct levels:

*

*Outside

*Inside Level 1

*Inside Level 2

Outside and Inside Level 1 are connected, and Inside Level 1 and Level 2 are connected
I need a way to make it so that when a player interacts with a door object the game loads the level necessary AND spawns the player at the correct spawn point.
So when the player goes from Inside Level 1 to Outside, they need to spawn right infront of the door object in the Outside Level instead of Outside's default spawn location. The same is true of when the Player goes from Inside Level 2 back to Inside Level 1.
I just learned about singletons/autoload so I figure I need to set up some kind of level manager but Im not exactly sure how. I also don't know how to set the player's transform to be the same as the spawn point.

A: Yes, use an autoload.
We can really over-engineer this. There are many variations, as you will see below. But there are a set of steps you are going to follow. In the interest of not bloating this answer, I'll cover them in broad terms.
This is what you are going to do:

*

*In the scenes add a Position3D for each door. This Position3D will be where you will place the player character when it enters from the corresponding door. And give the Position3D a name that you can figure out form the name of the door.

*Store in a variable in the autoload which door the player interacted with. This is what we are going to use to find the Position3D on the new scene. The code in the door will either call a method on the autoload, or set the variable directly.

*Change scenes, by whatever means you prefer (it can be from the code in the door, or a method in the autoload - it can be with the scene tree methods or manually - you can load, preload or load interactively the new scene). Interactive load avoid freezing the game during the load. Which allows you have an animation to hide the load time.

*After the new scene is loaded, instantiated and in the scene tree… Get the corresponding Position3D with the value stored in the autoload (if there is any).

*Now you are going to place the player character at the Position3D you found. This might mean to move it, if you have the player character as part of the scene. Or a method in the autoload spawns the character in the correct position. Or you might even remove the player character from the old scene, store it in the autoload, and after the new scene is ready, add it to it. In fact, it is possible to make the player character itself an autoload. Regardless of how you get the reference to the character player, you are going to make sure its global_transform is set to the global_transform of the Position3D you found (if there was any). If there wasn't, then put (or let) the player character at a default position.
Addendum: If you only want the position instead of the transform, you can use global_transform.origin. There isn't a global_position in 3D in Godot 3, however it was added in Godot 4.


text:
Q: modx revo mSearch2 как добавить в &where несколько условий? Подскажите как правильно написать условие &where
[[!pdoPage?
&element=`mSearch2`
&parents = `14`
&templates = `4`
&minQuery = `1`
&where = `[[!#GET.sale_filter:is=`1`:then=`{"old_price:>=":1}`]]`
&includeTVs = `image,price,old_price,new_good,sku,model,brand,quantity`
&tpl = `SimpleSearchResult`
&tplWrapper = `@INLINE  <div class="sisea-results-list box inline">
                            [[+output]]
                        </div>`
&limit = `[[!#GET.count-search:default=`12`]]`
]]

В этом примере если установлена переменная GET[sale_filter] то включается фильтрация.
А как сделать чтобы добавлялись несколько условий? GET[brand],GET[quantity],GET[sale_filter],GET[price],GET[sort] - какие-то могут присутствовать а может и нет

A: &where = `[[!customSnippet]]`

Дабы не иметь проблем с синтаксисом параметра where, я бы посоветовал вам написать отдельный сниппет, который анализирует массив GET переменных, строит необходимый JSON массив и передает его в вызов pdoPage


text:
Q: Spine and Reactjs issues error @esotericsoftware/spine-player' does not contain a default export (imported as 'spine') I want embedded then Spine 2d into Reactjs app,
When I read Spine documents, they offer import spine from '@esotericsoftware/spine-player';
but I render app it issues a error:
Attempted import error: '@esotericsoftware/spine-player' does not contain a default export (imported as 'spine').
My code:
import React from 'react';
import spine from '@esotericsoftware/spine-player';

const Character = () => {

    var jsonUrl = 'assets/Vi.json';
    var atlasUrl = 'assets/Vi.atlas';

    new spine.SpinePlayer('player-container', {
        jsonUrl: jsonUrl,
        atlasUrl: atlasUrl,
        animation: 'jump',
        premultipliedAlpha: true,
        backgroundColor: '#cccccc',
        viewport: {
            debugRender: true,
        },
        showControls: true,
    });

    return

;
};

A: I solved this problem like this in my case. There is no exported member named spine in spine-player.
import React from 'react';
import { SpinePlayer } from '@esotericsoftware/spine-player';

const Character = () => {

    var jsonUrl = 'assets/Vi.json';
    var atlasUrl = 'assets/Vi.atlas';

    new SpinePlayer('player-container', {
        jsonUrl: jsonUrl,
        atlasUrl: atlasUrl,
        animation: 'jump',
        premultipliedAlpha: true,
        backgroundColor: '#cccccc',
        viewport: {
            debugRender: true,
        },
        showControls: true,
    });

    return

;
};


text:
Q: Is the mobile viewport size based on browser or the screen resolution? Are the viewport in mobile phones based on the screen resolution or the mobile browser?
Here are some popular mobile browser viewport sizes:
-Opera Mobile browser viewport 850px
-iPhone safari browser viewport 980px
-iPad (landscape & portrait mode) viewport 980px
mobile device?
-Android browser viewport 800px
-IE mobile browser viewport 320px
source.
But is the viewport size scaled by resolution of the

A: The mobile viewport size is based on the the CSS pixel ratio,
 for example,
My device(Mi A1) has a resolution of 1080x1920 with 2.55 CSS pixel ratio,
the viewport on this device is calculated as

( 1080 / 2.55 ) x ( 1920 / 2.55 ) =  424 x 753.

A pixel ratio of 2.55 means for every 2.55 physical pixels on the device,CSS maps 1 pixel.
As today's mobiles have higher resolution on small screens,
The media queries in CSS refer to the calculated viewport and not the physical resolution while rendering pages on mobile phones to give a larger view of the page due to small real estate of the mobiles.
Whereas, this is not the case with laptops because with higher resolution they come with larger real estate.
My laptop has a screen resolution of 1366x768 pixels and when I check it's viewport size that to turns out to be 1366x768 on default zoom (when viewed full-screen).
Check yours on this pen

Changes with zoom-in and zoom-out

A: Technically, mobile devices feature two viewport sizes, the layout viewport and the visual viewport.
The layout viewport is fixed as it is based on the width and height of the screen of the physical device. Its dimensions can be accessed with the screen.width and screen.height properties in JavaScript and device-width for the purpose of media queries in CSS3.
The visual viewport is determined by the width and height of the browser window. Its dimensions can be accessed with the window.innerWidth and window.innerHeight properties in JavaScript and width for the purpose of media queries in CSS3.


text:
Q: One number is removed from the set of integers from $1$ to $n.$ The average of the remaining numbers is $163/4.$ Which integer was removed?
One number is removed from the set of integers from $1$ to $n.$ The average of the remaining numbers is $\dfrac{163}4$.  Which integer was removed?

Source. British Mathematical Olympiad 2010/11, Round 1, Problem 1
I was hoping if someone could spot the flaw in my working for this question.
Attempt.
I began by letting the integer that was removed be $x$.
Then: $$\frac{1 + 2 + \cdots + (x-1) + (x+1) +\cdots + n} {n-1} = \frac{163}{4}$$
There is two arithmetic sums in the denominator, the first from 1 to $x$ and the second from $x+1$ to $n$.
These are equal to $\frac{x(x-1)}{2}$ and $\frac{(n-x)(n+x+1)}{2}$, and subbing in to first equation this gives:
$$\frac{x(x-1) + (n-x)(n+x+1)}{2(n-1)} = \frac{163}{4}$$
which reduces to:
$$\frac{n^2 + n - 2x}{2(n-1)} = \frac {163}{4}$$
And then:
$$2(n^2 + n -2x) = 163(n-1)$$
At first I thought you could consider factors, as 163 was prime then:
$n-1 = 2$ giving $n = 3$ and $n^2 + n - 2x = 163$, which using $n=3$ gives $x= -75.5$ which isn't our positive integer.
I then tried considering a quadratic in $n$ and using the discriminant but again that just looked to give a negative value of $x.$ I would be grateful for any help

A: We know that $n$ is odd. Notice that
$$ n^2 - n \leq n^2 + n -2x \leq n^2 +n - 2 $$
$$ \implies n^2 - n \leq \frac{163}{2}(n-1) \leq n^2 +n - 2  $$
which gives us $n \geq 79.5$ and $n\leq 81.5$, so $n=81$

A: This is not how you are supposed to solve it, but I feel like cheating. We have the equation $2(n^2+n-2x)=163(n-1)$, and $1\leq x\leq n$.
If you assume that $x=1$ then you solve for $n$ using the quadratic formula, and you obtain $79.5$.
If you assume that $x=n$ then you solve for $n$ you obtain $81.5$. Thus $n=80$ or $n=81$.
If $n=80$ then you can solve for $x$ and obtain $83=4x$, wrong. So $n=81$. Solving again yields $4n=244$, and ding ding, we have a winner.

As everyone else seems to have done this in the way I considered cheating, I should expand on the way I initially did it, which is completely different.
We have $2(n^2+n-2x)=163(n-1)$, and $1\leq x\leq n$. We see that $n$ is odd, so $n=2m+1$. Substituting in and cancelling the 2s yields
$$(2m+1)^2+(2m+1)-2x=163m$$
or
$$4m^2+2-2x=157m.$$
Write $y=x-1$ and also, the LHS is even, so $m=2a$ is even. More substituting  and removing the $2$ from both sides yields
$$8a^2-y=157a.$$
The crucial point: we see that $a\mid y$. Since $n=2m+1=4a+1$, and $y$ is a multiple of $a$, $y=\alpha a$ for $\alpha$ between $1$ and $4$. Dividing through by $a$ yields
$$8a-\alpha=157.$$
Taking congruences modulo $8$ yields $\alpha\equiv 3\bmod 8$, so $\alpha=3$. Thus $y=3a$, so $x=3a+1$ and $n=4a+1$. We put this back into the top equation, $2(n^2+n-2x)=163(n-1)$, to obtain $a=20$, so $n=81$, $x=61$.

A: The average of $1,2,3,\ldots,n$ is the number halfway between the endpoints, $(n+1)/2,$ so the sum is $n(n+1)/2.$ Omitting $x$ from among $1,2,3,\ldots,n,$ we get the sum $n(n+1)/2-x.$
Thus the average of $1,2,3,\ldots,n$ must be a weighted average of $\big( n(n+1)/2-x\big)/(n-1)$ and $x,$ with respective weights $(n-1)/n$ and $1/n.$
$$
\frac{n-1} n \left( \frac{n(n+1)/2} {n-1} - \frac x {n-1} \right) + \frac 1 n\cdot x = \frac{n+1} 2
$$
Therefore we have:
\begin{align}
& \frac{n-1} n \cdot \frac{163} 4 + \frac x n = \frac{n+1} 2 \\[8pt]
& \frac{n(n+1)}{2(n-1)} - \frac x {n-1} = \frac{163} 4
\end{align}
So we get a system of two equations that is quadratic in $n$ and linear in $x.$ I'd try solving for one of those two in terms of the other and then substituting and solving the remaining equation.

A: Say you're removing $x$ from the set $1, 2, \ldots, n$.  The average of the resulting numbers will be at least $n/2$ (if you remove $n$) and at most $(n+2)/2$ (if you remove $1$.)  So we have
$$ n/2 \le 163/4 \le (n+2)/2 $$
or, multiplying through by 4,
$$ 2n \le 163 \le 2n+2. $$.
So $n = 81$.  You don't have to explicitly work out the number being removed, but it's $(1 + 2 \ldots + 81) - (163/4) \times 80$ = $(81 \times 82)/2 - (163/4) \times 80 = 61$.


text:
Q: Polymer Elements ShadowDOM child nodes - Setting style attributes dynamically I'd like some ideas on how to set a font-size to a <paper-textarea>, dynamically (i.e set font-size from JS instead of CSS).

*

*There's no default attribute in the docs for font-size.

*It looks like it can only be set via a mixin (which cannot be changed via JS).

For example, <paper-textarea>'s DOM tree looks something like this:

*

*<paper-textarea>

*

*ShadowDOM begins

*

*

*

*<textarea> <-- This is the actual textarea

Is there any way to target the child-node in it's shadowDOM via JS and set it's style directly?

An example, which of course doesn't work.

*

*I bind property fontSize to the <paper-textarea>

*Since there's no attribute fontSize to set for this particular element, it doesn't work.

<base href="https://polygit.org/components/">

<link href="polymer/polymer.html" rel="import">
<link href="paper-input/paper-textarea.html" rel="import">
<link href="paper-button/paper-button.html" rel="import">

<dom-module id="x-example">

  <template>
      <paper-textarea label="Textarea" value="{{inputData}}" font-size="{{fontSize}}"></paper-textarea>
    <paper-button class="primary" on-tap="incrementFontSize">Increment Font Size</paper-button>
  </template>

</dom-module>

<x-example></x-example>

Ideally, I would set up a fontSize observer and imperatively target the <paper-textarea>'s child node to set it's style when fontSize changes.
How can I target those nodes?
Note: I'd prefer an "official" way, if it exists. The Polymer spec changes often and flimsy hacks would tend to break when updating the library.

A: Here is one way of doing it:
<dom-module id="dynamic-style">
 <template>

 <paper-textarea on-tap="updateStyle"></paper-textarea>
</template>
</dom-module>

Dynamic styling is currently an issue with Polymer and as per recommendation updateStyles is the only method through which it will work.
And here's a working snippet based on your example:

<base href="https://polygit.org/components/">

<link href="polymer/polymer.html" rel="import">
<link href="paper-input/paper-textarea.html" rel="import">
<link href="paper-button/paper-button.html" rel="import">

<dom-module id="x-example">

  <template>
    <paper-textarea label="Textarea" value="{{inputData}}"></paper-textarea>
    <paper-button class="primary" on-tap="incrementFontSize">Increment Font Size</paper-button>
  </template>

</dom-module>

<x-example></x-example>

A: You can use plain javascript in your polymer, simply write
this.style.fontSize = Number(this.fontSize + 4)+"px"


text:
Q: Not able to call a method through reflection The following is my method and i try to call the method using Reflection in java:
@PreAuthorize("isAuthenticated() and hasPermission(#request, 'CREATE_REQUISITION')")
    @RequestMapping(method = RequestMethod.POST, value = "/trade/createrequisition")
    public @ResponseBody
    void createRequisition(@RequestBody CreateRequisitionRO[] request,
            @RequestHeader("validateOnly") boolean validateOnly) {
        logger.debug("Starting createRequisition()...");
        for (int i = 0; i < request.length; i++) {
            CreateRequisitionRO requisitionRequest = request[i];

            // FIXME this has to be removed/moved
            requisitionRequest.setFundManager(requisitionRequest.getUserId());
            // FIXME might have to search using param level as well
            SystemDefault sysDefault = dbFuncs.references.systemDefault
                    .findByCompanyAndDivisionAndPortfolio(
                            userContext.getCompany(),
                            userContext.getDivision(),
                            requisitionRequest.getPortfolio());
            requisitionRequest.setCustodianN(sysDefault.getCustodianN());

            gateKeeper.route(requisitionRequest);
        }
    }

the way i create Reflection :
public static void main(String[] args) {
        Class[] paramString = new Class[1];
        paramString[0] = String.class;

        //Object parameter
        Class[] parames = new Class[1];
        parames[0] = CreateRequisitionRO.class;

        Class booleanVal ;
        booleanVal = Boolean.class;

        Class cls;
        CreateRequisitionRO[] request = new CreateRequisitionRO[10];
        try {
            //load the HexgenWebAPI at runtime
            cls = Class.forName("com.hexgen.api.facade.HexgenWebAPI");
            Object obj = cls.newInstance();

            Method method = cls.getDeclaredMethod("createRequisition", parames,booleanVal);
            method.invoke(obj, request,true);

        }catch(Exception ex){
            ex.printStackTrace();
        }

    }

i get the following exception :
The method getDeclaredMethod(String, Class...) in the type Class is not applicable for the arguments (String, Class[], Class)

at the following line
Method method = cls.getDeclaredMethod("createRequisition", parames,booleanVal);
I understand the exception but my method argument is array of objects. if i remove array than i get NoSuchMethod Exception
how to solve this?

A: You need to pass a class of the CreateRequisitionRO array, not an array of classes: replace this
Class[] parames = new Class[1];
parames[0] = CreateRequisitionRO.class;

with this:
Class parames = CreateRequisitionRO[].class;

In addition, since the second parameter is boolean, not Boolean, you need to replace
booleanVal = Boolean.class; // The class of the wrapper Boolean

with
booleanVal = Boolean.TYPE;  // The class of the primitive boolean


text:
Q: Harmonizing regression and classification losses I'm investigating the task of training a neural network to predict one future value given a sinusoidal input. So for example, as seen in the Figure, the input signal is x and the expected output signal y. The model's output is y^. Doing the regression task is fairly straightforward, and there are a lot of choices for this problem. I'm using a simple recurrent neural network with mean-squared error (MSE) loss between y and y^.

Additionally, suppose I know that the sinusoid is made up of N modalities, e.g., at some points, the wave oscillates at 5 Hz, then 10 Hz, then back to 5 Hz, then up to 15 Hz maybe—i.e., N=3.
In this case, I have ground-truth class labels in a vector k and the model does both regression and classification, additionally outputting a vector k^. An example is shown in the Figure. As this is a multi-class problem with exclusivity, I figured binary cross entropy (BCE) loss should be relevant here.
I'm sure there is a lot of research about combining loss functions, but does just adding MSE and BCE make sense? Scaling one up or down by a factor of 10 doesn't seem to change the learning outcome too much. So I was wondering what is considered the standard approach to problems where there is a joint classification and regression objective.
Additionally, on top of just BCE, I want to penalize k^ for quickly jumping around between classes; for example, if the model guesses one class, I'd like it to stay in that one class and switch only when it's necessary. See how in the Figure, there are fast dark blue blips in k^. I would like the same solid bands as seen in k, and naive BCE loss doesn't account for that.
Appreciate any and all advice!


text:
Q: Как упорядочить элементы в таблице PrettyTable (python) Есть три списка одинаковой длины, которые генерируются динамически (всегда имеют разную длину в зависимости от действий пользователя). Например, сгенерировались три вот таких списка (первый список определяет количество строк в выводимой таблице):
line_number_dict = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
X_dict = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
maximum_dict = [2.27, 'Ошибка', 2.21, 2.06, 'Ошибка', 2.61, 1.94, 'Ошибка', 'Ошибка', 1.88]

Как вывести в PrettyTable данные так, чтобы каждый элемент списка находился в одной строке с элементом другого списка? Учитывая, что в следующий раз списки могут потом иметь другую длину.
Например, вывод должен иметь вот такой вид:

№
Значение Х
Искомое значение

1
1
2.27

2
3
'Ошибка'

3
5
2.21

4
7
2.06

5
9
'Ошибка'

6
11
2.61

7
13
1.94

8
15
'Ошибка'

9
17
'Ошибка'

10
19
1.88

A: from prettytable import PrettyTable

line_number_dict = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
X_dict = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
maximum_dict = [2.27, 'Ошибка', 2.21, 2.06, 'Ошибка', 2.61, 1.94, 'Ошибка', 'Ошибка', 1.88]

table = PrettyTable()
for colname, col in (('№', line_number_dict),
                     ('Значение X', X_dict),
                     ('Искомое значение', maximum_dict)):
    table.add_column(colname, col)
print(table.get_string())


text:
Q: Using the Windows command line, remove unwanted prefixes I have a number of files that need to be renamed without their current prefix. Unfortunately there is no strict format
01 - MYFILE.txt
02 - MYFILE - Maybe with extra hypen.mp3
333 - MYFILE.bin

These should be renamed to:
MYFILE.txt
MYFILE - Maybe with extra hypen.mp3
MYFILE.bin

Basically I want to remove any characters in class [0-9- ] i.e. any hypen, digit, space UNTIL a character is found that is not in this class.
I need to get this done using a batch file

A: @ECHO OFF
SETLOCAL
SET sourcedir=u:\test
FOR %%o IN ("%sourcedir%\*") DO (
 FOR /f "tokens=*delims=0123456789- " %%a IN ("%%~nxo") DO (
  ECHO REN "%%o" "%%a"
  IF /i NOT "%%~nxo"=="%%a" ECHO gated REN "%%o" "%%a"
 )
)
GOTO :EOF

The required commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO REN to REN to actually rename the files.
Sample source dir listing:
 Directory of u:\test

06/01/2014  08:36                 0 01 - myfile.txt
06/01/2014  08:37                 0 02 - myfile - maybe with extra hypen.mp3
06/01/2014  08:38                 0 333 - myfile.bin
06/01/2014  08:38                 0 leave me alone - I am not to change.atall

And results:
REN "u:\test\01 - myfile.txt" "myfile.txt"
REN "u:\test\02 - myfile - maybe with extra hypen.mp3" "myfile - maybe with extra hypen.mp3"
REN "u:\test\333 - myfile.bin" "myfile.bin"
REN "u:\test\leave me alone - I am not to change.atall" "leave me alone - I am not to change.atall"

edit - new gated rename line echoed to bypass attempts to rename to same name.

A: This is not to hard to accomplish using the DOS for/f command.
Assume you have a file named test.txt:
01 - MYFILE.txt
02 - MYFILE - Maybe with extra hypen.mp3
333 - MYFILE.bin

Here is a batch file that may be helpful. named test.bat in my case:
FOR /F "tokens=1,2* delims=0123456789- " %%i in (test.txt) do @echo %%i %%j %%k
set /p DUMMY=Hit ENTER to continue...

Here is the results in a cmd window:
C:\Users\Ron Fredericks\Desktop>FOR /F "tokens=1,2* delims=0123456789- " %i in (
test.txt) do @echo %i %j %k
MYFILE.txt
MYFILE Maybe with extra hypen.mp3
MYFILE.bin

C:\Users\Ron Fredericks\Desktop>set /p DUMMY=Hit ENTER to continue...
Hit ENTER to continue...


text:
Q: Install biomaRt package (R version 3.5.2) for linux (Ubuntu for Windows) I am trying to install Biomart package, and I used this code:
source("https://bioconductor.org/biocLite.R")
    biocLite("biomaRt")
    library("biomaRt")

and I get this warning message:
Warning messages:
1: In install.packages(pkgs = doing, lib = lib, ...) :
  installation of package 'curl' had non-zero exit status
2: In install.packages(pkgs = doing, lib = lib, ...) :
  installation of package 'openssl' had non-zero exit status
3: In install.packages(pkgs = doing, lib = lib, ...) :
  installation of package 'XML' had non-zero exit status
4: In install.packages(pkgs = doing, lib = lib, ...) :
  installation of package 'RCurl' had non-zero exit status
5: In install.packages(pkgs = doing, lib = lib, ...) :
  installation of package 'httr' had non-zero exit status
6: In install.packages(pkgs = doing, lib = lib, ...) :
  installation of package 'biomaRt' had non-zero exit status

Someone to help, please?
Thanks.

A: The issue here is that R needs to compile other R packages: curl, openssl, XML, RCurl. To do this, some development libraries need to be installed on your Linux platform.
You can often guess what they might be called: if R package "XXX" is a problem, you need to apt-cache search for something like libXXX-dev. Often the name includes a number too. So you can try, for example, from the command line:
sudo apt-get update
apt-cache search libcurl | grep dev

to search for libcurl development packages.
Then you can install them, for example:
sudo apt-get install libcurl4-openssl-dev

As a minimum, I think you need something like:
sudo apt-get install libcurl4-openssl-dev
sudo apt-get install libxml2-dev

Then try the R package installation again. Note any error messages, install more libraries as necessary, repeat until it works.
Web search with appropriate terms should locate more information about required system dependencies for installation.


text:
Q: create a file through a variable in bash I have this issue with a simple bash script to create a file and then log to it the output of rsync.
However, it does not work I keep getting "command not found", does not create the file and does not log to it. I get the error "/var/log/" is a directory.
#!/bin/bash
FILENAME=ram_sys4-$(date +%Y_%m_%d_%H:%M).log
touch /var/log/$(FILENAME)
date >> /var/log/$(FILENAME)
rsync -r -L -H -g -o -p -t -a --delete --verbose --log-format="%t %i %l %f %M %h %o \n" --log-file=/var/log/$(FILENAME) /root/Desktop/R/ /root/Desktop/W/
date >> /var/log/$(FILENAME)

A: The syntax $(VAR_NAME) is used in Makefiles, but not in bash. In bash, use
${VAR_NAME}

or even simpler
$VAR_NAME

A: #!/bin/bash
FILENAME=ram_sys4-$(date +%Y_%m_%d_%H:%M).log
touch /var/log/${FILENAME}
date >> /var/log/${FILENAME}
rsync -r -L -H -g -o -p -t -a --delete --verbose --log-format="%t %i %l %f %M %h %o \n" --log-file=/var/log/${FILENAME} /root/Desktop/R/ /root/Desktop/W/
date >> /var/log/${FILENAME}

$(FILENAME) is Command Substitution what you are trying do to is Parameter Expansion


text:
Q: Required values of imported type don't show in list of "Example values" I wonder what I omitted so that Swagger is not exposing public object values of type Misd\PhoneNumberBundle\Doctrine\DBAL\Types\PhoneNumberType in the list of example values? The example values when POSTing an object are as follows, despite having another public object value:
The Swagger interface showing example values
[
  {
    "username": "string",
    "password": "string",
    "id": 0
  }
]

I can manually add the field and everything works fine (the value gets posted), but it's not ideal since a required value is not listed by the documentation.
  /**
   * @AssertPhoneNumber(defaultRegion="US", message="Please specify a valid mobile phone number", type="mobile")
   * @Assert\NotBlank
   * @ORM\Column(name="phone_number", type="phone_number", unique=true)
   */
  public $phoneNumber;

What am I missing? Looking forward to getting hints on this, thank you in advance.

A: Specifying the ApiProperty as an annotation solved my problem. Simply use ApiPlatform\Core\Annotation\ApiProperty and annotate the phone number property as follows:
  /**
   * @ApiProperty(
   *     attributes={
   *         "swagger_context"={
   *             "type"="string"
   *         }
   *     }
   * )
   * @AssertPhoneNumber(defaultRegion="US", message="Please specify a valid mobile phone number", type="mobile")
   * @Assert\NotBlank
   * @ORM\Column(name="phone_number", type="phone_number", unique=true)
   */
  public $phoneNumber;


text:
Q: Cannot copy from Vim under Tmux into clipboard using "+p on Ubuntu I'm using zsh, tmux, and Vim and for some reasons recently, I've noticed I cannot copy from Vim to X clipboard under tmux using "+y. Any idea how I can troubleshoot this issue? It used to work before.

A: It returns 1. I think the problem is with tmux, using the wrong $DISPLAY env. I think I got this error, after I logged to my machine from my laptop using SSH. Here's more info on it: unix.stackexchange.com/questions/75681/… When I create a new tmux client, I can copy from Vim to clipboard, but I still can't get my detached client working, yet.


text:
Q: Automapper, map from two unrelated sources I am pulling data from a web API so I have no relationships between sources. I have a list of tickets from one method and a list of statuses from another.  The ticket model has a statusId field that relates to one of the statuses in the list of statues.  My TicketDTO has a StatusName field that I need to map from my previously populated list of statuses.
I have no idea how to do this in Automapper.  Any suggestions or examples?
Thanks in advance


text:
Q: VB.net TCP Non-Blocking State I have code that sending string from client to server with TCP Connection.
But i dont know how to convert it to NonBlocking TCP State Connection.
i have try to put socket.Blocking = FALSE, but that code give me an error.
Socket Error Code: 10035
Exception Title: A non-blocking socket operation could not be completed immediately
Heres my code for sending string from client to server.
Server Code :
Imports System.Net
Imports System.Net.Sockets
Imports System.Text

Module Module1
    Dim soket As Socket
    Sub Main()
        Try
            Dim alamatIP As IPAddress = IPAddress.Parse("127.0.0.1")
            Dim tcpListener As New TcpListener(alamatIP, 8000)
            'soket.Blocking = False - THIS WILL GIVE ME AN ERROR
            tcpListener.Start()

            System.Console.WriteLine("Server port 8000...")

            Dim myendpoint As IPEndPoint
            myendpoint = CType(tcpListener.LocalEndpoint, IPEndPoint)

            System.Console.WriteLine("IP : " + myendpoint.Address.ToString + " and port is " + myendpoint.Port.ToString)
            System.Console.WriteLine("Waiting for connection !")

            soket = tcpListener.AcceptSocket()
            myendpoint = CType(soket.RemoteEndPoint(), IPEndPoint)

            System.Console.WriteLine("Receiving from " + myendpoint.Address.ToString())

            Dim bitData(100) As Byte
            Dim newString As String = ""
            Do
                Try
                    Dim size As Integer = soket.Receive(bitData)
                    newString = Encoding.ASCII.GetString(bitData)
                    Console.WriteLine(newString)
                    Array.Clear(bitData, 0, bitData.Length)
                Catch ex As Exception
                    Console.Write(ex.ToString())
                End Try
            Loop While newString <> "exit"
            soket.Close()
            tcpListener.Stop()
        Catch ex As Exception
            Console.WriteLine("Error ..." + ex.ToString())
        End Try
        Console.ReadLine()
    End Sub

End Module

Client Code :
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports System.IO
Imports System.Threading
Module Module1

    Sub Main()
        Try
            Dim tcpClient As New TcpClient 'creating the client
            Console.WriteLine("Connecting....")
            tcpClient.Connect("127.0.0.1", 8000) 'connecting the client the server
            'port is same as in the server
            Console.WriteLine("Connected")
            Console.WriteLine("Enter the string to be transmitted : ")

            Dim strMessage As String
            Dim stm As Stream
            Dim counter As Integer = 0

            Do

                stm = tcpClient.GetStream() 'getting the stream of the client
                Dim ascenc As New ASCIIEncoding
                strMessage = Console.ReadLine()
                Dim byteData() As Byte = ascenc.GetBytes(strMessage)
                Console.WriteLine("Transmitted ")
                stm.Write(byteData, 0, byteData.Length())

            Loop While strMessage <> "exit"

                    tcpClient.Close() 'closing the connection
        Catch ex As Exception
            Console.WriteLine("Error..." + ex.StackTrace.ToString()) 'writing the exception into the console
        End Try
    End Sub

End Module

Thanks for any help.

A: When you attempt to read from a non-blocking socket or write to it and the operation cannot be completed right now, then the socket is supposed to signal an error. In VB it means it is supposed to raise an exception. For example, this happens when your machine hasn't received any data but you try to Read something.
Before trying an operation on a non-blocking socket, call Select or Poll in order to make sure it is ready for the operation.


text:
Q: SMS integration in yii I am trying to integrate SMS in my web application. I added the code in my last line of function:
header("Location:http://www.bulksmsservice.co.in");

But its not redirecting to that site. (Function is in model page)

A: If you use the PHP Command header, be sure there is no output before you call it. To do it in the Yii view file is too late. But to do this in the Yii Controller is not a good Practice. Better would be $this->redirect() or in the view File use Javascript Code:
<script>
    window.location ='http://www.bulksmsservice.co.in';
</script>

A: i added my function sendbulk in controller and replace code with below
 function sendbulk($num,$msg)
 {
    $link = "http://www.bulksmsservice.co.in/api/sentsms.php?username=****&api_password=*******&to=".$no."&priority=2&sender=******&message=".$msg. "&unicode=1";
   $ctx = stream_context_create(array(
        'http' => array(
            'timeout' => 1
       )
            )
    );
    file_get_contents($link, 0, $ctx);
  }

Now it's working perfectly for single messages and multiple messages :)


text:
Q: How to send excel file directly to printer or print html code? I have an ASP.Net 3.5 (C#) site that loads an excel file and then I want to print on a label printer at teh user's default printer?

*

*Excel File is populated on sheet1

*Print Area has been set in the file

*When I print from excel to the label printer it prints fine.

I would like to send the excel file to the user's default printer. and have it automatically print the print area or the first sheet.
I would be open to sending a HTML String that has my data formatted in a table if that is possible.  That would eliminate any need for the excel file.
Microsoft Excel is not installed on the webserver so using the Excel Refrence is out.  But I do have the Microsoft Office SDK 2.0 and can use that if needed.
Thanks in advance for any tips or any directions.

A: Anything you could do manually, you can record using the macro recorder and figure out the code. Here is a generated code for sending files to my printer:
Application.ActivePrinter = "HP LaserJet P2014 on Ne03:"
ExecuteExcel4Macro "PRINT(1,,,1,,,,,,,,2,""HP LaserJet P2014 on Ne03:"",,TRUE,,FALSE)"

You could change the variables to match your own printer


text:
Q: complex query as source I have a query to be used as source. but this is a huge query containing lot of temp tables created and finally joining which brings select data. So I used Script Task for this query which works perfectly. Is there any other way instead of Script task ?

A: If you use CTEs instead of temp tables you can directly use it as a source query in the OLE DB Source.

A: Alternatively, you could keep your current logic in a script task but then insert the data from the final select into a temporary (physical) table.  The data flow task could then do a simple select directly on that temp table.


text:
Q: Why my bcp query out not work in sql server? I'm new in sql server and want to save select query into the csv file using with bcp query out  for that purpose write this query:
declare @cmd as nchar(50)
SET @cmd = 'bcp  select *from [behzad].[dbo].[behzad] queryout "d:\spt_values.dat" -U behbeh -P beh1368421 '
EXEC master..XP_CMDSHELL @cmd

but i get this output:

How can i solve this problem?thanks.

A: As you are using queryout your source must be a query.
As a query has got blanks, you have to quote it:
Further more your @cmd nchar(50) is to short and will probably truncate your command.
Try this:
declare @cmd as nchar(500)
SET @cmd = 'bcp  "select * from [behzad].[dbo].[behzad]" queryout "d:\spt_values.dat" -U behbeh -P beh1368421 '
EXEC master..XP_CMDSHELL @cmd

With a SELECT * FROM ... query it was easier actually, to use the 3-part-qualified table name together with out instead of a SELECT ... with queryout...


text:
Q: tikz: draw arrow till above of middle of below rectangle How to take the arrow just above the middle of rectangle R2 and down to R2.north (at center of top)?
\documentclass[a4paper]{scrartcl}
\usepackage{amsmath,amssymb,amsfonts}
\usepackage{tikz}
\usepackage{tikz-uml}
\usetikzlibrary{shapes.multipart,positioning,fit}
\usepackage{pgf-umlsd}
\usetikzlibrary{arrows}

    \begin{document}
    \begin{tikzpicture}
        \node[text width=3cm]                       (A)  at (0,0)               {\tiny AAA};

        \node[anchor=north west , text width=1cm]   (A1) at (A.south west)      {\tiny BBB};
        \node[anchor=west       , text width=1cm]   (A2) at (A1.east)           {\tiny CCC};
        \node[anchor=west       , text width=1cm]   (A3) at (A2.east)           {\tiny DDD};

        \node[anchor=north west , text width=1cm]   (A4) at (A1.south west)     {\tiny EEE};
        \node[anchor=west       , text width=1cm]   (A5) at (A4.east)           {\tiny FFF};
        \node[anchor=west       , text width=1cm]   (A6) at (A5.east)           {\tiny };

        \node [inner sep=0pt,
        draw,
        rounded corners,
        fit = (A)(A1)(A2)(A3)(A4)(A5)(A6)
        ] (A13) {};

        \draw   (A1.north west) -- (A3.north east)
        (A1.south west) -- (A3.south east);

        \node[below left = 1.0cm and 0.5cm of A13.south, text width=1cm]    (B1) {\tiny GGG};
        \node[below =0cm of B1, text width=1cm] (B2) {\tiny HHH};
        \node [inner sep=0pt,
        draw,
        rounded corners,
        fit = (B1)(B2)
        ] (B6) {};

        \draw[gray,->] (A6.center)  -- ++(east:1.0) -- ++(down:0.5) -- ++(west:1.5) -- ++(down:0.4);

    \end{tikzpicture}
    \end{document}

A: For this, you can make use of the -| connector, which (unlike -- that draws just a straight line connecting two nodes) draws first a horizontal and than a vertical line, so that two nodes are connected at right angles. There is also the counterpart |- that first draws the vertical line. Then, you can easily let the arrow end right on top of B6 (which is how you named in the code the node you denoted with R2 in your picture) using B6.north.
The full code would then be (I commented out two packages that are not needed and of which I don't have the first one anyways):
\documentclass[a4paper]{scrartcl}
\usepackage{amsmath,amssymb,amsfonts}
\usepackage{tikz}
%\usepackage{tikz-uml}
\usetikzlibrary{shapes.multipart,positioning,fit}
%\usepackage{pgf-umlsd}
\usetikzlibrary{arrows}

\begin{document}
    \begin{tikzpicture}
        \node[text width=3cm]                       (A)  at (0,0)               {\tiny AAA};

        \node[anchor=north west , text width=1cm]   (A1) at (A.south west)      {\tiny BBB};
        \node[anchor=west       , text width=1cm]   (A2) at (A1.east)           {\tiny CCC};
        \node[anchor=west       , text width=1cm]   (A3) at (A2.east)           {\tiny DDD};

        \node[anchor=north west , text width=1cm]   (A4) at (A1.south west)     {\tiny EEE};
        \node[anchor=west       , text width=1cm]   (A5) at (A4.east)           {\tiny FFF};
        \node[anchor=west       , text width=1cm]   (A6) at (A5.east)           {\tiny };

        \node [inner sep=0pt,
        draw,
        rounded corners,
        fit = (A)(A1)(A2)(A3)(A4)(A5)(A6)
        ] (A13) {};

        \draw   (A1.north west) -- (A3.north east)
        (A1.south west) -- (A3.south east);

        \node[below left = 1.0cm and 0.5cm of A13.south, text width=1cm]    (B1) {\tiny GGG};
        \node[below =0cm of B1, text width=1cm] (B2) {\tiny HHH};
        \node [inner sep=0pt,
        draw,
        rounded corners,
        fit = (B1)(B2)
        ] (B6) {};

        \draw[gray,->] (A6.center)  -- ++(east:1.0) -- ++(down:0.5) -- ++(west:1.5) -| (B6.north);

    \end{tikzpicture}
\end{document}


text:
Q: Is it possible to add markdown to the OS X Server blog editor? I recently installed OS X Server and have enabled the wiki/blog functionality.
Is it possible to add markdown to the blog editor?
If not, is there software that integrated with the blog functionality and provides a markdown editor as part of a native OS X application?

A: I reviewed an edition of the server guide and see no markdown support anywhere, so I think you may have to go with another tool that easily exports into other formats.
I'd recommend running with Markdown Service Tools to start. It's all you need to stick to markdown on a mac. If you like GUIs like I do, you may also like using MacDown to write in markdown and export however you need it. It's a great open-source solution to the problem.


text:
Q: How to filter or query list of index names in Elasticsearch? I use the following to list indices
curl localhost:9200/_cat/indices?v

Is there is any way to filter or query index names, for example like with wildcards?
curl localhost:9200/_cat/indices - d '{
  "query": {
    "prefix": {
      "index": "sam-"
    }
  }
}'

What would be the format in elasticsearch.js?

A: Simple: curl localhost:9200/_cat/indices/sam-*?v

A: It should be like that:
curl -X GET "127.0.0.1:9200/_cat/indices/sam-*?v&s=index"