text:
Q: Get Facebook friends who've installed my app problems I just released an iOS app that has Facebook integration, and /me/friends is not working as I expected.  When a new user logs in (or an existing user for that matter) and I use "startWithGraphPath:" to get the users' friends', I only receive people who were friends prior to us deploying the application.  So, the API call works, friends are returned, but not all the friends that I know are using the app.
Does anyone know if there's a significant time lag to this working?
On the app developer page it shows a green light and that the app is available to all users.
On the status page it says user_friends is an available permission.
Why would I get some users, but not all?  I used my wife's phone to sign on to the application, but yet when I ask for friends, she is not returned.
Any insight is appreciated.
Ken


text:
Q: My Python-Java Interface, good design? And how to wrap JNI Functions? I'm going to write my own Python-Java interface. It is compiled as a DLL and
wrapped using ctypes.
Yet, it is possible to find Java-classes and allocate Java-objects.
But what would be an interface to another language without using those objects
methods? My aim is to make this as natural as possible. Unfortunately,
it isn't just possible to find Java-methods only by name.
My model is the following:
JClass

*

*An instance of this class represents a Java class.

JObject

*

*An instance of this class represents a Java-object. It has to be
initialized with a JClass-instance. (yet, of course, later there
should be arguments for the constructor also.)

JMethod

*

*Represents a method of a Java-object. It contains the name and signature of the desired method. The signature is evaluated dynamically by the classes that are given on initialization.
Example:
mainMethod  = JMethod('main', JStringArray)

Note that JStringArray is an instance of JClass that represents a string-array.
A JMethod can be added to a JClass instance. But can then be called only from an instantiated JObject.
JStaticMethod

*

*Just like the JMethod, but it can also be called from a JClass
instance.

Built-In types

*

*I'm doing JInt, JShort, JLont, JChar, etc.. to be the
built-in wrapper types.
Like:
JInt    = JClass('java/lang/Integer')
JShort  = JClass('java/lang/Short')
JString = JClass('java/lang/String')

Question(s):

*

*What do you think about this design?

*The JNI-Functions for calling methods of a Java-class / -object all
   take a variable amount of arguments. After reading several topics on
   calling a function with variable arguments from a function that does so,
   and also asked a question here on SO, I'm aware that this is not possible.
   Now, are there functions that don't take a variable number of arguments
   but a va_list or something? I just need to find some way to call a method from Python in Java!

A: 1. What do I think of this design?

*

*it's not clear what actual problem you're trying to solve.

*what about edge cases; error-handling; forward-/backward-compatibility; bugs in Python/Java?  Not fun, but essential for robust software.

*mixing two languages is hard enough, mixing three is sure to be much much worse.  I would expect major maintainability and coupling problems.

*there are already solutions to these problems.  RPC, for getting programs in different languages to talk to each other.  Jython, for Java/Python interoperability.  I believe, Jython even allows you to create Python objects in Java and vice versa directly.  Clarifying any shortcomings of these existing systems, and how you would address these shortcomings, would be helpful.
Here are a few missing things:

*

*packages

*privacy

*interfaces/abstract classes

*method resolution:  overloads and overrides(especially when more than one method would match)

*exceptions

*type-checking, or recovering from type errors

2. I just need to find some way to call a method from Python in Java!  What about Jython, RPC, or just calling an executable?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Problem with export (download) into Excel-format with accented (central-european) charecters I found and have read many answers here, but unfortunately none works for me. :(
So: I wanna export (and download) the array into Excel-format. Actually I try into CSV with .xls extension. But unfortunately only the following two cases occur:

*

*OR the accented letters are well, but the columns are not separated (tab char is like a "normal" char)

*OR the cell-separating is working, but the accented characters are wrong coded

I tried probably all the encodings, content-types, output-tpye (I mean bare echo, php://output, file-read etc.) with so many headers, but none of them works.


text:
Q: Jenkins/Hudson - Run script on all slaves I have a requirement to run a script on all available slave machines. Primarily this is so they get relevant windows hotfixes and new 3rd party tools before building.
The script I have can be run multiple times without undesirable side effects & is quite light weight, so I'm happy for this to be brute force if necessary.
Can anybody give suggestions as to how to ensure that a slave is 'up-to-date' before it works on a job?
I'm happy with solutions that are driven by a job on the master, or ones which can inject the task (automatically) before normal slave job processing.

A: My shop does this as part of the slave launch process.  We have the slaves configured to launch via execution of a command on the master; this command runs a shell script that rsync's the latest tool files to the slave and then launches the slave process.  When there is a tool update, all we need to do is to restart the slaves or the master.
However - we use Linux whereas it looks like you are on Windows, so I'm not sure what the equivalent solution would be for you.

A: To your title: either use Parameter Plugin or use matrix configuration and list your nodes in it.
To your question about ensuring a slave is reliable, we mark it with a 'testbox' label and try out a variety of jobs on it. You could also have a job that is deployed to all of them and have the job take the machine offline it fails, I imagine.
Using Windows for slaves is very obnoxious for us too :(


text:
Q: Copy and paste an excel file with variable name What I want to design is a file which can copy and paste a file in the active worksheet. However, this file will be updated daily and also change its name. Therefore, I'd like to refer to a dynamic name so to say.
Sub stackoverflow()

' copy workbook to new worksheet

    Workbooks.Open Filename:= _
    "/Documents/Documenten/movementreport202001075.xlsx"
    Cells.Select
    Selection.Copy
    Windows("test").Activate
    ActiveSheet.Paste

End Sub

For instance, the "20200107" can be "20200108.xlsx" tomorrow. So it is dependent on the date, time and seconds you download the report.

A: You can use the format function to put it into the format you want:
Workbooks.Open Filename:= "/Documents/Documenten/" & Format$(Date, "d.m.yyyy") & ".xlsx"

Seems like you would want to use a drive letter too tho...
Update:
It's the same concept (all you are doing is formatting the date and concatenating string values):
Workbooks.Open Filename:= "/Documents/Documenten/movementreport" & Format$(Date, "dmyyyy") & ".xlsx"

see how that works now?
I still say you would probably want to use a drive letter too tho...


text:
Q: Displaying one element over another without losing ability to click the lower element The "general" question....
If I have two HTML elements using z-index, one on top of the other, the bottom one becomes unclickable.  The bottom one, however, is the main content.  The top one is translucent and must be displayed over the bottom one.
...
My specific problem....
I'm trying to develop a web app that can be controlled with a leap motion device.
I'm using an SVG over the top of a web page to display the user's fingertips as cursors (with the leap motion device).  I need the SVG to display over the web page...but I need the webpage itself to be clickable, of course.
I guess what I'm asking is...is there a way to display the SVG on top (covering the entire page) but still make the page underneath it usable?  I understand z-index is probably not the answer here, but I'm not sure what is.  I've found similar problems here, but most of the solutions are "don't have one element displayed over the other."
I'm also fine with "use something else as a cursor" as an answer if there's a better way to do that, but I'm sure my specific problem isn't the only application for wanting a lower element to be the one with focus.
Here's a quick fiddle of the code below to demonstrate:
http://jsfiddle.net/mmarkey/v5B9a/7/

A hyperlink to google

A hyperlink to amazon

A hyperlink to yahoo

A hyperlink to facebook

A hyperlink to bing

<svg class="top" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
    <circle cx="10" cy="25" r="10" fill="rgba(20,130,150,0.80)" />
    <circle cx="45" cy="40" r="10" fill="rgba(20,130,150,0.80)" />
    <circle cx="70" cy="50" r="10" fill="rgba(20,130,150,0.80)" />
    <circle cx="100" cy="10" r="10" fill="rgba(20,130,150,0.80)" />
</svg>

.bottom {
    background: #CCCCFF;
    position: absolute;
    z-index: 1;
    width: 100%;
    height: 100%;
}
.top {
    position: fixed;
    z-index:10;
}

A: In css you can use pointer-events:none; to allow it to click through.
Not sure if it works in all browsers.
http://jsfiddle.net/v5B9a/9/

A: See the similar question here: https://stackoverflow.com/a/17655894/2500474.
Here is the IE workaround:
var x = event.pageX;
var y = event.pageY;
$('.cursor').hide();
var here = document.elementFromPoint(x, y);
$('.cursor').show();
// Do what you want with the element here
$(here).click();

Hope this help


text:
Q: Strange behaviour of gnu make I have a simple Makefile (just for testing)
define my_macro
var_$(1) := $(1)
$(warning $(var_$(1)))
$(warning $(var_some_value))
endef

$(eval $(call my_macro,some_value))
$(warning $(var_some_value))

Gnu make (v 3.80) produces:
Makefile:8:
Makefile:8:
Makefile:10: some_value

Why first and even second warnings don't print anything ?

A: As the manual says, The argument to the eval function is expanded, then the results of that expansion are parsed as makefile syntax.
That means the eval gets expanded to this by substituting some_value for $(1) in the macro:
var_some_value := some_value
$(warning $(var_some_value))
$(warning $(var_some_value))

then the variable $(var_some_value) gets expanded, but at this point the result of the macro expansion has not been evaluated as makefile syntax yet, so the variable has not been set. That means it expands to:
var_some_value := some_value
$(warning )
$(warning )

Then finally that expanded text is processed as makefile syntax, so the variable gets defined, then the empty warnings get printed.


text:
Q: retrieving last message when joining 3 tables I'm currently retrieving data from 3 different tables. One of those tables contain messages sent which relates to each ID.
What I'm currently trying to do but have been unsuccessful is retrieve the last message on record for each ID.
Help please-
select
   C.id ,
   C.business,
   AP.firstname,
   AP.lastname,
   M.comments,
   M.dateread
from
   claims C
JOIN
   affected_people AP
      ON C.ID = AP.claimid
join
   Messages M
      on M.claimid = C.ID

A: Not sure, if that works for mysql:
select *
from(
    select
       C.id ,
       C.business,
       AP.firstname,
       AP.lastname,
       M.comments,
       M.dateread,
       max(M.dateread) over (partition by c.id)  max_dateread
    from
       claims C
    JOIN
       affected_people AP
          ON C.ID = AP.claimid
    join
       Messages M
          on M.claimid = C.ID)
          where max_dateread=dateread

A: Just add in
Order by M.dateread desc


text:
Q: What is this function declaration saying? new to Javascript.
Was playing around with a controller for a calculator and came across this function definition. Its bizarre, and I'm hoping someone might be able to clarify this. Why is number repeated here?
function calculationCommission(monthlyRevenue: number): number {

//function does stuff

}

A: First number is type of argument of function that will receive and second one is type of function return.
In this situation both are number


text:
Q: Ways to cross out $n^2/2$ squares on a $n\times n$ chessboard How many patterns $P_n$ are there to cross out $n^2/2$ squares on a $n\times n$ chessboard, so that the number of crossed out squares in each row and each column are all even?
Is there a way to get a general formula for $P_n$? Or, at least, a formula when $n$ is big?
For example, if $n = 4$, the answer could be found as $ P_4 = 246$ by listing all probabilities


text:
Q: Solving a matrix equation Let $\alpha \in \mathbb{R}$, $(\,u \ \ v \ \ w\,)^\textrm{t} \in \mathbb{R}^3$, $S = S^\textrm{t} \in \mathbb{R}^{3 \times 3}$ with
$$\alpha + (\,u \ \ v \ \ w\,)\,S\, \left(\begin{matrix}u \\ v \\ w\end{matrix}\right)= 0 \hspace{0.2in} \textrm{whenever} \hspace{0.2in} u^2 + v^2 + w^2 = 1.$$
Note that 't' denotes matrix transpose. Show that $$S = -\alpha I,$$ where $I$ is the $3 \times 3$ identity matrix.

A: $$ \alpha + (\,u \ \ v \ \ w\,)\,S\, \left(\begin{matrix}u \\ v \\ w\end{matrix}\right)= 0 $$
By  $ x \cdot Ay = A^Tx \cdot y $
$$ \alpha + \,S\,^T(\,u \ \ v \ \ w\,) \left(\begin{matrix}u \\ v \\ w\end{matrix}\right)= 0 $$
By $ u^2 + v^2 + w^2 = 1 $ and associatvity
$$ \alpha + \,S\,^T = 0  $$
By $ S = S^T $
$$ \alpha + \,S\ = 0  $$
wrapping things up
$$ \alpha I + \,S\ I = 0 I  $$
$$  S = -\alpha I $$


text:
Q: Can't read environment variables in Heroku I'm trying to deploy an app to Heroku. It's building correctly (using the heroku nodejs buildpack), but I can't access Heroku's environment variables. This is the environment file that is being used:
import * as process from 'process'

console.log(process); // Object containing numerous props (cwd, chdir, browser, etc.)
console.log(process.env); // Empty object but NOT undefined
console.log(process.env.BACKEND_URL); // Undefined

export const environment = {
    production: true,
    baseUrl: process.env.BACKEND_URL,
    apiBaseUrl: process.env.BACKEND_URL + '/api/v1/',
    cmsBaseUrl:  process.env.BACKEND_URL + '/content/pages/',
    verboseApiCalls: false
};

Build command that is being run:
"postinstall": "ng build --aot --prod && npm install -g serve",
Angular.json:
{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "front-end": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "prefix": "app",
      "schematics": {},
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/front-end",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.app.json",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "stylePreprocessorOptions": {
              "includePaths": [
                "src/assets/styles/partials"
              ]
            },
            "styles": [
              "src/styles-app-loading.scss",
              "src/assets/styles/catch.scss",
              "src/styles.css"
            ],
            "scripts": []
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true
            },
            "local": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.local.ts"
                }
              ],
              "optimization": false,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": false,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": false
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "front-end:build",
            "disableHostCheck": true
          },
          "configurations": {
            "production": {
              "browserTarget": "front-end:build:production"
            },
            "local": {
              "browserTarget": "front-end:build:local"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "front-end:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.spec.json",
            "karmaConfig": "src/karma.conf.js",
            "styles": [
              "src/styles.css"
            ],
            "stylePreprocessorOptions": {
              "includePaths": [
                "src/assets/styles/partials"
              ]
            },
            "scripts": [],
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ]
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "src/tsconfig.app.json",
              "src/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    },
    "front-end-e2e": {
      "root": "e2e/",
      "projectType": "application",
      "architect": {
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "front-end:serve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "front-end:serve:production"
            }
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": "e2e/tsconfig.e2e.json",
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    }
  },
  "defaultProject": "front-end"
}

