text:
Q: Eclipse Java: Eclipse complains of missing curly brace in class the following code in eclipse gives a "}" missing in classbody when in eclipse, but compiles perfectly well from the terminal. Any clues?
package quiz;

    public class Session {
        static int currentQuestion = 0;
        private Sentence[] sentences; // for building questions
        private Question[] questions;

        public void generateReport(Session publishSession) {

        }

        public int  getRightQuestionCount() {

        }

        public int getWrongQuestionCount() {

        }

        public int calculatePercent() {

        }
        public Question getQuestionAtIdx(int index) {
            return questions[index];
        }
        public Question getPreviousQuestion() {
            return getQuestionAtIdx(--currentQuestion);
        }
        public Question getNextQuestion() {
            return getQuestionAtIdx(--currentQuestion);
        }

        public void setQuestionAtIdx(int index, Question) {

        }
    }

A: Toward the end, you're declaring a function with two parameters; for the second parameter you specified the type, but no name. Maybe that's it.
public void setQuestionAtIdx(int index, Question <<missing name>>) {

}

A: that last method
public void setQuestionAtIdx(int index, Question/*has a missing arguement but only its type*/) {

        }

so add
public void setQuestionAtIdx(int index, Question question) {

        }

A: I think the problem is here:
public void setQuestionAtIdx(int index, Question) {        }
Question has no identifier.

A: Eclipse sometimes gets confused.  If the code is syntactically correct, try restarting eclipse.
your code as you pasted above will not compile due to several issues, notably missing parameter names and return values as mentioned above.


text:
Q: Software does not work properly after upgrade to 16.04 The title says already everything.
I upgraded without problems from 15.10 to 16.04 LTS, the icon for Ubuntu Software remained the same, if i open it i get the new GNOME version, but when i search for some apps (like GIMP, or VLC Player) i get "no application found".
Strange, isn't it ?

A: I had the same problem. I got it working by changing the language of the system into English. I think the problem was that the programme descriptions are not available in my language.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Where _should_ I ask for program ideas? I recently asked for program ideas.  I got five downvotes (or more if someone upvoted along the way ;), and the question was closed.
Where should I ask that kind of question?
(No one say Google (or another search engine).  Please.)
Edit:
Think moderately-sized, one-person projects for someone who already can program (at least to some standard).

A: Think moderately-sized, one-person projects for someone who already can program (at least to some standard).
The problem with this approach is that I could suggest to you "make a kazoo database" and since you haven't put any limitations on it, that's a valid answer.  I'm not as familiar with the FAQ on programmers, so I don't know how specific you'd need to be for it to be a valid question.

A: Ask yourself. I've had several of these questions. This is how I fixed it:

*

*Learn one programming language. Well. For me, this was C, I read through K&R and did all the exercises.

*Reinvent the wheel a few times, write a webserver, etc.

*Do Project Euler. Programming is about solving problems, not learning new languages.

*Figure out what you're interested in, for me, this was mathematics, networking and graphics.

*Learn more about what you're interested in

*Try choosing an open source project to join. For me, this was Redis and Apache.
By the time you're done with this, I am sure you will think of something. I guarantee it.

A: This could be an example of, what Jeff and Joel talk so much about on the podcast, simply an inadequate question (don't mean to sound harsh there sorry).
Perhaps what you're really wanting to ask is more along the lines of "Where/How do you find (or what gives you) inspiration for new projects?" or "What are the key / most important characteristics of development project that indicate it will have commercial viability?" or conversely, "what type of development projects should I consider to learn about X?".
Remember, the goal is canonical questions that add value for future visitors.
Even then it may be better on programming or startups stackexchange sites.

A: There is no appropriate place in the Stack Exchange network for "Give me ideas" type posts.  This primarily due to the network focus on trying to find the single best answer for a given question.
These types of questions can accrue tens, and hundreds of answers, all equally valid, and in some cases none particularly useful to the person who asked since they did not define the question narrowly.
Further, there is no "wrong" answer for this type of question.
I'd suggest going to the chat rooms in the languages you are interested in, and asking the people who hang out there what they think - it's more a discussion than a question and answer.

A: Find an open source project that interests you and contribute

A: Have you checked if the Halfbakery is suitable for programming projects?


text:
Q: On exponential polynomials Suppose we have the following function $f:\mathbb{R}^{+}\mapsto \mathbb{R}$
$$f(t)=\sum_{i=1}^k P_i(t)\exp(\alpha_i t),$$
where $\alpha_i$s are all algebraic numbers and $P_i(t)$ are all polynomials with algebraic coefficients and degree less than $m$.
There are several questions that I am interested in.
a. What is the maximal number $p$ such that there is a $t_0$ and for all $r\leq p$
$$f^{(r)}(t_0)=0.$$
b. Suppose $t_1,\cdots,t_q,\cdots$ are the real roots of $f(t)=0$, is it possible to have a converging sequence of $t_q$? In other words, is it possible to have Cauchy sequence $t_i$ such that $f(t_i)=0$? If not, do we have a lower bound of the distance between different roots?
c.Is there an algorithm to decide whether there is some common real root of $f(t)$ and $f'(t)$?

A: a) I'm not sure in general, but if $k=2$ a function of the form $A(t) \exp(t) + A(-t) \exp(-t)$
where $A$ is a polynomial of degree $m-1$ can give you $p=m+1$ if $m$ is odd, or $m+2$ if $m$ is even, with $t_0 = 0$.
b) The function $f$ is entire, so (except in the trivial case where it is identically $0$) its roots are a discrete set, and there can't be any such Cauchy sequences.
c) What do you mean by "compute"?  In most cases, I would expect the roots in question (if there are any) to be transcendental numbers not expressible in "closed form".  For example, this would be the case for
$ f(x) = (t + \cos(t))^2$.  On the other hand, standard numerical methods can be used to get arbitrarily good approximations of roots.


text:
Q: Add extra scripts to a page with header.php include file? I am trying to move the doctype, head, scripts etc, and opening body tags to a header.php include file. I am setting up php variables for page title etc.
All pages use the same scripts except one which needs an extra script.
I can't work out how to do this?
How can I add an extra  tag to a page which uses a header template?
Thanks for any help!

A: Simplest solution:
the script that needs the extra bit:
$show_extra = TRUE;
include('header.php');

header.php
<html>
<head>
if (isset($show_extra) && ($show_extra)) {
   ... output extra bits
}
</head>
etc...

A: You can have a     header($array_scripts) function, that display your header and all the scripts inside.
Let's say your scripts are CSS files, and your files are organized that way :
/www
---- /css
     ---- script1.css
     ---- script2.css
---- index.php
---- header.php

On your page index.php :
include_once("header.php");
$scripts = array("script1.css", "script2.css");
header($scripts);
// Rest of the code : <body>

And in your header.php file :
 function header($array_scripts)
{
  // display everything, like <!doctype HTML>, <head> tag...
  foreach($array_scripts as $script)
  {
     echo '<script src="css/'.$script.'">';
  }
  // close tags like </head>
}

You can even give your title, description, ... as parameters to your header function.
For example, if your header function has this prototype :
header($title, $array_scripts);

You will be able to display the title in header.php with:
// <head> ...
echo '<title>' . $title . '</title>';


text:
Q: can not add other get variable in php mvc I'm using this .htaccess code
    RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l

RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]

and this is my PHP
$url = isset($_GET['url']) ? $_GET['url'] : null;
            $url = rtrim($url, '/');
            $url = explode('/', $url);
            if(empty($url[0])){

etc.
Now I need to add new GET variable in htaccess
I tried this:
RewriteRule ^(.+)$ index.php?url=$1&lang=$2 [QSA,L]

but nothing happenned because I do not understand how to check $_GET['lang'] variable
when it may or may not exist. Also $_GET['url'] variable may be a string such as
categories,companynane,employee
or it might only be categories or categories,companyname or may be NULL.
I do not understand how to check this lang variable from the link like this:
http://mydomain.com/categories/companynane/employee/en
it is my updated class.
<?php
    class Bootstrap {
        public function __construct(){
            $url = isset($_GET['url']) ? $_GET['url'] : null;
            $url = rtrim($url, '/');
            $url = explode('/', $url);
            if(empty($url[0])){
                require Controllers.'main.php';
                $controller = new main();
                $controller->Index();
                return false;
            }
            $file = Controllers.$url[0].'.php';
            if(file_exists($file)){
                require $file;
            }else{
                $this->error();
            }
            $controller = new $url[0];
            $controller->loadmodel($url[0]);
            if(isset($url[3])){
                $_SESSION['lang'] = $url[3];
                if(method_exists($controller, $url[1])){
                    $controller->{$url[1]}($url[2]);
                }else{
                    $this->error();
                }
            }else{
                if(isset($url[2])){
                    $testinglang = $this->_new->checklang($url[2]);
                    if($testinglang == true){
                        $_SESSION['lang'] = $url[2];
                        if(method_exists($controller, $url[1])){
                            $controller->{$url[1]}();
                        }else{
                            $this->error();
                        }
                    }else{
                        if(method_exists($controller, $url[1])){
                            $controller->{$url[1]}($url[2]);
                        }else{
                            $this->error();
                        }
                    }
                }else{
                    if(isset($url[1])){
                        $testinglang = $this->_new->checklang($url[1]);
                        if($testinglang == true){
                            $_SESSION['lang'] = $url[1];
                            $controller->Index();
                        }else{
                            if(method_exists($controller, $url[1])){
                                $controller->{$url[1]}();
                            }else{
                                $this->error();
                            }
                        }
                    }else{
                        $controller->Index();
                    }
                }
            }
        }
        function error(){
            require Controllers.'error.php';
            $controller = new error();
            $controller->Index();
            return false;
        }

    }

I think everything is good except $url[0].
what about if $url[0] exists and is language?
or may be it is controller
please tell me how to check this.

A: In order to use $2 you need another pair of ()
So I guess you want something like that:
RewriteRule ^(.+)/(.+)$ index.php?url=$1&lang=$2 [QSA,L]

That would match http://mydomain.com/categories/en
Then you can do in php:
$lang = isset($_GET['lang']) ? $_GET['lang'] : null;
if ($lang == 'en') {
    // do something in english
}

After we ironed out your real problem, this should help:
Leave the RewriteRule as it was:
RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]

In php do after the code to fill $url:
$lang = array_pop($url);

array_pop returns the last element of an array. In your case this is the language. After that it will no longer be in $url, but you have $lang no matter how your URL looks like.


text:
Q: How do you tell if a particular column is in a table? I would like to know what query to use to determine if a particular table column exists in a given table.
For example I would like to know if the column named Address_1 exists in the table named Visits.
I think it is in a data dictionary table maybe.

A: Edit: As pointed out by @tidwall, this answer is for SQL Server and won't work for sqlite. This stackoverflow thread has the right answer for sqlite.

SELECT name
FROM sysobjects
WHERE id IN (
    SELECT id
    FROM syscolumns
    WHERE name = 'THE_COLUMN_NAME'
)

also, this yields all the table column information for your parsing enjoyment:
SELECT COLUMN_NAME, data_type, character_maximum_length
FROM information_schema.columns
WHERE TABLE_NAME = 'your_table_name'