Package.json: (dont really know if it's relevant)
{
  "name": "front-end",
  "version": "0.1.0",
  "scripts": {
    "ng": "ng",
    "build": "ng build",
    "test": "ng test",
    "postinstall": "ng build --aot --prod && npm install -g serve",
    "start": "serve dist/front-end/ -l $PORT",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^7.1.3",
    "@angular/cdk": "^7.1.1",
    "@angular/cli": "~7.1.2",
    "@angular/common": "^7.1.3",
    "@angular/compiler": "^7.1.3",
    "@angular/core": "^7.1.3",
    "@angular/flex-layout": "^7.0.0-beta.21",
    "@angular/forms": "^7.1.3",
    "@angular/http": "^7.1.3",
    "@angular/material": "^7.1.1",
    "@angular/platform-browser": "^7.1.3",
    "@angular/platform-browser-dynamic": "^7.1.3",
    "@angular/router": "^7.1.3",
    "@swimlane/ngx-charts": "^10.0.0",
    "classlist.js": "^1.1.20150312",
    "core-js": "^2.5.4",
    "rxjs": "^6.0.0",
    "typescript": "~3.1.6",
    "zone.js": "^0.8.26"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^0.13.2",
    "@angular/cli": "~7.1.2",
    "@angular/compiler-cli": "^7.2.5",
    "@angular/language-service": "^7.1.3",
    "@types/jasmine": "~2.8.6",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "~8.9.4",
    "codelyzer": "~4.2.1",
    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~1.7.1",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.0",
    "karma-jasmine": "~1.1.1",
    "karma-jasmine-html-reporter": "^0.2.2",
    "karma-spec-reporter": "0.0.32",
    "protractor": "^5.4.1",
    "ts-node": "~5.0.1",
    "tslint": "~5.9.1",
    "typescript": "~3.1.6"
  },
  "engines": {
    "node": "10.3.0"
  }
}

I tried this answer, but could not find the referenced modules anywhere. I really don't know where to look, so any help would be appreciated.

A: You can use the app.json file (doc).
When you want to deploy an app to Heroku, the app.json is read and env variables are set. Moreover you can specify the build, the addons (for example postgres) and the post-script commands that you want to execute.
Here is an example for your project :
    {
       "name": "Example",
       "description": "This app does one little thing",
       "success_url": "/",
       "scripts": {
          "postdeploy": "database create && database update"
         },
      "env": {
        "production": "true",
        "verboseApiCalls": "false"
      }
  }

One more step :), I push my app.json on my remote repository (github), and to deploy the app juste use the following url :
https://heroku.com/deploy?template=https://github.com/yourNameOrOrganisation/yourRepository

Don't forget also to add a Procfile.
Hope it helps ;)


text:
Q: Can we able to access local Whatsapp messages from my app in react native? Can we able to get the Whatsapp messages when someone sends a message to my app?

A: The answer is "NOT POSSIBLE"
Whatsapp uses end to end encrypted msgs and even you have no api to access whatsapp data.


text:
Q: Node.js - Execute functions one by one I am trying to run these functions one by one, after it will execute first function move to second one and so on .. now it will render both functions at the same time, it is taking so much memory when there are over 3000 functions.
webshot('google.com', 'google.jpeg', options, function(err) {});
webshot('yahoo.com', 'yahoo.jpeg', options, function(err) {});

A: That last argument to each of those is called a "callback;" it gets called when the work has been finished. So if you want to do these one at a time, put the call to the next one inside the callback of the previous one:
webshot('google.com', 'google.jpeg', options, function(err) {
    webshot('yahoo.com', 'yahoo.jpeg', options, function(err) {});
});

Of course, if you have a bunch of these (you mentioned 3000!), you're not just going to nest them like that. I would probably create an array of the arguments you want to pass them, and then use a callback loop:
function process(list, callback) {
    var index = 0;

    doOne();

    function doOne() {
        var entry = list[index++];
        webshot(entry.domain, entry.img, entry.options, function(err) {
            // ...error handling, etc...
            if (index < list.length) {
                doOne();
            } else {
                callback();
            }
        });
    }
}
var webshots = [
    {domain: 'google.com', img: 'google.jpeg', options: options},
    {domain: 'yahoo.com', img: 'yahoo.jpeg', options: options},
    // ...
];
process(webshots, function() {
    // All done
});

Side note: This would be a bit cleaner with Promises. There are various libraries that will promise-ify Node-style callback APIs (like webshot's), you might look at doing that.
If you did, you could handle those promises like this:
var webshots = [
    {domain: 'google.com', img: 'google.jpeg', options: options},
    {domain: 'yahoo.com', img: 'yahoo.jpeg', options: options},
    // ...
];
allDone = webshots.reduce(function(p, entry) {
    return p.then(function() {
        return promisifiedWebshot(entry.domain, entry.img, entry.options);
    });
}, Promise.resolve());
allDone.then(function() {
           // All done
       })
       .catch(function() {
           // Handle error
       });

A: You can use a control flow library like async:
'use strict';

const async = require('async');

async.series([
    (callback) => {
        webshot('google.com', 'google.jpeg', options, callback);
    },
    (callback) => {
        webshot('yahoo.com', 'yahoo.jpeg', options, callback);
    }
], (error) => {
    if(error) {
        console.log('Error: ' + error);
    }
});

There are also utilities function like map, each, eachOf to allow you to directly iterate throught your list of url and apply to the call:
'use strict';

const async = require('async'),
    urls = [
        {url: 'google.com', img: 'google.jpeg'},
        {url: 'yahoo.com', img: 'yahoo.jpeg'}
    ];

async.map(urls, (url, callback) => {
    webshot(url.url, url.img, options, callback);
    //I presumed webshot call the callback like callback(error, result)
}, (error, webshots) => {
    //If a error occured, async will skip there and error will be set
    //Else, webshots will be a array of all the results
});


text:
Q: what is the problem with my code linreg.predict() not giving out right answer? SO The question given to me was
Write a function that fits a polynomial LinearRegression model on the training data X_train for degrees 1, 3, 6, and 9. (Use PolynomialFeatures in sklearn.preprocessing to create the polynomial features and then fit a linear regression model) For each model, find 100 predicted values over the interval x = 0 to 10 (e.g. np.linspace(0,10,100)) and store this in a numpy array. The first row of this array should correspond to the output from the model trained on degree 1, the second row degree 3, the third row degree 6, and the fourth row degree 9.
So tried the problem myself and failed and saw some other persons GitHub code and was very similar to me but it worked.
So what is the difference between my code and the other person code?
Here is some basic code prior to my question
np.random.seed(0)
n = 15
x = np.linspace(0,10,n) + np.random.randn(n)/5
y = np.sin(x)+x/6 + np.random.randn(n)/10

X_train, X_test, y_train, y_test = train_test_split(x, y, random_state=0)

Here is my approach
pred=np.linspace(0,10,100).reshape(100,1)
k=np.zeros((4,100))

for count,i in enumerate([1,3,6,9]):
    poly = PolynomialFeatures(degree=i)
    X_poly = poly.fit_transform(X_train.reshape(-1,1))
    linreg = LinearRegression()
    linreg.fit(X_poly,y_train.reshape(-1,1))
    pred = poly.fit_transform(pred.reshape(-1,1))
    t=linreg.predict(pred)
    #print(t)                      #used for debugging
    print("###   ****   ####")     #used for debugging
    k[count,:]=t.reshape(1,-1)

print(k)

Here is the code that works
result = np.zeros((4, 100))
for i, degree in enumerate([1, 3, 6, 9]):
    poly = PolynomialFeatures(degree=degree)
    X_poly = poly.fit_transform(X_train.reshape(11,1))
    linreg = LinearRegression().fit(X_poly, y_train)
    y=linreg.predict(poly.fit_transform(np.linspace(0,10,100).reshape(100,1)))
    result[i, :] = y
print(result)

My approach got an error
     13     print("###   ****   ####")
---> 14     k[count,:]=t.reshape(1,-1)
     15
     16

ValueError: could not broadcast input array from shape (200) into shape (100)

While other code worked fine

A: The difference lies in the argument for linreg.predict. You are overwriting your pred variable with the result of poly.fit_transform, which changes it's shape from (100,1) to (200,2) in the first iteration of the loop. In the second iteration, t does not fit into k anymore, resulting in the error you are facing.


text:
Q: Help with directory ownership/permissions for apache I've been using Ubuntu Linux for a couple years now but I still have trouble with permissions.
I need to setup my web server for production. The root web directory should always be accessible by Apache and me (I login to ftp with my account) as well (if possible) by my CGI applications. I would like to hear your ideas of the best way to set something up like this in production.
Maybe what I've suggested isn't the best way to set this up even. If there's a better way to set things up for production (I plan to be using CGI scripts and compiled CGI binaries)

A: The directory should be owned and writable by the user making updates/changes to the web content. This should not be the Apache run-as user (by default, www-data).
So then:

*

*Neither user nor group ownership should be www-data.

*Normal files should be mode 644 or 664.

*Executable files and directories should be 755 or 775.

*If the Apache user must write to a directory for some reason (i.e., an upload script) that one directory should be mode 1777.

Remember, Apache will be performing actions on behalf of unknown and untrusted remote users. So only permit Apache to do what you want to let everyone on Reddit do on your box.

A: You can also use apache2-mpm-itk which allows to customize Apache user and group used for each virtual host.
apt-get install apache2-mpm-itk
nano /etc/apache2/sites-available/mydomain.com
<VirtualHost *:80>
    ServerAdmin webmaster@mydomain.com
    ServerName mydomain.com
    ServerAlias www.mydomain.com
    DocumentRoot /home/myuser/mydomain.com
    Options -Indexes
    AssignUserID myuser mygroup
</VirtualHost>

See Create and set up an Apache virtual host for more details.


text:
Q: Json_object in Oracle returns ORA-00907: missing right parenthesis I am trying to convert Oracle table data into JSON files. I have three databases and the below code gives output as JSON file in one DB but the other two databases throw ORA-00907: missing right parenthesis error.
Syntactically it is correct, as it gave output in one DB. Don't understand what is going wrong.
This is in Oracle DB, How do I find out which version of Oracle is installed in those DB's and if they are 12.2 and above, Is there a way to fix this issue? All I want is to convert the output of a select statement to a json file. Thanks in advance
code:
SELECT JSON_OBJECT ( 'empid' value eid , 'name' value ename , 'add' value eaddr )
FROM abc.emp

A: JSON_Object is available from Oracle version  12.2 .
Run the query Select * from v$version to check your oracle version


text:
Q: Linq nested Join from a group join if null I'm sure this is VERY simple but for the life of me I cannot find a single example of this.
I am doing a Group Join on a table I then want to do a second join on that grouped join.
Table 1 Orders
Table 2 Contacts
Table 3 Phone Numbers
dim query = from order in Orders _
Group Join contact in Contacts On order.contactId equals contact.contactId Into grpContacts = Group From gcontact in grpContacts.DefaultIfEmpty()
Group Join phone in PhoneNumbers On phone.phoneNumberId Equals gcontact.homePhoneId Into grpPhoneNumbers = Group from gphone in grpPhoneNumbers.DefaultIfEmpty()

This query will error out on the last join when gcontact is null. Which makes sense... but how do I do this join anyway and just have null/nothing values if the record does not exist?
 UPDATE RESOLVED *
If anyone else runs into this you can add an expression after the ON operator to determine if the previous group join is nothing. Thanks moander!
dim query = from order in Orders _
Group Join contact in Contacts On order.contactId equals contact.contactId Into grpContacts = Group From gcontact in grpContacts.DefaultIfEmpty()
Group Join phone in PhoneNumbers On IF(phone is nothing, 0, phone.phoneNumberId) Equals gcontact.homePhoneId Into grpPhoneNumbers = Group from gphone in grpPhoneNumbers.DefaultIfEmpty()

A: Try using iif to avoid accessing gcontact when it is null:
Equals iif(gcontact is nothing, 0, gcontact.homePhoneId)


text:
Q: How to limit string length of multiple elements with jquery? I want to limit the string length of all my $("a.paragraph"). I have the following code:
var paragraph = $("a.paragraph").text();
var maxlength = 500;
var strlength = paragraph.length;
if (strlength > maxlength) {
    var introduction    = paragraph.substr(0,maxlength); // cut string
    var search          = introduction.lastIndexOf(" "); // find position of last space (last word cannot be cut)
    introduction        = introduction.substr(0, search); // cut string until last space
    introduction        = introduction + "..."; // add ... in the end
    $("a.paragraph").text(introduction);
}

This code reworks the first element only and displays the result on all paragraphs. How can I loop every single paragraph?

A: You can make use of jQuery's each function:
$('a.paragraph').each(function() {
    var paragraph = $(this).text();
    // ... do stuff here
})

A: Using .each:
$('a.paragraph').each(function() {
    var paragraph = $(this).text();
    var strlength = paragraph.length;
    if (strlength > maxlength) {
        var introduction    = paragraph.substr(0, maxlength); // cut string
        var search          = introduction.lastIndexOf(" "); // find position of last space (last word cannot be cut)
        introduction        = introduction.substr(0, search); // cut string until last space
        introduction        = introduction + "..."; // add ... in the end
        $(this).text(introduction);
    }
});

A: You need to find each paragraph and loop around them:
$("a.paragraph").each(function() {
    var paragraph = $(this).text();
    var maxlength = 500;
    var strlength = paragraph.length;
    if (strlength > maxlength) {
        var introduction    = paragraph.substr(0,maxlength); // cut string
        var search          = introduction.lastIndexOf(" "); // find position of last space (last word cannot be cut)
        introduction        = introduction.substr(0, search); // cut string until last space
        introduction        = introduction + "..."; // add ... in the end
        $("a.paragraph").text(introduction);
    }
});

A: You need to loop over every element. The behavior you are experiencing is the way jQuery works by default.
$("a.paragraph").each(function(i,e) {
    var paragraph = $(e).text();
    var maxlength = 500;
    var strlength = paragraph.length;
    if (strlength > maxlength) {
        var introduction    = paragraph.substr(0,maxlength); // cut string
        var search          = introduction.lastIndexOf(" "); // find position of last space (last word cannot be cut)
        introduction        = introduction.substr(0, search); // cut string until last space
        introduction        = introduction + "..."; // add ... in the end
        $(e).text(introduction);
    }
});


text:
Q: Welch's t test vs Mann-Whitney for very unequal groups I have two vastly unequal groups (n1=18 and n2=400), and want to test mean differences between the groups for some 700 parameters (more specifically, RNA expression levels for 700 genes).
While I understand that Welch's t works well for non-normally distributed samples if both groups are large enough, this is not the case here. Testing for normality 700*2 times (or examining QQ plots) would take a lot and would almost certainly show that some variables are normally distributed and some are not.
In this case, would you go for

*

*Welch t-tests for everything (which would probably be breaking assumptions),

*Mann-Whitney tests for everything (which have a lower power and might lead to not getting too many significant results), or

*choosing the appropriate test for each variable, according to normality testing? This would probably not be a good idea, since I have to adjust the p-values using the FDR method, and I don't think that is correct if the p-values are generated by completely different tests

A: Your idea:

Mann-Whitney tests for everything (which have a lower power and might lead to not getting too many significant results)

is potentially misleading you in 2 ways.
First, as jbowman says on another page:

the worst that the Mann-Whitney can ever perform relative to the t-test is about 0.864 in terms of asymptotic relative efficiency, i.e., it would require 1/0.864x as much data to give the same power (asymptotically.)... The point of course being that you can't shoot yourself in the foot by using the Mann-Whitney test instead of the t-test, but the converse is not true.

Second, at the usual "significance" standard of p < 0.05 and 700 RNA species to examine, you will find about 35 "significant" differences even if there aren't any true differences. You will need to deal with the associated multiple comparisons problem, typically done via false discovery rate control with this type of study.
It's not a good idea to decide what type of test to perform based on a preliminary test of your results. This page has extensive discussion related to your type of situation.


text:
Q: How do I know if my visual studio product key is permanent? also, How do I know what type of license is in my visual studio?
what are the types of product license?

A: Your "product key" is always permanent. Just be sure you do not share it with other people.
To find your current license:

*

*Click Help > About Visual Studio

*Along the top there is a hyperlink -- "Product license information". Click that.

It will show you your current license.
For a quick and layman understanding of Visual Studio licensing, you can check this blog:
http://www.colinbowern.com/posts/visual-studio-licensing-in-a-nutshell
Cheers!


text:
Q: Destructuring a subset of an object directly into a new object Is there a one-liner to do this that I'm blanking on?
// this.state is a basic object with many keys
var {toDate, fromDate, location, flavor} = this.state
var goodKeys = {toDate, fromDate, location, flavor}
// goodKeys is an object that contains a subset of this.state's keys

The only way I can think of is:
var {keyIDontWant, otherUnwanted, ...goodKeys} = this.state

But this seems like it would be confusing to people reading the code, and take more effort to figure out how to write.

A: _.pick is still one of Underscore/Lodash features that have their use cases in ES6.
ES6 one-liner may be an IIFE and will result in enumerating the list of properties twice:
let goodKeys = (
  ({toDate, fromDate, location, flavor}) => ({toDate, fromDate, location, flavor})
)(this.state);

ES.next one-liner counterpart to _.pick may involve Object.entries:
Object.entries(o)
.filter(([key]) => ['toDate', 'fromDate', 'location', 'flavor'].includes(key))
.reduce((obj, [key, val]) => Object.assign(obj, { [key]: val }), {});


text:
Q: NSEvent doesn't work Can somebody tell me what's wrong with the following code. I want to simulate an "a".
NSEvent* keyEvent = [NSEvent keyEventWithType:NSKeyDown location:NSZeroPoint modifierFlags:NSCommandKeyMask timestamp:0 windowNumber:[windowNumber intValue] context:[NSGraphicsContext currentContext] characters:@"A" charactersIgnoringModifiers:nil isARepeat:NO keyCode:0];
[NSApp postEvent:keyEvent atStart:NO];


text:
Q: Word for neologisms derived from the names of fictional characters Is there a word that refers to or describes the subset of neologisms derived specifically from the names of fictional characters?

A: If you can handle two words: we might describe such terms as literary eponyms.
From Daily Writing Tips:

3. Literary Eponyms
Fictional characters often evoke such strong qualities that we assign their names to those qualities: faustian, quixotic. We also refer to people who exhibit qualities of literary characters by directly associating them, such as when we call someone a Casanova, a Romeo, or a Svengali (retaining initial capitalization), but some other such terms, such as lothario, are lowercased.


text:
Q: Suitable File Structure for Codeigniter First things first, this is not a coding error question.
its somewhat of a discussion type. Actually I followed a file-structure for last two years, and now i want to get people review or suggestions on that file structure
generally in CI the following structure in maintained within the application folder
root
-----------
     |___application
           |____ config
           |____ controllers
           |____ models
           |____ views
           ................
           ................
           |____ .htaccess

now I personally use this structure
root
-----------
 |___application
      |___front
      |     |____ config
      |     |____ controllers
      |     |____ models
      |     |____ views
      |     ................
      |     ................
      |     |____ .htaccess
      |
      |___admin
      |     |____ config
      |     |____ controllers
      |     |____ models
      |     |____ views
      |     ................
      |     ................
      |     |____ .htaccess

Now i have only one model which has the basic shareable functions. So i made two duplicate copies and put one in
application/front/models and the other one in the application/admin/models
Now the application/front folder is called by the seeting in the index.php file in the root folder
$application_folder = 'application/front';

Now to access the admin panel, we need to access the application/admin folder which is done by the following way
i made a duplicate of the index.php(renamed it as admin.php) file and put it in the root folder.
Then i made the change $application_folder = 'application/admin';
so if a url is like this
abc.com/admin.php/reports

then it calls the reports controller inside the application/admin/controllers folder
So all i want to know from you is that is this file-structure ok and shall i continue with this??
or i should use some other means

A: One very common solution to this is to set a new "Application Package."
In 2.x.0 this is not well documented, but you can see about it here:
http://ellislab.com/codeigniter/user-guide/libraries/loader.html
Basically add a shared path, called shared/ then add shared/models. To load that simply do:
$this->load->add_package_path(dirname(APPPATH).'shared/');
$this->load->model('whatever');

You can probably switch out APPPATH with FCPATH or something. It's been a year or two since I've used CodeIgniter for anything, but this is how I used to do it.


text:
Q: Use Excel-VBA to colour a range y if value is certain number is placed AND colour range x if value is certain number is placed I need to program a conditional format in Excel VBA (2016) without using the existing conditional formatting tool. As I am a newbie and tried for a while the following, I'm asking you to help me.
I want to write this e.g. in a private sub: for range E18:G18 and K1:K10:

If value is >=1 then colour = green
If value is <1 or "" then colour red

for range B1:B10

If value is >=3 then colour = green
If value is <3 & >0 then colour yellow
if value is  0 or "" the colour red

My code is the following - when i save it, nothing happens in my second defined range (K1:K10), also after reopening the excel-workbook.
Also nothing happens with my second conditional formatting range (B1:B10):
Private Sub Worksheet_Change(ByVal Target As Range)

Dim rngObserve As Range, rngCell As Range

Set rngObserve = Intersect(Target, Range("E18:G18, K1:K10"))

If rngObserve Is Nothing Then
    Exit Sub
End If
For Each rngCell In rngObserve.Cells
    If Not Intersect(rngCell, rngObserve) Is Nothing Then
        If rngCell.Value = vbNullString Then
            rngCell.Interior.Color = xlNone
        ElseIf rngCell.Value < 1 Then
            rngCell.Interior.ColorIndex = 3 'red
        ElseIf rngCell.Value >= 1 Then
            rngCell.Interior.ColorIndex = 4 'green
        Else
            rngCell.Interior.ColorIndex = 3 'red
        End If
    End If
Next

Dim rngObserve As Range, rngCell As Range

Set rngObserve = Intersect(Target, Range("B1:B10"))

If rngObserve Is Nothing Then
    Exit Sub
End If
For Each rngCell In rngObserve.Cells
    If Not Intersect(rngCell, rngObserve) Is Nothing Then
        If rngCell.Value = vbNullString Then
            rngCell.Interior.Color = xlNone
        ElseIf rngCell.Value < 3 And rgncell.Value > 0 Then
            rngCell.Interior.ColorIndex = 6 'yellow
        ElseIf rngCell.Value >= 3 Then
            rngCell.Interior.ColorIndex = 4 'green
        Else
            rngCell.Interior.ColorIndex = 3 'red
        End If
    End If
Next

End Sub

A: As mentioned in the comments, you can only have one Worksheet_Change subroutine. This code should get you what you need:
Private Sub Worksheet_Change(ByVal Target As Range)

Dim rngObserve As Range, rngCell As Range

'PGCodeRider comment: I'd set these to named ranges instead of hard-coded addresses
Set rngObserve = Intersect(Target, Range("E18:G18, K1:K10"))

    If Not rngObserve Is Nothing Then

        For Each rngCell In rngObserve.Cells

    If rngCell.Value = vbNullString Then
        rngCell.Interior.Color = xlNone
    ElseIf rngCell.Value < 1 Then
        rngCell.Interior.ColorIndex = 3 'red
    ElseIf rngCell.Value >= 1 Then
        rngCell.Interior.ColorIndex = 4 'green
    Else
        rngCell.Interior.ColorIndex = 3 'red
    End If

        Next rngCell

    End If

Set rngObserve = Intersect(Target, Range("B1:B10"))

    If Not rngObserve Is Nothing Then

        For Each rngCell In rngObserve.Cells

            If rngCell.Value = vbNullString Then
                rngCell.Interior.Color = xlNone
            ElseIf rngCell.Value < 3 And rngCell.Value > 0 Then
                rngCell.Interior.ColorIndex = 6 'yellow
            ElseIf rngCell.Value >= 3 Then
                rngCell.Interior.ColorIndex = 4 'green
            Else
                rngCell.Interior.ColorIndex = 3 'red
            End If

        Next rngCell

    End If
End Sub


text:
Q: Get child of list ui li dropdown knockout.js data binding Help pls. I have 22 objects, 5 parents and 17 for childs.
I can't get the child of the ui li. using data binding
knock out js. the 5 parent only displayed. thanks in advance.
enter image description here
enter image description here
Index.js
self._routes = ko.observableArray([]);
    self._child = ko.observableArray([]);
    for (var i = 0; i < backend.user().UserScreens.length; i++) {
        var str = backend.user().UserScreens[i].addOn; //add icon
        str = str.substring(0, str.length - 1); //trim last character ','
        if (backend.user().UserScreens[i].isParent || backend.user().UserScreens[i] == null) {
            self._routes.push({
                route: backend.user().UserScreens[i].linkURL,
                title: backend.user().UserScreens[i].description,
                moduleId: 'modules/' + backend.user().UserScreens[i].linkURL.replace(/[\n\r]+/g, '').replace(/\s{2,10}/g, ' ') + '/index',
                nav: true,
                _icon: 'fa ' + str,
                _id: '#' + backend.user().UserScreens[i].id
            });
        }
        else {
            self._child.push({
                childRoute: backend.user().UserScreens[i].linkURL,
                childtitle: backend.user().UserScreens[i].description,
                childmoduleId: 'modules/' + backend.user().UserScreens[i].linkURL.replace(/[\n\r]+/g, '').replace(/\s{2,10}/g, ' ') + '/index',
                childNav: true,
                childIcon: 'fa ' + str,
                childId: '#' + backend.user().UserScreens[i].id
            });
        }
    }

Index.html

A: Your model shows _routes and _child at same level thats why.
self._routes = ko.observableArray([]);
self._child = ko.observableArray([]);

Therefore your foreach on child will fall over as the child property doesn't exist. The fix would be to remove child from the route foreach or add $parent

But this will display all children foreach route, but i dont see any correlation between route and child so this may be what your looking.


text:
Q: How to remove a sprite when it reaches a certain point or it is touched? I am trying to make a game in cocos2d wherein I have sprites dropping from the top of the screen. Now, once the sprite is tapped, it should move back up. This works for me just fine but, there are some instances wherein the sprite would go back down after it goes off the screen. Also, my sprites don't disappear once they reach a certain y-axis position on the screen. Here's part of my code
-(void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint loc = [[CCDirector sharedDirector]convertToGL:[touch locationInView:[touch view]]];

CGRect rect = CGRectMake(sprite.position.x - (sprite.contentSize.width/2), sprite.position.y - (sprite.contentSize.height/2), sprite.contentSize.width, sprite.contentSize.height);

if(CGRectContainsPoint(rect, loc))
{
    [sprite runAction:[CCCallFuncN actionWithTarget:self selector:@selector(spriteCaught)]];
}}

-(void)spriteCaught
{
//currentPos is an integer to get the current position of the sprite
id moveUp = [CCMoveTo actionWithDuration:1 position:ccp(currentPos, 500)];
[sprite runAction:[CCSequence actions:moveUp, nil]];
if(sprite.position.y >= 480)
{
    [self removeChild:sprite cleanup:YES];
}}

Also, I'm not sure if my syntax is correct but my conditional statement (The one that checks the position in the y-axis of the sprite) doesn't work either. How do I go about fixing this? Any help and suggestion is greatly appreciated

A: Instead of manual rect, use sprite's bounding box.
         if(CGRectContainsPoint([sprite boundingBox], loc))

Also update spriteCaught function.
-(void)spriteCaught
{
    CGSize s = [[CCDirector sharedDirector] winSize];

    float dest_y = s.height+sprite.contentSize.height*0.5f; //assumed ur sprite's anchor y = 0.5

    //currentPos is an integer to get the current position of the sprite
    id moveUp = [CCMoveTo actionWithDuration:1 position:ccp(sprite.position, dest_y)];
    id calBlokc = [CCCallBlockN actionWithBlock:^(CCNode *node)
    {
        //here node = sprite tht runs this action
        [node removeFromParentAndCleanup:YES];
    }];
    id sequence = [CCSequence actions:moveUp, calBlokc, nil];

    [sprite runAction:sequence];
}


text:
Q: Is there a word for the total amount of time you weren't working in a day? I can say that I plan to work 7 hours today, but how do I say I plan to "not work" for 2 hours?
"Be on a break/pause for 2 hours" or "Rest for 2 hours" doesn't work because I might take several smaller breaks.
"Not work for 2 hours" sounds too vague because I am referring to periods of rest during the workday.
Maybe, "I plan to take breaks that add up to 2 hours".
Any ideas?

A: Downtime is used at lot of workplaces to denote the time when a worker is expected to work but is instead not working due to his choice or otherwise (system down or other unforeseen circumstances).

A: You could pluralise break, or be a bit more specific:

*

*Take two hours of breaks

*Be on breaks for two hours

*I shall take various breaks for two hours (or totalling two hours)

Or

*

*I shall do seven hours' work between 0900 and 1800 hours.

A: WordNet 3.0 cited in the Free Dictionary:

Noun 1. time off - a time period when you are not required to work; "he requested time off to attend his grandmother's funeral"

You would say:
"I plan to take two hours' time off."
Wikipedia notes time off and Paid time off (PTO) in AmE:

In the USA, Paid time off (PTO) is a feature in some employee agreements that provides a "resource" of hours that an employee can draw from to take time off from work, without having to specify a reason.

Note that the phrase is also used in a broader sense or in various contextual meanings, such as time when you are not at work or at school (Macmillan), a period when one is absent from work for a holiday, through sickness, etc (Collins), A break from one's employment or school, as in I need some time off from teaching to work on my dissertation , or He took time off to make some phone calls (dictionary.reference.com), and such other.

A: Take two hours of rest will cover a single extended period or multiple short breaks that total 120 minutes.

A: "I plan to spend two hours at leisure."
Definitions of "at leisure" from CollinsDictionary.com:

at leisure in American English

*

*having free or spare time

*with no hurry

*not occupied or engaged

Please note: "At leisure" might sound a little old-fashioned, or carry a whiff of the military. I investigated using Google and found no particular military association. "At ease" is similar and is most assuredly a military-associated term.


text:
Q: Access Microsoft Band 2 sensors through computer I'm trying to write a program that collects the pedometer and
heart rate data stream from the Microsoft Band 2. I've written an
android app that does this but is it possible to do this without a
smartphone and directly stream the data to a computer?

A: Yes, the Band SDK can be used with Windows Store 8.1 and Windows 10 Universal applications; you just Bluetooth-pair the Band to the PC and applications can stream sensor data from the Band just like their phone equivalents.
The Band SDK does not support OS X and I don't know whether it can be used in any arbitrary device running an Android-derived OS.


text:
Q: Is there something like printf in Action Script 3? I searched it for while but didn't find anything like printf in Action Script.
That makes it a little difficult to generate formated strings.

A: Printf-as is a third-party library that will handle this. Here is the GitHub repo. From the README:
printf("You can also display numbers like PI: %f, and format them to a fixed precision,
        such as PI with 3 decimal places %.3f", Math.PI, Math.PI);
// outputs: " You can also display numbers like PI: 3.141592653589793,
// and format them to a fixed precision, such as PI with 3 decimal places 3.142"

It also plays well with dates:
var date : Date = new Date();
printf("Today is %d/%m/%Y", date, date, date);

A: think you might be looking for StringUtil.substitute()
take a look here:
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/mx/utils/StringUtil.html#substitute

A: There is the Formatter classes that you could use or create custom formatters.
http://livedocs.adobe.com/flex/3/html/help.html?content=createformatters_2.html

A: The only function I know that prints to a standard output is trace() (debug purposes only) , which can take virtually any type of variable.
I might not have understood your question, though.


text:
Q: How to add order by for Union result? In SQL Server 2008, we can use Union/Unino All to put two results together, but I want to add order by for the final result. How can do that?
What I want is something like:
select id1 as id, * from ...
Union All
select id2 as id, * from ...
order by id

Help please. Thanks.

A: As noted in the comments, the pseudocode you've given should work, applying the order by to the combined result set. If you're trying to order in such a way that the two result sets are kept distinct, you'd need to introduce an artificial sort column, such as:
select id1 as id, *, 1 as MySortKey from ...
Union All
select id2 as id, *, 2 as MySortKey from ...
order by MySortKey, id

A: You can use this query as well
select * from (
select id1 as id, * from ...
Union All
select id2 as id, * from ...
) aaaa
order by id

A: use this code:
Select * from
(select id1 as id, * from ...
Union All
select id2 ad id,  * from ...
order by id) as t
order by t.id

A: use northwind
select OrderID, ProductID from [Order Details] a
UNION all
Select OrderID, EmployeeID from Orders b
order by a.ProductID

A: All of these answers included the original poster's attempt is just plain confusing or overly complicated.  A simple and easy to follow explanation is here:
How to order by with union
with,
"Just write
Select id,name,age
From Student
Where age < 15
Union
Select id,name,age
From Student
Where Name like "%a%"
Order by name

the order by is applied to the complete resultset
"
Just use UNION ALL instead of UNION here.


text:
Q: Replace one character with other in tab separated file Hi I want to replace all the . ( dots) by -1 in tab separated file.
.   .   .   .   .   .
.   .   .   .   .   .
.   0.4012  0.359026    0.3616  0.246   0.4324
.   0.6795  0.60024 0.4713  0.6171  0.7386
.   0.6863  0.614018    0.5227  0.6131  0.7376
.   .   .   .   .   .
.   0.2044  0.210264    0.1936  0.2192  0.2376
.   0.2043  0.210064    0.1929  0.2183  0.2376
.   0.9852  0.984625    0.9425  1   1
.   .   0.10603 0.1127  0.127   0.0427
.   0.6934  0.709864    0.8222  0.6944  0.664
.   0.0219  0.0213658   0.0015  0.0397  0.0219
.   .   .   .   .   .

How ever I dont want to replace the dots present along with the numbers i.e. 0.4012 or 0.359.
I tried this code
perl -p -i.backup -e 's/". /-1/g' .\abc.txt

but It didn't work
Output I got was
.   .   .   .   .   .
.   .   .   .   .   .
.   0.4012  0.359026    0.3616  0.246   0.4324
.   0.6795  0.60024 0.4713  0.6171  0.7386
.   0.6863  0.614018    0.5227  0.6131  0.7376
.   .   .   .   .   .
.   0.2044  0.210264    0.1936  0.2192  0.2376
.   0.2043  0.210064    0.1929  0.2183  0.2376
.   0.9852  0.984625    0.9425  1   1
.   .   0.10603 0.1127  0.127   0.0427
.   0.6934  0.709864    0.8222  0.6944  0.664
.   0.0219  0.0213658   0.0015  0.0397  0.0219
.   .   .   .   .   .

Thanks in advance.

A: Your perl isn't too far off.
Remember that the substitute format's command is s/pattern/replacement/flags, just as it is in sed. The pattern is a regular expression, where a single dot translates to "any single character".  To match a literal dot, you need to escape it with a backslash, or put it in square brackets.
perl -p -i.backup -e 's/\.([^0-9])/-1\1/g' abc.txt

This matches literal dots that are followed by something other than a numeral, and replaces them with your replacement string, along with whatever non-numeral character was matched (\1).  Perl appears to consider the null at the end of the line to be a non-numeral, which allows the dots at the end of the line to be replaced as well.
Note that in perl, you could also replace [^0-9] with [^\d] or \D, and \1 with $1. But the former only works in perl and (some) GNU tools, and the latter is not the most widespread notation amongst command line tools. Personally, I'd rather keep my regexes and replacements more portable, so that if I were to switch from perl to, say, awk, I wouldn't have to rewrite so much code.
For example:
gawk '{$0=gensub(/\.([^0-9])/,"-1\1","g")}1' abc.txt > ,$$ && mv ,$$ abc.txt

or
sed -i.backup -Ee 's/\.([^0-9])/-1\1/g' abc.txt

Portability is generally a good thing, if you can manage it.

A: Following awk may help you on same.
awk '{for(i=1;i<=NF;i++){sub(/^\.$/,"-1",$i)}} 1' Input_file

Change awk to awk -F"\t" AND Input_file to OFS="\t" Input_file in case of your Input_file is having delimiter as TAB and you want to have output in TAB format too.


text:
Q: attempting to run a spring-mvc project in intelliJ I've cloned a spring-mvc project and was hoping to get it running. First time working on a project like this and could use help. I was told, I should be able to run the project and have a test environment on localhost. Instead, I only have an option to debug. I've added spring for Framework support, maybe I need to add something else?
run test image http://snag.gy/AySh6.jpg
here are some images of my project structure, in case it helps
modules
module image http://snag.gy/94Cnb.jpg
libraries
project library image http://snag.gy/znR7x.jpg
SDK's
project sdk image http://snag.gy/cI4Wj.jpg
edit: added image for add run configuration menu
configuration menu http://snag.gy/piyzz.jpg
run configuration menu

A: You need to deploy the webapp to a tomcat.
You can check this issue for more info:
Intelli tomcatJ

A: You need to create a run configuration for your server and configure the webapp to be deployed to it. Spring mvc is meant to be run on a server, and the client is, usually, a browser.

A: Using the right-click popup menu gives only options to run tests. You have to create a new run configuration using the Run item from the main menu, or the specific run area on the main toolbar.


text:
Q: Algorithm to find all values less than a given value in a binary search tree
Having a Binary Search Tree of int create a linked list of all the integers less than a given integer x value.

What I've tried?
1)brutal solution(inefficient)
An  inorder visit of the BST, I insert a node in the list for every integer int the Bst,
and then I free every node of the list starting from x
2)more efficient but wrong
I make a search and when I find x, I create a list with an in-order visit of the left son of the node where I've found x.
It's obvious wrong, for example considering the follow BST:
                         10
                        /  \
                       9    11
                      /       \
                     5         15
                    / \        / \
                   1   8      13  19
                             /  \
                            12  14