text:
Q: SyntaxError: Unexpected token # while displaying text file My task is to display a simple property file in an html page using AngularJS.
The property files looks something like this :
#
key1=value1
key2=value2
The hash "#" symbol refers to lines with comments in the property file
I m reading the file content and returning the it as a String from my REST api.
   @GET
   @Path("/showFile")
   @Produces(MediaType.APPLICATION_JSON)
   public String showFile() {
/*some logic */
return content;
}

And my Angular code is
$scope.getFile = function() {
        $http.get("service/showFile").success(function(content) {
            $scope.fileContent = content;
            console.log(content);
            console.log("Scope variable\n"+$scope.fileContent);
        });

I get the file contents correctly from the service, but while parsing the lines with the hash"#" symbol I get the Unexpected token error. Please suggest a workaround to parse '#'.


text:
Q: TypeError: 'int' object is not callable when summing up matrix diagonals I need help with understanding what in my code is causing the error below:
The whole trace back is here:
    Traceback (most recent call last):

  File "C:\Users\AppData\Local\Temp/ipykernel_18232/558242258.py", line 1, in <module>
    diagonalDifference(arr)

  File "C:\Users\AppData\Local\Temp/ipykernel_18232/2138727441.py", line 3, in diagonalDifference
    m = sum([arr[i][i] for i in range(n)])

TypeError: 'int' object is not callable

n = int(input().strip()) # n for n*n mat
arr = []
for _ in range(n):
   arr.append(list(map(int, input().rstrip().split())))  #takes n times inputs, each time n space separated integer

def diagonalDifference(arr):
        n = len(arr)
        m = sum([arr[i][i] for i in range(n)])
        o = sum([arr[i][n-i-1] for i in range(n)])
        return abs(m-o)

thank you
PS. thank you for your suggestion. I saw this suggestion of renaming any possible sum or int variables. but I do not have any of those anywhere in my code.

A: As @Kemp said, you are trying to use an int as a function in the line your error message points to.
The two keywords you are using as a function are sum and range. So it is likely you have a line somewhere in your code where you assign an int to one of those two keywords.
look for sum = or range = in your code and rename them.


text:
Q: Whats the right way to encode an umlaut in a dataURI I  have a small script that let the user save a CSV file using dataURI. Unfortunately there are some problems with german umlauts, so Käufe will become Käufe. The href with the dataURI is created like this:
'data:application/csv;charset=utf-8,' + encodeURIComponent(csvString)

A: It's very likely not a problem of the encoding in the URL, but of whoever is interpreting that data later not understanding that it's encoded in UTF-8 and interpreting it in Latin-1 instead. There is no "right way" to encode non-ASCII characters in a URL. URLs can only consist of a subset of ASCII characters, period. For anything else there's the percent encoding method to encode arbitrary bytes to the %xx format. What encoding those bytes represent is entirely up to you and is entirely up to the recipient to interpret in the correct encoding.


text:
Q: Trouble with Python file I/O and lists So I have to do a Python programming assignment with lists and input and output files and I am stuck. I have to look up triangles with a name, color, and perimeter. The triangles are in a .txt file that looks like this:
Triangle1,red,0,0,0,1,1,0
Triangle2,blue,1,0,0,1,0,0
GeorgeJetson,BLUE,20.1,10.5,23,5,6,33.3
Triangle4,BlUe,10,10,20,20,0,0
Triangle2,red,1,1,0,1,0,0
Gusty,orange,0,0,0,2,2,2
Gusty,red,0,0,0,2,2,2
triangle2,orange,0,0,0,2,2,2

My code thus far is this:
from math import sqrt

def peri(x1,y1,x2,y2,x3,y3):
    side1 = sqrt(((x1-x2)**2)+((y1-y2)**2))
    side2 = sqrt(((x2-x3)**2)+((y2-y3)**2))
    side3 = sqrt(((x1-x3)**2)+((y1-y3)**2))
    p = side1 + side2 + side3
    return p

def main():
    # Handshake
    print("This program performs database processing.")
    # Prompt for input and output file names
    infileName = input("Enter input file name: ")
    outfileName = input("Enter output file name: ")

    # Open input file name and read it
    infile = open(infileName,"r")

    # Read file, create triangle list
    trilist = []
    for line in infile:
        name,color,x1,y1,x2,y2,x3,y3 = line.split(",")
        x1 = eval(x1)
        y1 = eval(y1)
        x2 = eval(x2)
        y2 = eval(y2)
        x3 = eval(x3)
        y3 = eval(y3)
        perimeter = peri(x1,y1,x2,y2,x3,y3)
        triangle = name,color,perimeter
        trilist.append(triangle)

    # Close input file
    infile.close()

    LowerCaseOutfile = False
    AscendingOutfile = False
    print("")
    print("Commands:")
    print("perimeterbyname: Display triangle perimenters by name")
    print("perimeterbycolor: Display triangle perimenters by color")
    print("namebycolor: Display triangle names by color")
    print("colorbyname: Display triangle colors by name")
    print("lowercase: Display triangle names and colors in lowercase")
    print("ascending: Display triangle perimeters in ascending order")
    print("quit: Quit the program")
    print("")
    userInput = input("Enter a command: ")
    while userInput != "quit":
        if userInput == "perimeterbyname":
            triname = input("Enter a triangle name: ")
            for triangle in trilist:
                if triname == name:
                    print(triangle)
                else:
                    print("Invalid name")

        print("")
        print("Commands:")
        print("perimeterbyname: Display triangle perimenters by name")
        print("perimeterbycolor: Display triangle perimenters by color")
        print("namebycolor: Display triangle names by color")
        print("colorbyname: Display triangle colors by name")
        print("lowercase: Display triangle names and colors in lowercase")
        print("ascending: Display triangle perimeters in lascending order")
        print("quit: Quit the program")
        print("")
        userInput = input("Enter a command: ")

    # Open output file name and write it
    outfile = open(outfileName, "w")

    # Write to the output file
    print(trilist, file = outfile)

    # Close output file
    outfile.close()

    print("Triangles have been written to", outfileName)

main()

I am having trouble getting the name of the triangle from the list in the if statement. Python does not recognize the variable "name". Help?

A: I'm guessing you're talking about while in the loop to print out a triangle only if it matches the user input. The reason that "name" isn't valid there is that python doesn't store what variables you used when creating the list of triangles, only their value. Thus, when you're reading them out again, it's just a value.
So, each trilist (which is a list of tuples) is:
[("name","color",perimeter),("name","color",perimeter)] where "name", "color" and perimeter are the actual values of each triangle.
Now you can do either pull out the values of the tuple into separate variables:
name, color, perimeter = triangle

inside your for loop and then use the variables as you'd expect or just manually index the tuple directly:
name = triangle[0]

Now, to bring that together, you can actually write your for loop in two ways:
        # leave triangle as a tuple
        for triangle in trilist:
            if triname == triangle[0]:
                print(triangle)
            else:
                print("Invalid name")

or:
        # assign elements of tuple to separate variables
        for name,color,perimeter in trilist:
            if triname == name:
                print(triangle)
            else:
                print("Invalid name")


text:
Q: How to filter array in react native? I have array
 const arr = [
    {id: 1, country: 'Austria'},
    {id: 2, country: 'Germany'},
    {id: 3, country: 'Austria'},
  ];

I tried the following the code to filter it.
arry.map((item,idx) => (
   item.country== "Austria"?(
       console.log(item.id)
   )
   :
   null
))

The output is

1 3

,
but I want to get output after whole filter like

1,3

I want only the IDs where country is Austria as given below.

1,3

A: use reduce function

const arry = [
    {id: 1, country: 'Austria'},
    {id: 2, country: 'Germany'},
    {id: 3, country: 'Austria'},
  ];

   const result = arry.reduce((acc,item,idx) => {

          if(item.country == "Austria"){
             if(idx === 0) acc += item.id
             else acc += `,${item.id}`
           }

           return acc

    }, '')

    console.log(result)

A: This is How I Filter
const arry = [
    {id: 1, country: 'Austria'},
    {id: 2, country: 'Germany'},
    {id: 3, country: 'Austria'},
];

const result = arry.filter((item, index) => {

      if(item.country == "Austria"){
         return true
       }

       else{
        return false
       }

})

console.log(result)

A: One line answer:
arr.filter(i => i.country == 'Austria')


text:
Q: XML Feed not displaying all records only random My XML feed is here
http://xml.betfred.com/football-bonus.xml
This is the code I use for a different sport which I've just copied into a new page
<?php
function FBList() {
$xmlData = 'http://xml.betfred.com/football-bonus.xml';
$xml = simplexml_load_file($xmlData);
$curdate = date('d/m/Y');

$new_array = array();

foreach ($xml->event as $event) {
//    if ($limit == $c) {
//        break;
//    }
//    $c++;
    $eventd = substr($event->attributes()->{'date'},6,2);
    $eventm = substr($event->attributes()->{'date'},4,2);
    $eventy = substr($event->attributes()->{'date'},0,4);
    $eventt = $event->attributes()->{'time'};
    $new_array[$eventy.$eventm.$eventd.$eventt] = array(
        'eventd' => $eventd,
        'eventm' => $eventm,
        'eventy' => $eventy,
        'eventt' => $eventt,
        'eventdate' => $eventd.'/'.$eventm.'/'.$eventy,
        'eventid' => $event->attributes()->{'eventid'},
        'eventtime' => $event->attributes()->{'time'},
        'eventname' => $event->attributes()->{'name'},
        'venue' => $event->attributes()->venue,
        'riders' => $event->bettype->bet,
        'bettypeid' => $event->bettype->attributes()->{'bettypeid'},
    );
}

ksort($new_array);
$limit = 10;
$c = 0;
foreach ($new_array as $event_time => $event_data) {
    $racedate = $event_data['eventy'].$event_data['eventm'].$event_data['eventd'];
    $today = date('Ymd');
    if($today == $racedate){
    //  if ($limit == $c) {
    //    break;
    //}
    //$c++;
    $replace = array("/"," ");
    $riderscnt = $event_data['riders']->count();
    $eventname = str_replace($replace,'-', $event_data['eventname']);
    $venue = str_replace($replace,'-', $event_data['venue']);
    echo "

".$event_data['eventtime']."

".$event_data['venue'].' - '.$event_data['eventname']."

";

}
}
}
?>

ok now ignore the fact there are random horse racing related references in teh code
the XML structure between the 2 are identical
however the above code is only displaying these entries
1245 - Wycombe v Aston Villa
1330 - Linlithgow Rose v Forfar
1400 - Carpi v Udinese
1500 - Barcelona v Granada
1600 - Lyon v Troyes
1700 - Fiorentina v Lazio
1715 - Sevilla v Athletic Bilbao
1730 - Hearts v Aberdeen
1830 - Vitoria Guimaraes v Arouca
1900 - Rennes v Lorient
1930 - Real Madrid v Deportivo
1945 - Roma v AC Milan
2105 - Levante v Rayo Vallecano
Im sure you'll notice there are TONS missing
Any help would be appreciated as this is annoying me beyond belief

A: I realise you already have an answer but I thought I'd post this here anyway - it continues from the other post earlier.
<?php

    echo '
    ';

    $eid=25573326.20;

    $events=(object)array(
        'horses'    =>  (object)array(
            'url'   =>  'http://xml.betfred.com/Horse-Racing-Daily.xml',
            'query' =>  '//event/bettype[ number( @bettypeid )="'.$eid.'" ]'
        ),
        'football'  =>  (object)array(
            'url'   =>  'http://xml.betfred.com/football-bonus.xml',
            'query' =>  '//event/bettype'
        )
    );

    #$obj=$events->horses;
    $obj=$events->football;

    /* create the DOM object & load the xml */
    $dom=new DOMDocument;
    $dom->load( $obj->url );

    /* Create a new XPath object */
    $xp=new DOMXPath( $dom );
    /* Search the DOM for nodes with particular attribute - bettypeid - use number function from XSLT to test */
    $oCol=$xp->query( $obj->query );

    /* If the query was successful there should be a nodelist object to work with */
    if( $oCol ){

        echo "
";

        foreach( $oCol as $node ) {
            echo '

'.$node->parentNode->getAttribute('name').' - [ '.$node->getAttribute('name').' ]

'.date( 'D, j F, Y H:i:s', strtotime( $node->getAttribute('bet-start-date').' '.$node->parentNode->getAttribute('time') ) ).'
';

            foreach( $node->childNodes as $bet ){
                echo "
Name: {$bet->getAttribute('name')} ID: {$bet->getAttribute('id')} Price: {$bet->getAttribute('price')}
";
            }
            echo '
';
        }
        echo "
";

    } else {
        echo 'XPath query failed';
    }
    $dom = $xp = $col = null;
?>

A: When you create entries in new array you add date and time as the key:
$new_array[$eventy.$eventm.$eventd.$eventt] = array(...

When you have matches starting at the same date and time it will overwrite the old entry.
Maybe try
$eventid = $event->attributes()->{'eventid'};
$new_array[$eventy.$eventm.$eventd.$eventt.$eventid] = array(...

to get unique keys.


text:
Q: Connect to linked server (Oracle) in SQL Server using Instant Client I need to connect to a remote database (Oracle) using a MS SQL Server (2019) linked server. What I did so far:

*

*Installed Oracle Instant Client x64 and the ODBC drivers on the machine where the SQL server is running

*Created a symlink to the central TNSNAMES.ORA (on a file share in the network) inside the Oracle Instant client folder.

*Set the necessary environment variables

*Created an ODBC connection to the database on the Oracle server on this machine

*Restarted MS SQL Server

*Created a linked server (Microsoft OLEDB Provider for ODBC Drivers) in the SQL instance

When connecting to the SQL Server using sqlcmd on this machine (I did not install SSMS there), I can query the linked database using OPENQUERY(). I can also read the file TNSNAMES.ORA using this command (note, the given file is the symlink, but it displays the contents of the linked file, as it should):
SELECT * FROM OPENROWSET(BULK 'C:\InstantClientx64\tnsnames.ora', SINGLE_CLOB) TNSNames

So far, everything is fine.
Now, when I connect to the SQL Server from my workstation using SSMS, i get the following error when trying to read TNSNAMES.ORA using the command above:
Cannot bulk load because the file "C:\InstantClientx64\tnsnames.ora" could not be opened. Operating system error code 5(Access is denied.).

I created a file test.txt in the instant client folder containing something like "Am I allowed to read this?" - and I was, no problems.
I started procmon on the server to find out what happens. When using the above command on the SQL server,  I get a REPARSE (because it's a link!), and then SUCCESS, the file is displayed in the sqlcmd console.
When using this command in SSMS (on my local workstation), first appears the REPARSE (OK), then ACCESS DENIED.
In both cases it is the same user account which is displayed as "Impersonating" in the procmon's details. There is definitely no problem with a firewall, and the read permissions on the tnsnames.ora file on the network share are granted for Everyone. I am also able to create an ODBC item on the local workstation, and can connect and query the database from here.
I have done this in the past I don't know how often, and never had problems. What am I missing?

A: Why are you trying to read the tnsnames.ora file via SQL?  The Oracle libraries will (should) internally open it and use it when your app connects to the DB.
The default location for network config files is shown in the Instant Client installation doc.  In your case it will be C:\InstantClientx64\network\admin.  Unless you have set the TNS_ADMIN variable, then start by creating this subdirectory and putting tnsnames.ora in it.
(A future version of Instant Client on Windows will create the network\admin subdirectory automatically, similar to the way it is created with the Linux Instant Client packages).


text:
Q: creating and copy/duplicating a select/option list menu with JavaScript I have a select list menu:
<label>
    <select name="select" id="select1">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
    </select>
</label>

I want to duplicate it with the exact informations dynamically. I can do that by creating a select element and copying the innerHTML from the first select. (I also generate a table row which my select is going to be on, but it's not important):
var selectt = document.createElement("select");
selectt.setAttribute("name", "select"+counter);
selectt.setAttribute("id", "select"+counter);
selectt.onchange = function() {sellcalculate(counter);

cell3.appendChild(selectt);
document.getElementById("select"+counter).innerHTML=document.getElementById("select1").innerHTML;

It works fine on Firefox, but IE just creates the select but wouldn't copy the options.
My second question is: how can I add an onchange event to the created element?
 selectt.onchange = function(){sellcalculate(counter)};

This doesn't seems to work.
here is the compelete function after edit  function and solving the ie problem :
function addRow(tableID) {
    var counter = document.getElementById('rowcounter').value;
    counter++;
    document.getElementById('rowcounter').value = counter;
    var table = document.getElementById(tableID);
    var rowCount = table.rows.length;
    var row = table.insertRow(rowCount);
    var cell = row.insertCell(0);
    var cell2 = row.insertCell(1);
    var element2 = document.createElement("input");
    element2.type = "text";
    element2.id = "amount" + counter;
    element2.onchange = function () {
        sellcalculate(counter)
    };
    cell2.appendChild(element2);
    var cell3 = row.insertCell(2);
    var selectt = document.createElement("select");
    selectt = document.getElementById("select1").cloneNode(true);
    selectt.setAttribute("name", "select" + counter);
    selectt.setAttribute("id", "select" + counter);
    selectt.onchange = (function (cntr) {
        return function () {
            sellcalculate(cntr);
        };
    })(counter);
    cell3.appendChild(selectt);
}

A: I can't test in IE right now, but try using .cloneNode() instead to create the new element.
var selectt = document.getElementById("select1").cloneNode(true);

selectt.setAttribute("name", "select"+counter);
selectt.setAttribute("id", "select"+counter);
selectt.onchange = (function( cntr ) {
    return function() { sellcalculate(cntr); };
})( counter );

cell3.appendChild(selectt);

The true argument passed to .cloneNode makes it a deep clone (all descendants).
Also, I assumed you want the onchange handler to reference the current value of counter instead of a potentially different future value. As such, I scoped the current value using a new function invocation.
Now whatever the value of counter is when this code runs will be the value passed to sellcalculate().

A: You can use jQuery .clone() like this:
$('#select1').clone().attr({'id':'select'+counter, 'name':'select'+counter}).appendTo('cell3Selector');

Test page here.


text:
Q: Google new spreadsheet Split() function bug? try this.
in cell A1 10/8/2013 Mike1, 2013, 0
now Split(A1,",")
now change A1 and add a colon 10/8/2013 Mike:1, 2013, 0
Split(A1,",") ... notice how Mike:1 is gone. Bug?
I need to split something with a colon in it and it is chopping off part of the text

A: The problem is that "10/8/2013 Mike:1" is interpreted as a date, it seems to be something like: "dd/mm/yyyy hhhh:mm". (if you change the display of the first cell to raw text you'll see he is giving you a number: 41496).
try this formula:
=arrayformula(SUBSTITUTE(arrayformula(split(REGEXREPLACE(A1;":";"#@#");","));"#@#";":"))

in a easier way: As I suppose you can't change the way it's displayed, the possible workaround that I see here is to first split around the ":", then split with the "," and then join the two first elements.

A: I can't reproduce this issue, either with function SPLIT or with Split text into columns... and with or without formatting as dd/mm/yyyy hhhh:mm.
Select A1, Data > Split text into columns... is all that is required.


text:
Q: bs4 : insert new tag in a tag according to a specific attribute After some research, I can't find adequate solutions: For example, i want to insert the tag 'b' inside a tag 'a' when 'id=2'  :
<?xml version"1.0 encoding="utf-8?>

I'm thinking about something like : soup.a.has_key('2').append(b)
but it doesn't work...
Some help ?

A: Perhaps you can use
from bs4 import BeautifulSoup as bs
s="""

"""

soup = bs(s)
nt = soup.new_tag('b')
soup.find(id="2").append(nt)

First a new  tag is created using new_tag(), the tag with id="2" is found with find() and the new tag is appended with append().


text:
Q: How do I combine a SELECT + WHERE query with an INSERT query? I want to combine the two following queries, can anyone give me a idea how to do that?
(the INSERT query should run only if the SELECT query has a result)
query no 1:
INSERT IGNORE INTO senders(
sender_id,
telephone,
)
VALUES ( 1, 0723355888)

query no 2:
SELECT student_name
FROM students
WHERE student_id =1

A: INSERT INTO senders (sender_id, telephone)
SELECT student_id, student_telephone FROM students
WHERE student_id = 1
LIMIT 1

or if telefone is not a part of the students table, hard code it:
This works because if the query 0 rows, no insert is performed at all.
INSERT INTO senders (sender_id, telephone)
SELECT 1, 0723355888 FROM students
WHERE student_id = 1
LIMIT 1

A: try using this query -
INSERT IGNORE INTO senders (sender_id, telephone)
SELECT student_id as sender_id, telephone
FROM students
WHERE student_id=1

A: try this:
INSERT IGNORE INTO senders( sender_id, telephone)
SELECT 1 as sender_id, 0723355888 as telephone
FROM students WHERE student_id =1


text:
Q: access private variable from other class in java i hope that i mean my words.
i have a class like this:
public class MainClass extends JFrame{
    private JLabel mainlabel;
    private SampleClass sample=new SampleCalss();

    public void intital(){
        mainlabel=new JLabel("Main");
        sample.setMethod(getLabel());
        //
        //some code
        //
        add(mainlabel);
    }

    public static void main(){
        intital();
    }

    public JLabel getLabel(){
        return mainlabel;
    }
}

and other class like this:
public class SampleClass extends JFrame{
    private JButton button=new JButton("Change");
    private JLabel sLabel;

    public SampleClass(){
        //somecode
        //
        button.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                sLabel.setText("Sample text set");
            }
        });
        add(jButton);
    }

    public void setMethod(JLabbel l){
        sLabel=l;
    }
}

is this a true way to access mainlabel and change its value from other class(in this sample code in class SampleClass) is there a better or right solution?
note that MainClass is class that has main method.

A: The correct way to access a private variable from another class is with getter and setter methods. Otherwise, you should have made that variable public.
That is:
// getter
public JLabel getMainLabel() {
    return mainlabel;
}

// setter
public void setMainLabel(JLabel mainLabel) {
    this.mainlabel = mainLabel;
}

However, it is a bad practice to return private data directly - that allows external code to modify your private state. In general, you should return a copy of your private data so that external code can't mess with the internals of your class. But if you need external code to call methods on your private data, then you should probably be providing manipulation methods in your class, rather than directly exposing private data.
You probably really want to create methods like setText() and getText() in your main class, and then call the setText() and getText() methods on mainlabel. However, you need to be careful with this, as you might be inclined to replicate every single method defined by JLabel in your class. That would tightly couple both your class and its consumers wit the JLabel implementation. If you choose to replace the JLabel with something else in the future, it will take a lot of work to unwind the coupling you've created.

A: You can use Java Reflection to access the private variables and change the values.
http://download.oracle.com/javase/tutorial/reflect/member/fieldValues.html
Why not expose the mainlabel through setMainLabel ?
public void setMainLabel(JLabel mainLabel) {
    this.mainlabel = mainLabel;
}

A: In class, private variables can be used without explicitly calling getter method for private variable.
So it would be like below for the first class
sample.setMethod(mainlabel);

And your assumption for setting private variable in different class by using setter method is correct.

A: The problem with your method is if MainClass ever changes its JLabel (by creating a new one), SampleClass still has a reference to the old one. You can give SampleClass a reference to MainClass via the constructor or a setter method:
public class SampleClass extends JFrame{
private JButton button=new JButton("Change");
private MainClass main;

public SampleClass(MainClass main)
{
    this.main = main;
    // do stuff
}

And whenever you need to access MainClass' label, call its getter method:
main.getLabel();

A: Create a mutator method that will allow  access to the private variable
public void setLabel(JLabel _label) {

mainlabel = _label;
}


text:
Q: H264 //RTSP using Android phone I would like to create a VR so I created a RTSP server to link to my Zedmini. It is working if I use a h265 encoder, but the bad thing is the RTSP only works if I use Iphone7 VLC app or computer window 8 VLC software, my Android phone huawei p7 Onvifer app cannot use this RTSP address at all. I need to use huawei p7 for my project as I am going to create the app and link to this RTSP server.
Based on my checking, Some Android device do not support h265 encoder, so I decided to use h264 and I have been googling a lot for few weeks but became frustrated for not finding a solution to use h264.
This is the code which I amend from test-readme.c------>
#include <gst/gst.h>

#include <gst/rtsp-server/rtsp-server.h>

int main (int argc, char *argv[]) { GMainLoop *loop; GstRTSPServer *server; GstRTSPMountPoints *mounts; GstRTSPMediaFactory *factory;

gst_init (&argc, &argv);

loop = g_main_loop_new (NULL, FALSE);

/* create a server instance */ server = gst_rtsp_server_new ();

/* get the mount points for this server, every server has a default object

that be used to map uri mount points to media factories */ mounts = gst_rtsp_server_get_mount_points (server);
/* make a media factory for a test stream. The default media factory can use

gst-launch syntax to create pipelines.
any launch line works as long as it contains elements named pay%d. Each
element with pay%d names will be a stream */ factory = gst_rtsp_media_factory_new ();
//working case for streaming video //gst_rtsp_media_factory_set_launch (factory,"( videotestsrc is-live=1 ! x264enc ! rtph264pay name=pay0 pt=96 )");

//working case for external camera //gst_rtsp_media_factory_set_launch (factory,"( v4l2src is-live=1 device=/dev/video1 ! video/x-raw, width=(int)720, height=(int)480 framerate=30/1 format=I420 ! timeoverlay ! omxh265enc ! rtph265pay name=pay0 pt=96 )");

//working case for JX2 camera //gst_rtsp_media_factory_set_launch (factory,"( nvcamerasrc sensor-id=0 ! video/x-raw(memory:NVMM), width=1920, height=1080, framerate=30/1, format=I420 ! nvvidconv flip-method=4 !video/x-raw, width=(int)720, height=(int)480 framerate=30/1 format=I420 ! timeoverlay ! omxh265enc ! rtph265pay name=pay0 pt=96 )");

//Fail or not working case for Zed mini camera testing FOR H264 gst_rtsp_media_factory_set_launch (factory,"(v4l2src is-live=1 device=/dev/video1 ! video/x-raw, width=2560, height=720, framerate=30/1, format=I420 ! nvvidconv !video/x-raw, width=(int)720, height=(int)480, framerate=30/1, format=NV12 ! omxh264enc bitrate=10000000 ! rtph264pay name=pay0 pt=96 )");

//working case for Zed mini camera FOR H265 //gst_rtsp_media_factory_set_launch (factory,"(v4l2src is-live=1 device=/dev/video1 ! video/x-raw, width=2560, height=720, framerate=30/1, format=I420 ! nvvidconv !video/x-raw, width=(int)720, height=(int)480 framerate=30/1 format=I420 ! timeoverlay ! omxh265enc ! rtph265pay name=pay0 pt=96 )");

gst_rtsp_media_factory_set_shared (factory, TRUE); /* attach the test factory to the /test url */ gst_rtsp_mount_points_add_factory (mounts, "/test", factory);

/* don't need the ref to the mapper anymore */ g_object_unref (mounts);

/* attach the server to the default maincontext */ gst_rtsp_server_attach (server, NULL);

/* start serving */ g_print ("stream ready at rtsp://172.16.124.75:8554/test\n"); g_main_loop_run (loop);

return 0; }

This code is working on streaming video, JX2 camera, simple USB camera (low end), also zedmini camera but using h265. I need the code to run using h264, there must be some element missed out here or wrong.
gst_rtsp_media_factory_set_launch (factory,"(v4l2src is-live=1 device=/dev/video1 ! video/x-raw, width=2560, height=720, framerate=30/1, format=I420 ! nvvidconv !video/x-raw, width=(int)720, height=(int)480, framerate=30/1, format=NV12 ! omxh264enc bitrate=10000000 ! rtph264pay name=pay0 pt=96 )");


text:
Q: How to connect to POSTGRESQL in Codeigniter 3? I am trying to connect to PostgreSQL using Codeigniter framework.
Now in my database.php
I have the following code :
$active_group = 'default';
$query_builder = TRUE;

$db['default'] = array(
    'dsn'   => '',
    'hostname' => 'localhost',
    'username' => 'postgres',
    'password' => '',
    'database' => 'fmsdb',
    'dbdriver' => 'postgre',
    'dbprefix' => '',
    'pconnect' => FALSE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);

But When I run my site in localhost, I get following database error :

A PHP Error was encountered
Severity: Warning
Message: pg_connect(): Unable to connect to PostgreSQL server: could
  not connect to server: Permission denied Is the server running on host
  "localhost" (::1) and accepting TCP/IP connections on port 5432? could
  not connect to server: Permission denied Is the server running on host
  "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432?
Filename: postgre/postgre_driver.php
Line Number: 154

I tried putting this in my PostgreSQL.conf file :
listen_addresses = '*'

Where am I going wrong?

A: Tested with Codeigniter 4, PHP 7.3 and PostgreSQL 9.3.5:
1) Enable in your php.ini
extension=php_pgsql.dll

2) In app/Config/Database class override your $default property as follows:
/**
 * The default database connection.
 *
 * @var array
 */

public $default = [
    'DSN'      => '',
    'hostname' => 'your_host',
    'username' => 'your-user',
    'password' => 'your-password',
    'database' => 'your-database',
    'DBDriver' => 'postgre',
    'DBPrefix' => '',
    'pConnect' => false,
    'DBDebug'  => (ENVIRONMENT !== 'production'),
    'cacheOn'  => false,
    'cacheDir' => '',
    'charset'  => 'utf8',
    'DBCollat' => 'utf8_general_ci',
    'swapPre'  => '',
    'encrypt'  => false,
    'compress' => false,
    'strictOn' => false,
    'failover' => [],
    'port'     => 5432, //the default port
];

A: First enable Postgresql extension in php.ini
extension=php_pgsql.dll
You also can enable Postgresql extension for PDO as well.
extension=php_pdo_pgsql.dll

$db['default'] = array(
    'port'   => 5432, # Add
);

OR
$db['default'] = array(
    'dsn'   => 'pgsql:host=localhost;port=5432;dbname=database_name',
    'dbdriver' => 'pdo',
);

Database-configuration in codeigniter.com

A: *

*First enable these two extensions
extension=php_pgsql.dll
extension=php_pdo_pgsql.dll

*Then restart apache

*Add $db['default']['port'] = 5432 in database.php file with all other codes.


text:
Q: Not able to set data in guacamole clipboard I am using Apache Guacamole library in our project for rendering Windows VM in web browser.
For Clipboard integration I need to transfer clipboard content from Local System to remote VM (guacamole Clipboard) and vice versa.
I am able to get the clipboard content of remote VM using the guacamole onclipboard event. But I am unable to send Local System clipboard content to remote VM (Guacamole clipboard).I am using createClipboardStream() API for setting data to guacamole clipboard but I am not getting any data in remote VM clipboard.
Please find the code snippet as below -
Guacamole API reference -
https://guacamole.apache.org/doc/0.9.2/guacamole-common-js/symbols/Guacamole.Client.html#createClipboardStream
// sending Local System Clipboard content to Remote VM (Guacamole Clipboard)
function setGuacamoleClipboard(data) {
    var stream = guac.createClipboardStream("text/plain");
    var writer = new Guacamole.StringWriter(stream);
    for (var i=0; i<data.length; i += 4096){
        writer.sendText(data.substring(i, i+4096));
    }
    writer.sendEnd();
}

I have also tried below Java code for setting guacamole clipboard using writeInstruction().This approach also did not work for me
tunnel.getSocket().getWriter().writeInstruction(new GuacamoleInstruction("clipboard","text/plain","Welcome Guacamole clipboard"));

Am I missing anything ?


text:
Q: GitHub - fatal: could not read Username for 'https://github.com': No such file or directory I have the following problem when I try to pull code using git Bash on Windows:
fatal: could not read Username for 'https://github.com': No such file or directory

I already tried to implement the accepted solution provided here:

*

*Error when push commits with Github: fatal: could not read Username
However the problem still persists.
After adding/removing origin I still get the same error.
Could advise on this issue?
Thanks!

A: This error can also happen when trying to clone an invalid HTTP URL.  For example, this is the error I got when trying to clone a GitHub URL that was a few characters off:
$ git clone -v http://github.com/username/repo-name.git
Cloning into 'repo-name'...
Username for 'https://github.com':
Password for 'https://github.com':
remote: Repository not found.
fatal: Authentication failed for 'https://github.com/username/repo-name.git/'

It actually happened inside Emacs, though, so the error in Emacs looked like this:
fatal: could not read Username for 'https://github.com': No such device or address

So instead of a helpful error saying that there was no such repo at that URL, it gave me that, sending me on a wild goose chase until I finally realized that the URL was incorrect.
This is with git version 2.7.4.
I'm posting this here because it happened to me a month ago and again just now, sending me on the same wild goose chase again.  >:(

A: TL;DR: check if you can read/write to /dev/tty. If no and you have used su to open the shell, check if you have used it correctly.
I was facing the same problem but on Linux and I have found the issue. I don't have my credentials stored so I always input them on prompt:
Username for 'https://github.com': foo
Password for 'https://foo@github.com':

The way how git handles http(s) connections is using /usr/lib/git-core/git-remote-https
you can see strace here:
stat("/usr/lib/git-core/git-remote-https", {st_mode=S_IFREG|0755, st_size=1366784, ...}) = 0
pipe([9, 10])                           = 0
rt_sigprocmask(SIG_SETMASK, ~[RTMIN RT_1], [], 8) = 0
clone(child_stack=NULL, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7f65398bb350) = 18177
rt_sigprocmask(SIG_SETMASK, [], NULL, 8) = 0
close(10)                               = 0
read(9, "", 8)                          = 0
close(9)                                = 0
close(5)                                = 0
close(8)                                = 0
dup(7)                                  = 5
fcntl(5, F_GETFL)                       = 0 (flags O_RDONLY)
write(6, "capabilities\n", 13)          = 13
fstat(5, {st_mode=S_IFIFO|0600, st_size=0, ...}) = 0
read(5, "fetch\noption\npush\ncheck-connecti"..., 4096) = 38
write(6, "option progress true\n", 21)  = 21
read(5, "ok\n", 4096)                   = 3
write(6, "option verbosity 1\n", 19)    = 19
read(5, "ok\n", 4096)                   = 3
stat(".git/packed-refs", {st_mode=S_IFREG|0664, st_size=675, ...}) = 0
lstat(".git/objects/10/52401742a2e9a3e8bf068b115c3818180bf19e", {st_mode=S_IFREG|0444, st_size=179, ...}) = 0
lstat(".git/objects/4e/35fa16cf8f2676600f56e9ba78cf730adc706e", {st_mode=S_IFREG|0444, st_size=178, ...}) = 0
dup(7)                                  = 8
fcntl(8, F_GETFL)                       = 0 (flags O_RDONLY)
close(8)                                = 0
write(6, "list for-push\n", 14)         = 14
read(5, fatal: could not read Username for 'https://github.com': No such device or address
"", 4096)                       = 0
--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_EXITED, si_pid=18177, si_uid=1000, si_status=128, si_utime=6, si_stime=2} ---
exit_group(128)                         = ?
+++ exited with 128 +++

So I tried to call it directly:
echo "list for-push" | strace /usr/lib/git-core/git-remote-https my

and the result:
poll([{fd=3, events=POLLIN|POLLPRI|POLLRDNORM|POLLRDBAND}], 1, 0) = 1 ([{fd=3, revents=POLLIN|POLLRDNORM}])
recvfrom(3, "\27\3\3\1\32", 5, 0, NULL, NULL) = 5
recvfrom(3, "\307|4Q\21\306\334\244o\237-\230\255\336\25\215D\257\227\274\r\330\314U\5\17\217T\274\262M\223"..., 282, 0, NULL, NULL) = 282
openat(AT_FDCWD, "/dev/tty", O_RDONLY)  = -1 ENXIO (No such device or address)
openat(AT_FDCWD, "/usr/share/locale/locale.alias", O_RDONLY|O_CLOEXEC) = 4
fstat(4, {st_mode=S_IFREG|0644, st_size=2995, ...}) = 0
read(4, "# Locale name alias data base.\n#"..., 4096) = 2995
read(4, "", 4096)                       = 0
close(4)                                = 0
openat(AT_FDCWD, "/usr/share/locale/en_US/LC_MESSAGES/libc.mo", O_RDONLY) = -1 ENOENT (No such file or directory)
openat(AT_FDCWD, "/usr/share/locale/en/LC_MESSAGES/libc.mo", O_RDONLY) = -1 ENOENT (No such file or directory)
openat(AT_FDCWD, "/usr/share/locale-langpack/en_US/LC_MESSAGES/libc.mo", O_RDONLY) = -1 ENOENT (No such file or directory)
openat(AT_FDCWD, "/usr/share/locale-langpack/en/LC_MESSAGES/libc.mo", O_RDONLY) = -1 ENOENT (No such file or directory)
write(2, "fatal: could not read Username f"..., 83fatal: could not read Username for 'https://github.com': No such device or address
) = 83
exit_group(128)                         = ?
+++ exited with 128 +++

And here it came to me:
openat(AT_FDCWD, "/dev/tty", O_RDONLY)  = -1 ENXIO (No such device or address)
...
write(2, "fatal: could not read Username f"..., 83fatal: could not read Username for 'https://github.com': No such device or address
) = 83

git-remote-https tries to read credentials via /dev/tty so I tested if it works:
$ echo ahoj > /dev/tty
bash: /dev/tty: No such device or address

But in another terminal:
# echo ahoj > /dev/tty
ahoj

I knew I switched to this user using su so I exited the shell to see how and found out I used command su danman - so I tested it again:
~# su danman -
bash: cannot set terminal process group (-1): Inappropriate ioctl for device
bash: no job control in this shell
/root$ echo ahoj > /dev/tty
bash: /dev/tty: No such device or address

I probably ignored the message and continued working but this was the reason.
When I switched using the correct su - danman everything worked fine:
~# su - danman
danman@speedy:~$ echo ahoj > /dev/tty
ahoj

After this, git started working correctly

A: I faced the exact same problem. This problem occurred when I cloned a repo using HTTPS URL and then tried to push the changes (using Shell on Linux/Mac or Git Bash on Windows):
git clone https://github.com/{username}/{repo}.git

However, when I used SSH URL to clone, this problem didn't occur:
git clone git@github.com:{username}/{repo}.git

In case you already cloned the repo using HTTPS and don't want to redo everything, you may use set-url to change the origin URL to SSH URL:
git remote set-url origin git@github.com:{username}/{repo}.git

Note: I have SSH key added to my GitHub account. Without setting up SSH key, this method will not work either.
BTW, git clone or pull should work without any of these changes. These are needed only when you git push after clone.

A: I found my answer here:
edit ~/.gitconfig and add the following:
[url "git@github.com:"]
 insteadOf = https://github.com/

Although it solves a different problem, the error code is the same...

A: Short Answer:
git init
git add README.md
git commit -m "first commit"

git remote add origin https://github.com/{USER_NAME}/{REPOSITORY_NAME}.git
git push --set-upstream origin master

Ignore first three lines if it's not a new repository.
Longer description:
Just had the same problem, as non of the above answers helped me, I have decided to post this solution that worked for me.
Few Notes:

*

*The SSH key was generated

*SSH key was added to GitHub, still had this error.

*I've made a new repository on GitHub for this project and followed the steps described

As the command line toolm I used GitShell (for Windows, I use Terminal.app on Mac).
GitShell is official GitHub tool, can be downloaded from https://windows.github.com/

A: I fixed this by installing a newer version of Git.  The version I installed is 2.10.2 from https://git-scm.com.  See the last post here: https://www.bountysource.com/issues/31602800-git-fails-to-authenticate-access-to-private-repository-over-https
With newer Git Bash, the credential manager window pops up and you can enter your username and password, and it works!

A: For those getting this error in a Jenkins pipeline, it can be fixed by using an SSH Agent plugin. Then wrap your git commands in something like this:
sshagent(['my-ssh-key']) {
    git remote set-url origin git@github.com:username/reponame.git
    sh 'git push origin branch_name'
}

A: Tried everything here, didn't work.
However, when I tried to debug via git config --system --list, I got fatal: unable to read config file '/etc/gitconfig': No such file or directory.
So I did the following,
sudo ln -s $HOME/.gitconfig /etc/gitconfig

and voila, it works.

A: Here is the simple trick that can work
android studio -> settings -> version control -> git -> use credential helper
have fun

A: just check the below
Android Studio -> Preferences -> Version Control -> Git -> Use Credential Helper

A: Replace your remote url like this:
git remote set-url origin https://<username>@github.com/<username>/<repo>.git

A: In my case I had to setup "personal access token" under GitHub:

*

*settings -> developer settings

*and enable SSO.

A: [SSH] executing...
fatal: could not read Username for 'https://github.com': No such device or address

[SSH] completed
[SSH] exit-status: 1

Build step 'Execute shell script on remote host using ssh' marked build as failure
Finished: FAILURE

Sol:-
If the repository is private and also it belongs to another person or organisation and you are a contributor of that repository then you can run git commands from Jenkins job and it doesn't prompt you for the username and password.
https://username:token@github.com/accountname/reponame.git

A: For me nothing worked from suggested above, I use the git pull command from Jenkins Shell Script and apparently it takes wrong user name. I spent ages before I found a way to fix it without switching to SSH.
In your the user's folder create .gitconfig file (if you don't have it already) and put your credentials in following format: https://user:pass@example.com, more info. After your .gitconfig file link to those credentials, in my case it was:
[credential]
   helper = store --file /Users/admin/.git-credentials

Now git will always use those credentials no matter what. I hope it will help someone, like it helped me.

A: If you want to continue use https instead ssh, and avoid type into your username and password for security reason.
You can also try Github OAuth token, then you can do
git config remote.origin.url 'https://{token}@github.com/{username}/{project}.git'
or
git remote add origin 'https://{token}@github.com/{username}/{project}.git'
This works for me!

A: Note that if you are getting this error instead:
fatal: could not read Username for 'https://github.com': No error

Then you need to update your Git to version 2.16 or later.

A: Follow the steps to setup SSH keys here: https://help.github.com/articles/generating-ssh-keys
OR
git remote add origin https://{username}:{password}@github.com/{username}/project.git

Update: If you get "fatal: remote origin already exists." then you have to use set-url:
git remote set-url origin https://{username}:{password}@github.com/{username}/project.git

A: This is an issue with your stored credentials in the system credential cache. You probably have the config variable 'credential.helper' set to either wincred or winstore and it is failing to clear it. If you start the Control Panel and launch the Credential Manager applet then look for items in the generic credentials section labelled git:https://github.com. If you delete these, then the will be recreated next time but the credential helper utility will ask you for your new credentials.

A: I am using GitHub actions where the jobs are configured to accomplish a task. This solution applies to all the CIs (Jenkins, Travis, Circle) where the git command execution environment changes.
job1:
Checkout the repository using the github actions actions/checkout@v2 using the personal access token(PAT), The job completed successfully and repository is cloned.
job2:
Fetch the tags using the command git fetch --tags. The job failed with the same error
fatal: could not read Username for 'https://github.com': No such file or directory
Reason of failure: When the job changed, the command running environment also changed, even though the repository exists but the github credentials needs to be provided to fetch the tags.
Solution: add this command before fetching the tags in the job2
git config remote.origin.url 'https://${{ your_personal_access_token }}@github.com/${{ github.repository }}'
Note: ${{ expression }} is the github actions yaml syntex to uncover the environment varibales/ to run expressions.

A: Try using a normal Windows shell such as CMD.

A: Earlier when I wasn't granted permission to access the repo, I had also added the SSH pubkey to gitlab. At the point I could access the repo and run go mod vendor, the same problem as your happens. (maybe because of cache)
go mod vendor

go: errors parsing go.mod:
/Users/macos/Documents/sample/go.mod:22: git ls-remote -q https://git.aaa.team/core/some_repo.git in /Users/macos/go/pkg/mod/cache/vcs/a94d20a18fd56245f5d0f9f1601688930cad7046e55dd453b82e959b12d78369: exit status 128:
    fatal: could not read Username for 'https://git.aaa.team': terminal prompts disabled

After a while trying, I decide to remove the SSH key and terminal prompts filling in username and password. Everything is fine then!

A: Double check the repository URL, Github will prompt you to login if the repo doesn't exist.
I'm guessing this is probably to check if it's a private repo you have access to. Possibly to make it harder to enumerate private repos. But this is all conjecture. /shrug

A: I had this problem in a ssh jail (jailkit), where /dev/tty was not present. I added this device file with jk_cp and the error went away.

A: I got the answer by clearing Invalidate caches and then clean build helped me.

*

*Select 'File > Invalidate Caches / Restart' and then click the
'Invalidate and Restart' button.

*Select Build > Clean Project and then select Build > Rebuild
Project.

A: If your repo is private then
Instead of this format
https://github.com/username/<project_name>.git

Use this format
git@github.username/<project_name>.git

You can get a correct url under SSH option
Go To Your Github Repo -> Click on Code -> Select SSH -> Copy your repo URL
Hope this helps.

A: What worked for me is to change the access of the Git repository from private to public.

A: *

*From the Android Studio terminal execute git pull
example: test@test:~/StudioProjects/dummy-project-android$ git pull

*Add the user name
example: test@test:~/StudioProjects/dummy-project-android$ "username"

*Add the user password
Password for 'https://dummy-project-android@git.com':"password"
After that, we can perform the rest of the operation

A: Here is the simple cause for people who get this error: you are trying to pull from a repo you haven't yet set up your local git to access. For me, I got this error when I changed a public repo to a private one. It's clear to me now that a public repo needs no auth, yet a private one does.
Hope this helps clarify why the error occurs and one potential trigger for that cause.


text:
Q: Excel sum with relative positions How do I sum from whats in B2 to C2 ?
B2 = A10 or just 10 (preferred)
C2 = A25 or just 25 (preferred)
Normally you would just use SUM(A10:A25), but the values in B2 and C2 are not fixed, they change based on input.
I can use MATCH to find the numbers, but how do I tell SUM to use those numbers ?
The values to sum are always in the same column.

A: You can use the INDIRECT function for this, e.g.
=SUM(INDIRECT(B2):INDIRECT(C2))

if you can live with entering the entire cell name (A10, A25).
Or to just have the numbers in B2 and C2, you could use
=SUM(INDIRECT(ADDRESS(B2;1)):INDIRECT(ADDRESS(C2;1)))

(Hope I got the columns and rows in the right order!)

A: You want to specify Cell Co-ordinates in the value of a Cell ?
Is that what you're getting at ?
Try Setting
B1 = "A10"
C1 = "A25"
D1 = =SUM(INDIRECT(B1):INDIRECT(C1))

A: Use the INDIRECT() function.  You pass it a string that is a range, which allows you to have a dynamic range based on input.


text:
Q: Creating line break for tabular table inside a theorem environment I have a table inside theorem environment and I would like to have a line break before the table is being drawn. Currently it will start drawing the table on the same line that the theorem is listed and it looks rather ugly. Does anyone know how I could achieve this?
I have an example in the following code:
\documentclass[12pt]{article}
\usepackage{amsthm}

\theoremstyle{plain}
\newtheorem{thm}{Theorem}[chapter]
\theoremstyle{definition}
\newtheorem{exmp}[thm]{Example}

\begin{document}
  \begin{exmp}
     \begin{tabular}{ccc}
        $ row1 & row1 & row1 $\\
        $ row2 & row2 & row2 $\\
        $ row3 & row3 & row3 $\\
     \end{tabular}
  \end{exmp}
\end{document}

The solution is to add \leavevmode after \begin{exmp} and also leave a blank line before the tabular environment.

A: the header of a theorem object in amsthm always ends in horizontal mode.
the 'tabular' environment begins in horizontal mode, so if a table is to start
on a new line, it's necessary to enter vertical mode.  hence a blank line
will be needed.
but that's not enough, since the theorem definitions in amsthm ignore blank
lines in order for the text of a theorem to continue on the same line as the
header.  (this is an ams style specification.)  so in order for a blank line
to take effect, it's necessary to put something else on the "first line".
the recommended way to short-circuit the "something on the line" requirement
is to insert \leavevmode.  although this seems counterintuitive, it provides
a horizontal mode element that will allow the blank line to have the desired
effect of starting a new paragraph. the relevant part of the example should
look like this:
...
  \begin{exmp}
     \leavevmode

     \begin{tabular}{ccc}
...

another method is to add the string $ $.  however, this has the disadvantage
that it inserts something that takes physical space in the output, and in the
edge case where a header with optional added text exactly reaches the
right-hand margin, it can result in the addition of a physical blank line in
the output.
irrelevant to the question, the example provided has two flaws -- article
does not define \chapter, and the $ signs in the tabular are out of
synch and result in errors when trying to process the file.


text:
Q: Spark Scala year/month function error: not found I'm getting the following error with my code, can you tell me why?

notebook:28: error: not found: value month
  retail_df = retail_df.withColumn("Month", month(retail_df("Date")))
notebook:29: error: not found: value year
  retail_df = retail_df.withColumn("Year", year(retail_df("Date")))

import org.apache.spark.sql.types._

// Make cutom schema
var schema = StructType(Array(
       StructField("Store", IntegerType, true),
       StructField("DayOfWeek", IntegerType, true),
       StructField("Date", DateType, true),
       StructField("Sales", IntegerType, true),
       StructField("Customers", IntegerType, true),
       StructField("Open", IntegerType, true),
       StructField("Promo", IntegerType, true),
       StructField("StateHoliday", StringType, true),
       StructField("SchoolHoliday", StringType, true)))

val retail_dfr = sqlContext.read.format("com.databricks.spark.csv").option("header", "true").schema(schema)
var retail_df = retail_dfr.load("/FileStore/tables/Rossman/train.csv")

val sales_custs_df = retail_df.select( "Store", "Sales", "Customers" )
val retails_open_df = retail_df.where( retail_df("Open") > 0)
val holidays_df = retail_df.filter(($"StateHoliday" === 1) && ($"SchoolHoliday" === 1))
val store_ids = retail_df.select(retail_df("Store")).distinct()
var weekday_promos = retail_df.stat.crosstab( "DayOfWeek" , "Promo" )

weekday_promos = weekday_promos.withColumnRenamed( "DayOfWeek_Promo", "DayOfWeek" )
                             .withColumnRenamed( "0", "NoPromo" )
                             .withColumnRenamed( "1","Promo" )

retail_df = retail_df.withColumn("Month", month(retail_df("Date")))
retail_df = retail_df.withColumn("Year", year(retail_df("Date")))

retail_df.show(5)

A: Both month and year needs to be imported to use. To import them use
import org.apache.spark.sql.functions.{month, year}

or
import org.apache.spark.sql.functions._

to import all avaiable sql functions. More information on what's available can be found here.


text:
Q: Python MySQL could no process parameters Hello everybody i am Trying to do a Update statment with the python mysql connector but i allways get the error
mysql.connector.errors.ProgrammingError: Could not process parameters: int(633671912411), it must be of type list, tuple or dict
i have tryed with oder binding types but this also dont work
i dont have a clue why i get this error .
Code:
 cursor.execute("""Update users set CARDSN = :id where Username = :username """, id,username)

A: Please do not use reserved names or functions like id() for variable names. Use specific names like user_id
As the error says: Arguments must be supplied list, tuple or dict, not one by one. Since you specify keyword arguments, you need a dict:
 cursor.execute("""Update users set CARDSN = :id where Username = :username """, {'id': id, 'username': username})

A: As the error message is telling you, your data "must be of type list, tuple or dict".
If you look at this example, the data variable is a tuple.
#The SQL statement, don't mind it
insert_stmt = (
  "INSERT INTO employees (emp_no, first_name, last_name, hire_date) "
  "VALUES (%s, %s, %s, %s)"
)

# Here data is a TUPLE of 4 elements
data = (2, 'Jane', 'Doe', datetime.date(2012, 3, 23))
cursor.execute(insert_stmt, data)

In your case, you probably just need to put the parenthesis around id, username.
What you are currently doing is calling the function execute with 3 parameters : Your SQL statement, the variable id AND the variable username. The framework is waiting for 2 parameters : the statement and the data. You need to put your id and username inside one single variable, that is a tuple, dict or list.
This could be :
my_dict = {'id': id, 'username': username}
cursor.execute(statement, my_dict)

Or if you don't want intermediate variables :
 cursor.execute("""Update users set CARDSN = :id where Username = :username """, {'id': id, 'username': username})


text:
Q: Docker image does not run - cannot find module I have a docker image of my TypeScript based server, that I was able to build and deploy previouly on Heroku without any problems. There was an minor change in my code that I wanted to push and since then the docker image runs with error as seen in the screenshot below

My dockerfile:

My package.json:

My index.ts:

Even after undoing those changes in the code and building the original image instead(that worked previously) the issue still persists.
How can I resolve this?
Thanks in advance.


text:
Q: Count clicks of url in Rails using custom routes. I try to save summary of clicks on image with link.
In view:
#holder
      .hidden-phone
        .banner-left
          - @left_banner.each do |f|
            = link_to image_tag(f.image.url), click_banner_url(f)
        .banner-right
          - @right_banner.each do |f|
            = link_to image_tag(f.image.url), click_banner_url(f)

In controller:
def click
        @banner = Banner.find(params[:id])
        @banner.update(clicks: @banner.clicks + 1)
        redirect_to @banner.link
end

In routes:
resources :banners do
    member do
      get 'click'
    end
end

I get error:
NoMethodError in BannersController#click
undefined method `+' for nil:NilClass
What I'm doing wrong?

A: Increment
Further to making your default value 0 in your database, you'll want to use a much more succinct method called increment, which will add 1 to your column's value regardless:

increment
Initializes attribute to zero if nil and adds the value passed as by
  (default is 1). The increment is performed directly on the underlying
  attribute, no setter is invoked. Only makes sense for number-based
  attributes. Returns self.

Judging from that, you'll be best doing this:
def click
    @banner = Banner.find(params[:id])
    @banner.increment!(:clicks) #-> saves the record
    redirect_to @banner.link
end

--
Filters
Something else to consider is how you're achieving the functionality you want
You mention you're directing people through a "custom route" when they click a banner. This adds an extra level of complexity which doesn't need to be there. You can just use a filter in your application:
#app/controllers/banners_controller.rb
Class BannersController < ApplicationController
   before_action :click

   def show
      ... logic here
   end

   private

   def click
      @banner = Banner.find params[:id]
      @banner.increment!(:click)
   end
end


text:
Q: Serving static files with nginx located in another docker container Just to start off, I have seen this. But he/she uses build, and I use image.
I have a docker-compose file that pulls an image that I have made previously onto my server.
app:
  restart: always
  image: some-app-image:latest

nginx config
location /static/ {
    root /data/app/web_interface;  <--- this exists in some-app-image container
}

Normally, I would have a volume mounted onto the app image that contains the static files.
However, this is becoming redundant since the app container has the static files in itself.
All the nginx container needs to do is "peer" into the app container and serve those static files. Like:
location /static/ {
    root http://app:8000/web_interface;
}

or
location /static/ {
    root app/web_interface;
}

Any chance there is a way to serve static files located in another container from a nginx container?

A: All the ideas I've had in the past:
Sharing a docker volume from app to nginx
You can make a volume in the app's Dockefile and copy in the staticfiles when the container runs. Then share the volume with nginx container using volumes_from. This is kind of ugly and doesn't work at all if your app depends_on nginx. I'd say this is definitely a no-go as it works terribly when scale up your app container.
The idea of also mapping staticfiles from the host into the nginx container is also not optimal. You'll have an extra weird step to deal with them.
Separate static container
Build another nginx container serving only the static files on a different virtualhost. static.foo.bar.
Use a CDN
There are tons of CDNs out there you can put your staticfiles and most frameworks have plugins for handling that. I have some projects doing this. Works great.
Use uWSGI
You can serve staticfiles with uWSGI using --static-map. See docs. This is what I ended up doing as it was a cheap and easy... and friendly when it comes to scaling. Then you probably also need to use http-socket so uWSGI talks http instead.

A: This is a very late answer, but adding it in case someone else finds this.
Perhaps you could make use of server caching so that NGINX will effectively serve the static files from it's file system after the first request to the app being proxied.
Here is a good guide to caching with NGINX
You could set the inactive flag to a long time as the assets are static.

Basic example based on the guide above:
proxy_cache_path /path/to/cache levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=30d use_temp_path=off;

server {
  ...

  location /static {
    proxy_cache my_cache;
    proxy_pass http://app:8000/static; # <--- wherever static files are on app server
  }

  ...
}

A: One of the solutions is to copy assets to a shared volume on app service's start:
docker-stack.yml:
volumes:
  docroot:
services:
  site:
    volumes:
      - docroot:/docroot
  nginx:
    volumes:
      - docroot:/docroot

app service's entrypoint.sh:
#!/usr/bin/env sh
rsync -a --delete --exclude /uploads public/ /docroot
# start the site

WORKDIR is at /app. docroot at /app/public. Here I additionally make it not copy uploads dir.
More on it here.

A: I did something similar but different:
I have docker-compose running two containers: nginx and flaskapp. I have the nginx container serve static requests and forward the rest to the flask app. Here's my nginx config (flaskapp.conf):
server {
listen 80;
server_name $SERVER_NAME;

location ^~ /static/  {
    include  /etc/nginx/mime.types;
    root /;
}

location / {
    proxy_set_header Host $host;
    proxy_pass http://frontend:8000;
}
}

and the dockerfile for my nginx container:
FROM nginx

RUN rm /etc/nginx/conf.d/default.conf
RUN mkdir static
COPY /static/ /static/
COPY flaskapp.conf /etc/nginx/conf.d/

I copy over a static folder that has the assets I need and now I can load them into the front end.


text:
Q: How to set permanent cookie? I have a manual login based on cookies.
Its working great but I have a problem because if this app is not used for a few hours it logout automatically. Can anyone help me in this?
Login Controller where cookie is stored:
if (Crypt::decrypt($parentsAuthenticationInfo->code) == $request->get('code')) {
            $cookie = Cookie::forever('access_token', json_encode($parentsAuthenticationInfo->token));

            return redirect()->action('Institution\\AuthParent\\HomeParentController@index')->withCookie($cookie);
        }

Middleware:
public function handle($request, Closure $next)
    {
        $token = json_decode($request->cookie('access_token'));
        if($request->cookie('access_token')) {

            $user_check = $request->session()->get('parent' . md5($token));
            if($user_check == null){
                $parentAuthInfo = $this->parentsAuthenticationInfoRepository->getActiveParentAuthInfoByToken($token);
                if($parentAuthInfo){
                    $request->session()->put('parent_' . md5($token), $parentAuthInfo);
                    $request->session()->save();
                }
                $user_check = $parentAuthInfo;
            }
            $request->merge(['parentAuth' => $user_check]);
            View::share(['parentAuth' => $user_check]);

            if($user_check)
                return $next($request);
        }

        return redirect('/login');
    }

A: What happens when you create a cookie using the cookie() method?
Something like this:
// The duration of this cookie is 5 years:
// 60 * 24 * 30 * 12 * 5 = 2592000 minutes

$cookie = cookie('access_token', 'value', 2592000);


text:
Q: Potential problems with paralleling a jumbo battery to iphone internal battery? Recently I happen to replace a new iPhone 4 replacement battery, with a little bit of peel down of the battery, I saw there is a bare lithium battery unit with a PCB battery protection board.

My idea is to lead two wires from the input to an external pack of 3 paralleled Panasonic NCR18650A (3100mAh 18650) batteries, totalling battery capacity to around 3.7v 10Ah.
My question is will this work? Charging and Discharging, reasonable accuracy on the percentage of battery capacity measuring? Thanks.

A: Don't bother.  Here are the issues:

*

*The circuit you are connecting this to is not going to expect the higher charging current and at best won't know how to behave.  At worst it might damage something.

*There is software inside the iPhone that tracks the rate of discharge and estimates the remaining power.  This software will do some learning, to adjust for battery differences, but it is unlikely to adjust for a 2x or 3x capacity increase.
You would be better off making what is essentially a USB battery pack.  A battery that has a USB jack on it so you can plug in various USB devices to charge them.  This would be a cleaner design (no weird wires coming out of your iPhone) and would also work with other devices without modification.


text:
Q: How to create a filppable stackview like LinkedIn I have used the following link to create a filppable stack view https://github.com/blipinsk/FlippableStackView. But I want to create a flippable stack view like linkedin.. See the attachment.. Can you guys help me?

A: The are plenty of libraries to implement animation like this. One of them https://github.com/kikoso/Swipeable-Cards which you can use easily with gradle. As alternative: https://github.com/Diolor/Swipecards


text:
Q: Website compilation process[AppCode DLLs] We are working on a website project which contains around 1130 pages. After compilation, all the .aspx.cs files are converted into AppCode DLLs that has random names.
Whenever there are any changes in single .aspx.cs file[like a hotfix], we have to recompile and deploy the entire project on the application host.
We want to update only those files that have been changed and not the entire package.
One of a solution we are aware is that, converting Website to Web application; but we cannot implement that change at this stage of the project.
Is there any other way to find an efficient solution for this?

A: Yup. Talking in Visual Studio 2010:
While publishing the website, Select the option: 'Use Fixed naming and single page assemblies', Also select 'Allow this precompiled site to be updateable'.
After website is published. Go to the published folder. Open any aspx page (not the dll or .cs).. Note the dll name in page attribute under inherits attribute. Than using ftp or any other way to upload, copy or upload tht dll under bin to your website.
Also, you can create a doc or txt file to list all Dll names with respective paths to your file to easily know which dll to upload next time if there is any change.
Hope it helps.


text:
Q: How does unity leveling work/show in mh3U? My friend and I play multiplayer for the 3DS from time to time. I finished the story and killed Dire Miralis and he just got to high rank. when we do quests we get unity and we are both level 3, it shows on my guild card but on his it still says level 0 with all of the stickers, does he need to get further in the game to see his unity level up or is it something else?

A: Unity increases when you play with people whose Guild Card you have accepted. From your Guild Card list, you can only check how much unity you have gained from playing with a certain player, not that player's total unity. If your friend's unity isn't increasing, it's because you have not sent him your Guild Card.


text:
Q: Function with input (a,b,c) that results in output (x,z,y) So I'm working on a process that will allow me to calculate subobject normals for models I am putting into a game. Basically, I know how to calculate them but I need to create a function that can use this bit of code.
local sin, asin = math.sin, math.asin
local deg, rad = math.deg, math.rad
math.sin = function (x) return sin(rad(x)) end
math.asin = function (x) return asin(deg(x)) end       --Makes math.sin read in degrees instead of radians

x = function (sin (a))
z = function (sin (b))
y = function (sin (c))

d = {a, b, c}
end

e = {x, z, y}
end

repeat
print("Enter a value for x:")
a = io.read("*number")          -- read a number
print(math.sin(a))
print("Do you want to repeat? Type 1 to repeat")
a = io.read("*number")
until a ~= 1

The way it works is that the sine of the angle that the subobject was rotated becomes the normal value on that axis. (z = b because Blender operates in X-Y horizontal and the game is in X-Z horizontal)
Basically, I am looking for a function the allows me to input "array d" and get the output displayed as "array e" instead of that single output function. a, b, and c are variables, not constants.

A: A function in python can be defined as -
def myfunc(a,b,c):
    x = sin (a)
    z = sin (b)
    y = sin (c)
    return x,y,z

or you can input an array -
def myfunc(arr):
    x = sin (arr[0])
    z = sin (arr[1])
    y = sin (arr[2])
    return {x,y,z}

Notice that you can return multiple numbers stored in different ways, depending on your needs.


text:
Q: iphone app always lockup in device after login but works fine in iphone simulator I have an iphone app that is working fine in iphone simulator.
It was successfully build and archive in Xcode 3.2
But when I install it in my ipad/iphone it always lockup after login.
I tried to add a popup message after hitting the login button before redirecting to menu page, but its still not working. No matter how I edit the code in the login button, remove the database connection and just show the popup message, it will always lockup.
I am using diawi.com to install the app.
I am wondering what went wrong, when the app is working fine in the iphone simulator. I also clean the project before the build.
Please help.
Thanks


text:
Q: Liferay homepage is not found after starting the server in Eclipse I have set up a Liferay Tomcat Server in Eclipse. After the server starts and I go to localhost:8181 (where I configured the server), the page is empty. Also, if I right click the server in Eclipse and select Open Liferay Portal Home, a 404 Page Not Found is displayed.
When I start the server outside Eclipse, with startup.bat, the page loads just fine.
Does anyone have a clue about why this might happen?

A: Where you defined Tomcat http port? And in which way Tomcat is configured in Eclipse?
These questions because Eclipse is able (but it's not mandatory) to override Tomcat default configurations.
Just a note: do you try to use Liferay plugin for Eclipse? It can help you to proper configure a Liferay server in Eclipse (and help you for development also).

A: This answer assumes you're using Liferay IDE in Eclipse. It might be accurate even if you're not.
Try making your edits in the Eclipse workspace's server.xml file. The workspace should have a Servers folder, with your Tomcat Liferay server underneath it. The path in my workspace is as follows:
eclipse-luna-workspace/Servers/Liferay v6.2 CE Server (Tomcat 7) at localhost-config

Underneath the directory for the server are copies of the Tomcat configuration files, including server.xml. Make your edits to this server.xml file, restart your server in Eclipse, and Eclipse should copy it to the Tomcat instance at startup.


text:
Q: Add fork within an existing repo I have a repository on GitHub.com which contains some very useful files. These files act as a template and helper files for Latex code.
I rarely change these files because they are a template, but those who use them might have to make changes to them.
What I need is a way for those who use the files to create a fork into their own repository, make changes to their fork and push them, so that only their repository can see them.
The key: a fork INSIDE another repo.
Now, forks works not as being put into an existing repo but being beside it.
I really need it into the existing one.
Any clue of what I need to do?
The very, plain, solution is downloading the files as a zip, and unzip them into a plain folder in the repository. But this way they can't be updated.

A: The fork equivalent within a repo, is called branch.
just submit your changes to a new branch, and no need to push these changes anywhere.
To repeat: there is no need to push your changes at all.
If you are concerned about having your submodule in a dirty state and you don't want to accidentally commit an updated submodule to your main repository, you can ignore changes in submodules:
[submodule "coolstuff"]
    path = coolstuff
    url = ...
    ignore = dirty

If you are concerned about accidentally pushing your changes, you can set the push url of your remote to something invalid:
$ git remote set-url origin --push /dev/null

which gives you:
$ git push
fatal: '/dev/null' does not appear to be a git repository
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
$ git pull
Already up-to-date.

Aternatively, simply clone from a read-only URL.


text:
Q: Example of ggplot2 stat_summary_hex using alpha aesthetic mapping? I'm plotting customer churn using the ggplot2 stat_summary_hex function.
stat_summary_hex(aes(x = Lon, y = Lat, z = Churn),
   bins=100, colour = NA, geom = "hex", fun = function(x) sum(x))

ScaleFill <- scale_fill_gradient2(low = "blue", high = "orange", na.value = NA)

The stat_summary_hex is plotted over a basemap from get_map so I would like to set the alpha scale such that summary values close to 0 would have an alpha of 0.  However, it looks like stat_summary_hex does not acknowledge an alpha aesthetic.
Does someone have an example of stat_summary_hex with alpha mapping?

A: I found a work around by setting drop = TRUE and then changing the stat_summary_hex function to return NA when the result was less than my threshold:
stat_summary_hex(aes(x = Lon, y = Lat, z = Churn),
  bins=100, colour = NA, geom = "hex", drop = TRUE,
  fun = function(x) if(abs(sum(x)) > 5) {sum(x)} else {NA})


text:
Q: Spring Security - How to get the roles assigned to user I am implementing JWT Role Based Authorization. I am testing my apis through postman.
The users first makes a POST request and registers itself where we pass in the firstname, empid and password. The user on successfull registarion returns a response including a column roles which is null in the starting. Then I manually assign the user role. I have two roles in myROLE table i.e ADMIN or USER which I assign them manually.
After this, the user needs to authenticate or sign in in order for the token to be gnenrated.
Upto this point everything is correct. The token is being generated but it returns me the roles values null even though I have assigned the user ADMIN role manually. How do I get the roles assigned to user? please help. I am pasting some code below:
Below is my api for user authentication : AuthenticationController
    final Authentication authentication = authenticationManager.authenticate(
            new UsernamePasswordAuthenticationToken(
                authenticationRequest.getEmpID(),
                authenticationRequest.getPswd()
            )
    );
    SecurityContextHolder.getContext().setAuthentication(authentication);

    final String token = jwtTokenUtil.generateToken(userDetails
      ,authentication);

    List<String> roles = authentication.getAuthorities().stream()
    .map(item -> item.getAuthority())
    .collect(Collectors.toList());

As you can see here I have roles defined. How do I get the roles when authenticating the user?
I added this as mentioned above:
 List<String> roles = authentication.getAuthorities().stream()
    .map(item -> item.getAuthority())
    .collect(Collectors.toList());

It does not seem to do anything. What else I am missing?
Users.java:
public class Users {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "USER_ID")
private Long id;

//other columns
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "CONFIG_USERROLE", joinColumns = @JoinColumn(name =
"USER_ID"), inverseJoinColumns = @JoinColumn(name = "ROLE_ID"))
private Set<Role> roles;

public Users(){

}

Role.java:
 public class Role {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "ROLE_ID")
private Long id;

@Column(name = "ROLE")
private String role;

A: You need to set the roles in your UserDetailsWithToken to get them on the response object. They are only set on the JWT object.
Just add the following line to your AuthenticationController, after obtaining the roles list
UserDetailsWithToken.setRoles(roles);


text:
Q: How to Make my Footer Push with Content? Ok, so I have this footer on my page I'm designing, but I've encountered a problem; the footer sticks to the bottom of the page, but content can go past it... this is what I mean - http://i46.tinypic.com/2zted15.png.
Here is my the CSS/HTML code for my footer: http://pastebin.com/ZKCuBjhn
Thanks a lot in advanced.
Edit:
Here is the code for the whole page -
HTML code: pastebin.com/RAj11cPP ---
CSS code: pastebin.com/0kMgb1R2
Note: The ridiculous amount of  tags in the code was to demonstrate my problem.

A: Try adding clear: both; to your footer style. It would be nice to see the code of the rest of the page howerver.
Real Answer:
After looking at your code, it seems like this is more what you want: http://pastebin.com/Letx9hPA
I changed you footer's position to fixed so that it stayed on the bottom of the page. If that isn't what you want then remove position all together so that it is free to be pushed down.
Also I wrapped your content in a content div so that I could add the spacer needed at the bottom to make it all visible. Spacer added by setting padding-bottom: 100px which is the height of your footer.

A: You're using position: absolute for the div, so you're removing it from th normal flow of the page, afterwards, the upper content will pass through.
In the case your previous html is a div or something like that enclosing the whole superior piece, then use the div, DON'T "position absolute" it, use width: 100% and margin: 0 auto; The problem is not your footer, is the code that comes before the footer.
In case it's a div, you HAVE TO give some height but using min-height, so when the content inside it overflows, the div behaves nicely and push your footer downward. If you use height, then the div will adopt that height and your overflowing insides will leak off.
Here's a simple code:
body {
        background-color: #d6d6d6;
    }

    .header {
        background-color: #006F8D;
        color: #fff;
        margin: 0 auto;
        width: 600px;
        height: 100px;
    }

    .center {
        background-color: #fff;
        color: #454545;
        margin: 0 auto;
        width: 600px;
        min-height: 100px;
    }

    .footer {
        background-color: #fff;
        color: #454545;
        margin: 0 auto;
        width: 600px;
        height: 50px;
        border-top: 1px solid #ccc;
    }

That's for the CSS, now for the HTML:

menu 1 - menu2 - menu3

Middle

    Middle

    Middle

    Middle

    Middle

    v
    v
    Middle

Middle

Middle

v
    v
v
    Middle

v
    v
Middle

    v
    v
    v
    v
    v
    v
    vMiddle
Middle
Middle
Middle

Middle
Middle
Middle
Middle
Middle
Middle
Middle

Footer

If you need to absolutely position your footer then the answer is another one. Clarify me that and I'll answer the other question.
EDIT: Your code with mine (didn't used your css, and GOD, DON'T use that deprecated TAGS!!!! font, center, etc.)

<title>Website Homepage</title>

    Home
    Sign Up
    Login
    Link
    Link
    Link

See my problem?

                Website. All Rights Reserved.

<form action="http://www.google.com/search" method="get" onSubmit="Gsitesearch(this)">
<input name="q" type="hidden" />
<input type="text" placeholder="Search our site..." name="qfont" /> <input type="submit" value="Search" />
</form>


text:
Q: Which is/are the most secure password hash algorithm(s) in PHP? Which are the most secure password hash algorithm(s) in PHP?
Speed is irrelevant because I'm iterating the hash over a fixed time (rather than a fixed number of iterations). What I'm interested in is the mathematical strength.
My intuition tells me it's whirlpool, being the largest and slowest of the bunch. That or SHA-512. Which is recommended by experts?
Are there any other algorithms which provide more than 512 bit hashes?

A: Use the function password_hash(). If you let it (by specifying PASSWORD_DEFAULT), it will choose the recommended algorithm, which currently is BCrypt. If the algorithm changes, you don't have to change the code. If you like, you can also explicitly choose this algorithm using the constant PASSWORD_BCRYPT, but that opposes the intention of automatically updating to better algorithms when they become available in future versions.
You can use password_verify() to verify the password.
PHP will add the used algorithm to the hash, as well as a salt, so it will know everything it needs to know for the verification. That way, when new algorithms become available in newer versions of PHP, they will be used automatically, and those passwords will have a stronger hash.
You can use password_needs_rehash() to check if a password needs to be rehashed, should the default ever change.
If a password validates, you can rehash it and store it. That way you will update old passwords with weaker hashes automatically when a user logs in.

A: scrypt is debateably the most secure hashing algorithm because it is RAM-limited and therefore difficult to parallelize. However, it is not natively supported by many, if any, current systems.
bcrypt is next. It has no current known cryptographic weaknesses, is widely supported, and has a broadly adjustable work factor. It is also the current default algorithm for password_hash().
Everything else is sub-par.
Unless you have a degree in cryptography do not roll your own hashing or cryptography scheme.

2023 Update
Worth noting that since PHP7.2 [Released Nov 2017] Argon2 hashing has been available to password_hash(), provided PHP was built with the relevant options. Specifically Argon2id allows the specification of both time and memory cost parameters, making potentially better than both bcrypt and scrypt.


text:
Q: ProgrammingError: invalid reference to FROM-clause entry for table "iris_category" I have created a module and am adding a category, it was working correct in previous version of Odoo and on 10-april-2015 i updated new version i am getting the error
ERROR:
 HINT:  Perhaps you meant to reference the table alias "iris_business_category__category_id".

, in query  SELECT
"iris_business_category"."id",iris_category__content_id."title" FROM "iris_business_category","iris_category" as "iris_business_category__category_id","iris_content" as "iris_category__content_id"
                    WHERE "iris_business_category".id IN %s AND ("iris_business_category"."category_id" = "iris_business_category__category_id"."id") AND ("iris_category"."content_id" = "iris_category__content_id"."id")  ORDER BY "iris_business_category"."id"

How to solve this issue in new version??

A: yes it is a problem and it has been mentioned on odoo.


text:
Q: Change chart data range using a drop down list (vba) I'm trying to Change chart data range using a drop down list (vba). Here is my code:
Sub SelectTable()

With ActiveSheet.Shapes(Application.Caller).ControlFormat
    If ActiveSheet.Shapes(Application.Caller).Name = "Drop Down 2" Then
    Worksheets("Comparison").ChartObjects("Chart 8").Chart.SetSourceData Source:= _
    Range(.List(.Value) & "[#All]")
    Worksheets("Comparison").ChartObjects("Chart 8").Chart.PlotBy = xlRows

End If

End With

End Sub

Getting Run-time error: '1004'

while selecting the drop-down list.
Also, this VBA will not be based on any pivot table. It's going to make changes on a Dashboard sheet.
Yes, the chart has been created using Pivot but the drop down list is a combination of UserForm and Data Validation

A: I assume that your listbox return a string of your named range
Sub SelectTable()

With ActiveSheet.Shapes(Application.Caller).ControlFormat
    If ActiveSheet.Shapes(Application.Caller).Name = "Drop Down 2" Then
    Worksheets("Comparison").ChartObjects("Chart 8").Chart.SetSourceData Source:= _
    worksheet("sheetName??").Range(.Value & "[#All]")

    Worksheets("Comparison").ChartObjects("Chart 8").Chart.PlotBy = xlRows

End If

End With

End Sub