with this solution if x=15 I just consider {12,13,14}, it would work just for x=root.
The question is How can I do?

A: Pseudocode. v is current vertex, ans is the answer list, someTraversal is a method traversing through the tree and returning a list of its elements.

*

*v := root, ans := []

*if v.value > x
then v := v.left, goto 2;

*ans.append( someTraversal ( v.left ))

*if v.value = x
then return ans;

*ans.append( v.value )

*v := v.right;

*goto 2;

A: If you store the parent node of each node, a more efficient solution can be implemented, as long as you don't care about the order of the elements in the result list:

*

*Create a new list to save the result

*Find the node of interest

*Add to the list all the nodes in the left subtree of the node found on step 2, using any traversal you fancy (in-order, pre-order, etc.)

*Starting from the parent of the node found on step 2, go up through all the parents adding each node in the way until the current node is either the root node or a node to the left of its parent

*Finally, add all the elements to the left of the node found on step 4, again using any traversal

A: Here's a modified version of an inorder traversal that terminates when a node's value is > x.
def nums_less_than(n, x, l=None):
  if l == None:
    l = []
  if n.left:
    nums_less_than(n.left, x, l)
  if n.value < x:
    l.append(n.value)
    if n.right:
      nums_less_than(n.right, x, l)
  return l


text:
Q: Jersey 2 client with maven I want to create simple Jersey 2 Client app with Maven (Server app is also implemented and runs).
My pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.client</groupId>
    <artifactId>RestClient</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>RestClient</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-client</artifactId>
            <version>2.13</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

java code
package com.client;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;
import javax.ws.rs.client.Invocation.Builder;

public class App
{
    public static void main( String[] args )
    {

        Client client = ClientBuilder.newClient();
        WebTarget target = client.target("http://localhost:8080").path("simple-service-webapp/rest/myresource");

        Builder builder =   target.request();
        //Response response  = builder.get();
        String result  = builder.get(String.class);
        System.out.println(target.getUri().toString());
        System.out.println("Result=" + result);

    }
}

I build app by command mvn package and everything pass. Then, I run app by java -cp target/RestClient-1.0-SNAPSHOT.jar com.client.App and then error occurs:
Exception in thread "main" java.lang.NoClassDefFoundError: javax/ws/rs/client/ClientBuilder
        at com.client.App.main(App.java:20)
Caused by: java.lang.ClassNotFoundException: javax.ws.rs.client.ClientBuilder
        at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
        ... 1 more

It seems that libraries are not included, because files tree of projeckt looks:
.
├── pom.xml
├── src
│   ├── main
│   │   └── java
│   │       └── com
│   │           └── client
│   │               └── App.java
│   └── test
│       └── java
│           └── com
│               └── client
│                   └── AppTest.java
└── target
    ├── classes
    │   └── com
    │       └── client
    │           └── App.class
    ├── generated-sources
    │   ├── annotations
    │   └── test-annotations
    ├── maven-archiver
    │   └── pom.properties
    ├── RestClient-1.0-SNAPSHOT.jar
    ├── surefire
    ├── surefire-reports
    │   ├── com.client.AppTest.txt
    │   └── TEST-com.client.AppTest.xml
    └── test-classes
        └── com
            └── client
                └── AppTest.class

Where did I mistake? Thanks.

A: You need to copy the dependencies to from your local repo into you project (or anywhere really, wherever you want to -cp to). For this, you can use the maven-dependency-plugin. Just add this to the <plugins>
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-dependency-plugin</artifactId>
    <version>2.9</version>
    <executions>
        <execution>
            <id>copy-dependencies</id>
            <phase>package</phase>
            <goals>
                <goal>copy-dependencies</goal>
            </goals>
            <configuration>
                <outputDirectory>${project.build.directory}/lib</outputDirectory>
                <overWriteReleases>false</overWriteReleases>
                <overWriteSnapshots>false</overWriteSnapshots>
                <overWriteIfNewer>true</overWriteIfNewer>
            </configuration>
        </execution>
    </executions>
</plugin>

What the above plugin configuration will do is copy all the dependencies to target/lib.
The easiest way to run the jar as an executable is to also set the Class-Path in the MANIFEST.MF, through Maven. For that we can use the maven-jar-plugin. So add this to the <plugins>
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <version>2.5</version>
    <configuration>
        <archive>
            <index>true</index>
            <manifest>
                <addClasspath>true</addClasspath>
                <classpathPrefix>lib/</classpathPrefix>
                <mainClass>com.client.App</mainClass>
            </manifest>
        </archive>
    </configuration>
</plugin>

Also you will need to get rid of the <scope>provided</scope> for the Jersey client dependency. With this scope, Maven will not add the jars to the classpath.
After doing this, you can simply run java -jar your-jar.jar, without the need to -cp anything, as all the jars are specified in the Manifest. It should look something like
Manifest-Version: 1.0
Archiver-Version: Plexus Archiver
Built-By: XxxxXxxxx
Class-Path: lib/jersey-client-2.13.jar lib/jersey-common-2.13.jar lib/
 javax.annotation-api-1.2.jar lib/jersey-guava-2.13.jar lib/osgi-resou
 rce-locator-1.0.1.jar lib/javax.ws.rs-api-2.0.1.jar lib/hk2-api-2.3.0
 -b10.jar lib/hk2-utils-2.3.0-b10.jar lib/aopalliance-repackaged-2.3.0
 -b10.jar lib/javax.inject-2.3.0-b10.jar lib/hk2-locator-2.3.0-b10.jar
  lib/javassist-3.18.1-GA.jar
Created-By: Apache Maven 3.0.5
Build-Jdk: 1.8.0_20
Main-Class: com.client.App

A: You marked your jersey dependency as provided, therefore it won't be included in the output, because when the dependency is provided, it is assumed that it is available in the environment (for example by application server).
Try removing the <scope>provided</scope> from your Maven dependency or include the jersey jar on the classpath using the -cp parameter when you run your program.

A: The other thing you can do is package your dependencies into a fat jar. The maven-assembly-plugin will do this for you automatically.
<plugin>
  <artifactId>maven-assembly-plugin</artifactId>
  <configuration>
    <archive>
      <manifest>
        <mainClass>YOUR MAIN CLASS HERE</mainClass>
      </manifest>
    </archive>
    <descriptorRefs>
      <descriptorRef>jar-with-dependencies</descriptorRef>
    </descriptorRefs>
  </configuration>
  <executions>
    <execution>
      <id>make-assembly</id>
      <phase>package</phase>
      <goals>
        <goal>single</goal>
      </goals>
    </execution>
  </executions>
</plugin>

You can create a custom assembly specification if you need anything more sophisticated that this basic mode in which all dependencies are included in the jar.
There is also the maven-shade-plugin, which is also more configurable.
Another useful tool is:
mvn dependency:tree -Dverbose

to see exactly what your dependencies are.


text:
Q: upload multiple files with Spring REST URL with RestTemplate from Android device I am working on upload multiple files from android devices to PHP server, the code works fine when upload single file with FileSystemResource, and the API of files is String type. But I'm wondering how to upload multiple files within one request, any data structure I should use? Thanks.
Follow up:
How to post an array such as FileSystemResource[ ] as the same param "picUrl"
when I tried to do so, i got the HttpMessageNotWritableException, here's part of the stack of the exception

org.springframework.http.converter.HttpMessageNotWritableException: Could not write request: no suitable HttpMessageConverter found for request type [[Lorg.springframework.core.io.FileSystemResource;]
  03-29 18:07:07.657: W/System.err(31368):    at org.springframework.http.converter.FormHttpMessageConverter.writePart(FormHttpMessageConverter.java:314)
  03-29 18:07:07.667: W/System.err(31368):    at org.springframework.http.converter.FormHttpMessageConverter.writeParts(FormHttpMessageConverter.java:276)
  03-29 18:07:07.667: W/System.err(31368):    at org.springframework.http.converter.FormHttpMessageConverter.writeMultipart(FormHttpMessageConverter.java:266)
  03-29 18:07:07.677: W/System.err(31368):    at org.springframework.http.converter.FormHttpMessageConverter.write(FormHttpMessageConverter.java:209)
  03-29 18:07:07.677: W/System.err(31368):    at org.springframework.http.converter.FormHttpMessageConverter.write(FormHttpMessageConverter.java:91)
  03-29 18:07:07.687: W/System.err(31368):    at org.springframework.web.client.RestTemplate$HttpEntityRequestCallback.doWithRequest(RestTemplate.java:624)
  03-29 18:07:07.687: W/System.err(31368):    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:474)
  03-29 18:07:07.697: W/System.err(31368):    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:439)
  03-29 18:07:07.697: W/System.err(31368):    at org.springframework.web.client.RestTemplate.postForObject(RestTemplate.java:317)

API:
api
public BaseTest addDynamic(String content, File picUrl){

      MultiValueMap<String, Object> params = new LinkedMultiValueMap<String, Object>();
      try{
          StringBuilder sbContent = new StringBuilder(URLEncoder.encode(content, "UTF-8"));
          params.set("content", sbContent.toString());
      }catch (UnsupportedEncodingException e){
          params.set("content", content);
      }
      if(picUrl != null){
          Resource file = new FileSystemResource(picUrl);
          params.set("picUrl", file);
      }

      BaseTest result =  getRestTemplate().postForObject(
              AppContext.getInstance().getString(R.string.path_api),
              params,BaseTest.class);
      return result;
}

protected RestTemplate getRestTemplate() {
    return new RestTemplate(true, new HttpComponentsClientHttpRequestFactory());
}


text:
Q: Powershell `echo -e "1\n2\n3" | tail -n1` equivalent There are countless examples about how to get tail for file content, but there is no for pipes.
Is there any way to get last line from pipe ?
I have long chain of piped commands and I want last 1 line only.

A: If you want the last object, that is send through the pipe, Select-Object can do that for you:
$input | Select-Object -Last 1

If you are only interested in one particular property of this object, you can expand this property in the same statement:
[pscustomobject]@{propname = 'foo'},[pscustomobject]@{propname = 'bar'} |
    Select-Object -Last 1 -ExpandProperty propname

A: Or -1 is the last element of an array.
(echo 1 2 3)[-1]

3


text:
Q: Some annoying characters are not normalised by unicodedata I have a python string that looks like as shown below. This string is from the SEC filing of one public company in the US. I am trying to remove some annoying characters from the string using unicodedata.normalise function, but this is not removing all characters. What could be the reason behind such behavior?
from unicodedata import normalize
s = 'GTS.Client.Services@JPMChase.com\nFacsimile\nNo.:\xa0 312-233-2266\n\xa0\nJPMorgan Chase Bank,\nN.A., as Administrative Agent\n10 South Dearborn, Floor 7th\nIL1-0010\nChicago, IL 60603-2003\nAttention:\xa0 Hiral Patel\nFacsimile No.:\xa0 312-385-7096\n\xa0\nLadies and Gentlemen:\n\xa0\nReference is made to the\nCredit Agreement, dated as of May\xa07, 2010 (as the same may be amended,\nrestated, supplemented or otherwise modified from time to time, the \x93Credit Agreement\x94), by and among\nHawaiian Electric Industries,\xa0Inc., a Hawaii corporation (the \x93Borrower\x94), the Lenders from time to\ntime party thereto and JPMorgan Chase Bank, N.A., as issuing bank and\nadministrative agent (the \x93Administrative Agent\x94).'

normalize('NFKC', s)
'GTS.Client.Services@JPMChase.com\nFacsimile\nNo.:  312-233-2266\n \nJPMorgan Chase Bank,\nN.A., as Administrative Agent\n10 South Dearborn, Floor 7th\nIL1-0010\nChicago, IL 60603-2003\nAttention:  Hiral Patel\nFacsimile No.:  312-385-7096\n \nLadies and Gentlemen:\n \nReference is made to the\nCredit Agreement, dated as of May 7, 2010 (as the same may be amended,\nrestated, supplemented or otherwise modified from time to time, the \x93Credit Agreement\x94), by and among\nHawaiian Electric Industries, Inc., a Hawaii corporation (the \x93Borrower\x94), the Lenders from time to\ntime party thereto and JPMorgan Chase Bank, N.A., as issuing bank and\nadministrative agent (the \x93Administrative Agent\x94).'

As one can see from the outputs, the characters \xa0 is handled properly, but the characters like \x92, \x93 and \x94 are not normalized and are as it is in the result string.

A: Your data was decoded as ISO-8859-1 (aka latin1), but those Unicode code points are control characters in that encoding.  In Windows-1252 (aka cp1252) they are so-called smart quotes:
>>> '\x92\x93\x94'.encode('latin1').decode('cp1252')
''""'

They also don't change when normalized, but at least they display correctly if decoded properly:
>>> ud.normalize('NFKC','\x92\x93\x94'.encode('latin1').decode('cp1252'))
''""'
>>> print(s.encode('latin1').decode('cp1252'))
GTS.Client.Services@JPMChase.com
Facsimile
No.:  312-233-2266

JPMorgan Chase Bank,
N.A., as Administrative Agent
10 South Dearborn, Floor 7th
IL1-0010
Chicago, IL 60603-2003
Attention:  Hiral Patel
Facsimile No.:  312-385-7096

Ladies and Gentlemen:

Reference is made to the
Credit Agreement, dated as of May 7, 2010 (as the same may be amended,
restated, supplemented or otherwise modified from time to time, the "Credit Agreement"), by and among
Hawaiian Electric Industries, Inc., a Hawaii corporation (the "Borrower"), the Lenders from time to
time party thereto and JPMorgan Chase Bank, N.A., as issuing bank and
administrative agent (the "Administrative Agent").

Note the \xa0 code point is U+00A0 (NO-BREAK SPACE) and canonically normalizes to a SPACE:
>>> ud.name('\xa0')
'NO-BREAK SPACE'
>>> ud.normalize('NFKC','\xa0')
' '
>>> ud.name(ud.normalize('NFKC','\xa0'))
'SPACE'

It prints correctly without normalization:
>>> print('hello\xa0there')
hello there

A: unicodedata.normalize is not meant to "remove [...] characters".
It is there so that Unicode strings that might be equivalent, but written with different representations, can be cast to a uniform representation -- but it will not mutilate the text to drop characters that "don't look good". What happens with \xa0 (non-breaking space) in particular is that it is equivalent to a common plain space (\x20) in the normalized forms, and is therefore replaced by that.
That said, it looks like the application that generates the data you are consuming just includes these characters with semantic purpose; their meaning is here: C0 and C1 control codes - Wikipedia. If you want just to discard that information and preserve other non-ASCII characters in your text, a replace for all characters in the C1 block range, after normalizing, will do the job.  re.sub might be nice due to being able to allow the selection of a character range:
import re
...
s1 = normalize("NFKC", s)
s2 = re.sub("[\x1f-\x9f]", "", s1)

If you want to simply drop all non-ASCII characters (not recommended if your source is not ASCII + ctrl characters only), on the other hand, just encode the text with "ignore" as error policy:
s2 = s1.decode("ASCII", errors="ignore").decode()


text:
Q: Python with mysql query insertion - single parameter Below are the code that is not working
#!/usr/bin/python

import urllib
import datetime
import mysql.connector

data['price'] = 100

# Write to database
cnx = mysql.connector.connect(user='user', password='pw', database='db')
cursor = cnx.cursor()

query = ("INSERT INTO records(price) VALUES(%s) ")
cursor.execute(query, (data['price']))

cnx.commit()

cursor.close()
cnx.close()

MySQL has the corresponding table and column.

*

*id (PRIMARY INT AUTO_INCREMENT)

*price (FLOAT)

There is no connection problem.
It gives the following error. Any idea?

Traceback (most recent call last):   File "./sys-fetchdata.py", line
  22, in
      cursor.execute(query, (data['price']))   File "/usr/lib/python2.7/dist-packages/mysql/connector/cursor.py", line
  507, in execute
      self._handle_result(self._connection.cmd_query(stmt))   File "/usr/lib/python2.7/dist-packages/mysql/connector/connection.py", line
  722, in cmd_query
      result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))   File
  "/usr/lib/python2.7/dist-packages/mysql/connector/connection.py", line
  640, in _handle_result
      raise errors.get_exception(packet) mysql.connector.errors.ProgrammingError: 1064 (42000): You have an
  error in your SQL syntax; check the manual that corresponds to your
  MySQL server version for the right syntax to use near '%s)' at line 1

A: the MySQLCursor.execute() method takes a tuple (or a dict) as second (params) argument.
in your case: it should be (data['price'], ) (note the additional comma; without it the brackets have no effect) instead of (data['price']).

A: Let's try to find a solution:

*

*Do not execute your query, instead mogrify and print it. For example:
query = ("INSERT INTO records(price) VALUES(%s) ")
query_to_be_executed = cursor.mogrify(query, (data['price']))
print(query_to_be_executed)

*Next try to execute your printed query manually in bash or phpMyAdmin and fix it.

*Finally use fixed query in your python code.


text:
Q: Проблема со слайдером html/css Здравствуйте, у меня есть небольшой слайдер на css, возникла проблема:
Первый и второй слайд переключаются между собой без проблем, но после того как выбираю третий слайд, то переключатели перестают работать и менять слайды, помогите разобраться с проблемой, пожалуйста

.container {
  position: relative;
  width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.slide-toggle {
  border: 0;
  clip: rect(1px, 1px, 1px, 1px);
  -webkit-clip-path: inset(50%);
  clip-path: inset(50%);
  height: 1px;
  overflow: hidden;
  padding: 0;
  position: absolute;
  width: 1px;
  white-space: nowrap;
}

.sliders-block::before {
  position: absolute;
  content: '';
  left: 620px;
  top: 40px;
  width: 100px;
  height: 7px;
  background-color: #ffffff;
}

.slider-img {
  margin-top: 100px;
}

.sliders-block .first-slider {
  background: linear-gradient(180deg, #f7e296 113px, #ffffff 113px);
  padding-left: 30px;
  padding-top: 4px;
  padding-right: 60px;
}

.first-slider .slider-img {
  padding-left: 60px;
}

.first-slider .slider-info-block {
  padding-top: 80px;
  padding-left: 128px;
}

.first-slider .slider-info-block td {
  padding-right: 77px;
  padding-bottom: 5px;
}

.sliders-block .second-slider {
  background: linear-gradient(180deg, #f7e296 113px, #ffffff 113px);
  padding-left: 30px;
  padding-top: 4px;
  padding-right: 60px;
  padding-left: 27px;
}

.second-slider .slider-img {
  padding-top: 10px;
  padding-left: 90px;
}

.second-slider .slider-info-block {
  padding-top: 80px;
  padding-left: 138px;
}

.second-slider .slider-info-block td {
  padding-bottom: 5px;
}

.third-slider .slider-img {
  padding-top: 64px;
}

.sliders-block .third-slider {
  background: linear-gradient(180deg, #f7e296 113px, #ffffff 113px);
  padding-left: 30px;
  padding-top: 4px;
  padding-right: 60px;
}

.third-slider .slider-info-block {
  position: relative;
  z-index: 2;
  padding-top: 80px;
  padding-left: 45px;
}

.third-slider .slider-info-block td {
  padding-right: 45px;
  padding-bottom: 5px;
}

.slider-info-block h2 {
  font-family: 'gilroyextrabold', sans-serif;
  font-size: 47px;
  line-height: 55px;
  font-weight: 800;
  color: #000000;
  margin: 0;
  margin-bottom: 20px;
}

.slider-info-block p {
  font-family: 'Open Sans', sans-serif;
  font-size: 15px;
  line-height: 30px;
  font-weight: 300;
  color: #464646;
  margin: 0;
  margin-bottom: 44px;
  padding: 0;
}

.slider-info-block a {
  position: relative;
  z-index: 2;
  display: inline-block;
  font-family: 'gilroyextrabold', sans-serif;
  font-size: 18px;
  font-weight: 800;
  letter-spacing: 4px;
  color: #000000;
  text-decoration: none;
  text-transform: uppercase;
  margin-left: 45px;
  margin-bottom: 56px;
}

.slider-info-block a::before {
  position: absolute;
  z-index: -1;
  content: '';
  width: 220px;
  height: 8px;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  background-color: #f0c52e;
}

.slider-info-block a:focus::before,
.slider-info-block a:hover::before {
  height: 40px;
}

.slider-info-block a:active {
  color: rgba(0, 0, 0, 0.3);
}

.slider-info-block .headline {
  font-family: 'gilroylight', sans-serif;
  font-size: 36px;
  color: #000000;
}

.slider-info-block .description {
  font-family: 'Open Sans', sans-serif;
  font-size: 13px;
  font-weight: 300;
  color: #464646;
}

.slider-info-block td:last-child {
  padding-right: 0;
}

.toggle-position {
  position: absolute;
  bottom: 148px;
  right: 80px;
}

.toggle-position label {
  display: inline-block;
  width: 12px;
  height: 12px;
  border: 1px solid black;
  border-radius: 50%;
  margin-right: 18px;
}

.button-1:checked~.toggle-position label[for='btn-1'],
.button-2:checked~.toggle-position label[for='btn-2'],
.button-3:checked~.toggle-position label[for='btn-3'] {
  background-color: black;
}

.sliders-block .slide {
  display: none;
}

.button-1:checked~.sliders-block .first-slider,
.button-2:checked~.sliders-block .second-slider,
.button-3:checked~.sliders-block .third-slider {
  display: flex;
}

  <input class="slide-toggle button-1" type="radio" id="btn-1" name="toggle1" checked>
  <input class="slide-toggle button-2" type="radio" id="btn-2" name="toggle1">
  <input class="slide-toggle button-3" type="radio" id="btn-3" name="toggle1">

          Делай селфи,
 как Бен Стиллер!

          Самая длинная палка для селфи доступна в нашем магазине.
 Восемь (Восемь, Карл!) метров длиной и весом всего 5 килограмм.

        Подробнее

            8,5 м
            5 кг
            Карбон

            Длина палки
            Вес палки
            Материал

          Худеем
 правильно!

          Мотивирующие фитнес-браслеты помогут найти в себе силы не пропускать занятия и соблюдать диету.

        Подробнее

            48 часов

            Без подзарядки

          Порхает как бабочка, жалит как пчела!

          Этот обычный, на первый взгляд, квадрокоптер оснащен мощным лазером, замаскированным под стандартную камеру.

        Подробнее

            800 м
            50 м

            Дальность полета
            Радиус поражения


text:
Q: can i use the function md5_file to name files when upload without having conflict with names? all the idea i need to be sure that the file doesn't saved more than one time and don't lose any file because if tow files get the same (md5) the second file will not saved
(my goal don't save the same file Twice on hard disk)
In other words,
if one user upload image and after that another user upload the same image i need to don't save the the second image because it's already exist in the hard disk all of this because
i need to save space on my hard disk
this is my code it works fine
$targetFolder = '/test/uploadify/uploads'; // Relative to the root
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;

$myhash = md5_file($_FILES['Filedata']['tmp_name']);
$temp = explode(".", $_FILES['Filedata']['name']);
$extension = end($temp);

$targetFile = rtrim($targetPath,'/') . '/' .$myhash.'.'.$extension;
if(file_exists($targetFile)){
    echo 'exist';
}

// Validate the file type
$fileTypes = array('jpg','jpeg','gif','png'); // File extensions
$fileParts = pathinfo($_FILES['Filedata']['name']);
if (in_array($fileParts['extension'],$fileTypes)) {
    move_uploaded_file($tempFile,$targetFile);
}
else {
    echo 'Invalid file type.';
}

thanks for all of you

A: Well, of course you can do this, in fact this is the way I use to avoid file duplications (and I mean not having two files wit the same content and not just silly name collision).
If you are worried about collisions, then you might take a look at sha1_file:
http://es1.php.net/manual/en/function.sha1-file.php
What are the chances that two messages have the same MD5 digest and the same SHA1 digest?
I've been using the md5 approach the way you are suggesting here for image galleries and it works just fine.
Another thing to take care about is the time it takes to calculate the hash, the more complex the hash, the more time it needs, but I'm talking about processing really big batches.

A: If I understand your question correctly your goal is just to generate unique file names. If so, there is no point in reinventing the wheel - every hash function with fixed output length is going to have collisions - just use built in tempnam function.
Manual states:

Creates a file with a unique filename, with access permission set to 0600, in the specified directory. If the directory does not exist, tempnam() may generate a file in the system's temporary directory, and return the full path to that file, including its name.

Following should work well enough:
$targetDirectory = $_SERVER['DOCUMENT_ROOT'] . '/test/uploadify/uploads';
$uploadedFile = $_FILES['Filedata']['tmp_name'];
$targetFile = tempnam($targetDirectory, '');
move_uploaded_file($uploadedFile, $targetFile);

A: It's very small, but the chance is there. You can read more here and here
I suggest you add a salt to the end of the filename to make it practically impossible for files to conflict(You should put the salt in a different md5 function though)
$salt = md5(round(microtime(true) * 1000));
$hash = md5_file($_FILES['Filedata']['tmp_name']);
$targetFile = rtrim($targetPath,'/') . '/' .$hash.$salt.'.'.$extension;

You should then insert the filename in a database so you can access it later.

A: You could always add the systems current time in milliseconds to the filename. That plus the md5, would have a very unlikely chance of returning the same values.


text:
Q: Prevent RXTX from printing version info I am using RXTX 2.1-7 on windows, and I have one issue. Whenever I run a program using the RXTX library, the following generic versioning info gets printed:
Stable Library
=========================================
Native lib Version = RXTX-2.1-7
Java lib Version   = RXTX-2.1-7
This is fine to help debugging, but I would like to disable this printing now that I have the program set up properly. How do I prevent this print?

A: You can disable it by passing the system property -Dgnu.io.rxtx.NoVersionOutput=true, i.e. java -Dgnu.io.rxtx.NoVersionOutput=true yourclass.

A: DZone JavaLobby has an article titled How to Capture System.err and System.out which can help you capture the output.


text:
Q: function for scrabble type game not working (MIT 6.0001 pset 3:) The following code doesn't execute and I don't know why. I get 'syntax error when I try to run it.
SCRABBLE_LETTER_VALUES = {
'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2,
'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1,
'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1,
'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10
}

def get_word_score(word, n):
    char_values = 0
    for char in word:
        char_values += SCRABBLE_LETTER_VALUES[char.lower()]
    if 1 >= (7*len(word) - 3*(n-len(word))):
        print (char_values * 1)
    else:
        print (char_values * (7*len(word) - 3*(n-len(word)))

get_word_score('lazxocijhoaewsfj', 5)

A: You are missing a closing parenthesis for the print statement in the else:
def get_word_score(word, n):
    char_values = 0
    for char in word:
        char_values += SCRABBLE_LETTER_VALUES[char.lower()]
    if 1 >= (7*len(word) - 3*(n-len(word))):
        print (char_values * 1)
    else:
        print (char_values * (7*len(word) - 3*(n-len(word)))) # <-- Need another )


text:
Q: How to enter custom string values into GPString multiValue parameter in 10.4 python toolbox? I am trying to be able to add a list of years (or return periods) to a python toolbox tool I want to create. In the getParametersInfo function, I am currently setting up a parameter as a "GPString" datatype and want it to be a multiValue list. Here is my current code:
import arcpy
class Toolbox(object):
    def __init__(self):
        self.label = "Toolbox"
        self.alias = ""
        # List of tool classes associated with this toolbox
        self.tools = [TestParameters]
class TestParameters(object):
    def __init__(self):
        self.label = "TestParameters"
        self.description = ""
        self.canRunInBackground = False
    def getParameterInfo(self):
        param0 = arcpy.Parameter(
                    displayName ='Do Nothing Here:',
                    name ='in_features',
                    datatype ="GPFeatureLayer",
                    parameterType ='Required',
                    direction ='Input')
        param1 = arcpy.Parameter(
                    displayName ='Enter Return Periods as Years',
                    name ='tbl_features',
                    datatype = "GPString", #"GPValueTable", #"GPTableView", #"DETable", #
                    parameterType ='Required',
                    direction ='Input',
                    multiValue=True)
        param1.filter.type = "ValueList"
        param1.filter.list = []
        params = [param0,param1]
        return params
    def isLicensed(self):
        return True
    def updateParameters(self, params):
        param1.filter.list = []
        return
    def updateMessages(self, params):
        return
    def execute(self, params, messages):
        arcpy.AddMessage("Testing Tool, nothing here yet")
        arcpy.AddMessage(params[1].valueAsText)
        return

However, when I pull up the tool in ArcCatalog and open the tool prompt I get an empty box. I expected that, but the "Add Value" button does not allow me to add any values. I would like to add years values such as "2", "5", "10", "100", "500", & etc...
Am I missing something that should go inside the updateParameters function? Or is there a way to enable the "Add Value" button? It would be nice not to have to hard code year values, as others may be using this script later and may have different years they need to input. This is why I left the param1.filter.list = [] as a blank list, as the ESRI documentation for it doesn't cover how to enter values after the tool is opened.
Or is there a different type of parameter that can easily do this? I've tried the values commented out on the datatype line for param1. If any of those would work, which one might help me be able to customize this?

A: I think this looks counterintuitive, I would do just what you've done so far. Unfortunately, the only way around this problem (when you don't want to present your users with existing list of years) is to use the ValueTable with a single column. Looks like a hack first, but it works well.
The tool after some years have been added:

The tool code after modifications. Just removed all the filters settings and added definition of Value Table columns.
import arcpy
class Toolbox(object):
    def __init__(self):
        self.label = "Toolbox"
        self.alias = ""
        # List of tool classes associated with this toolbox
        self.tools = [TestParameters]

class TestParameters(object):
    def __init__(self):
        self.label = "TestParameters"
        self.description = ""
        self.canRunInBackground = False
    def getParameterInfo(self):
        param0 = arcpy.Parameter(
                    displayName ='Do Nothing Here:',
                    name ='in_features',
                    datatype ="GPFeatureLayer",
                    parameterType ='Required',
                    direction ='Input')
        param1 = arcpy.Parameter(
                    displayName ='Enter Return Periods as Years',
                    name ='tbl_features',
                    datatype = "GPValueTable", #"GPValueTable", #"GPTableView", #"DETable", #
                    parameterType ='Required',
                    direction ='Input',
                    multiValue=True)
        param1.columns =([["GPString", "Period as year"]])
        params = [param0,param1]
        return params
    def isLicensed(self):
        return True
    def updateParameters(self, params):
        return
    def updateMessages(self, params):
        return
    def execute(self, params, messages):
        arcpy.AddMessage("Testing Tool, nothing here yet")
        arcpy.AddMessage(params[1].valueAsText)
        return

The output after clicking OK:

Testing Tool, nothing here yet
2016;2017;2018


text:
Q: You do not have permission to call UrlFetchApp I am trying to capture Web-hooks with Google Sheets and send it to my own api, what i want exactly is to send the row data when it is modified.
Here is the code i added in google apps script.
 function onEdit(e){
  UrlFetchApp.fetch("https:www.url.com/script.php",e);
}

Every time i edited a cell this error accrued.
Google Apps Script: Exception: You do not have permission to call UrlFetchApp.fetch.
Required permissions: https://www.googleapis.com/auth/script.external_request

Here is appscript.json file content
{
  "timeZone": "Pacific/Pago_Pago",
  "dependencies": {
  },
  "exceptionLogging": "STACKDRIVER",
  "oauthScopes": ["https://www.googleapis.com/auth/script.external_request"],
  "runtimeVersion": "V8"
}