text:
Q: Wrapping plastic in aluminium foil to protect it from heat Does it make any sense to wrap the plastic handle of a pan in aluminium foil to protect it from overheating when placing it to the hot oven?

A: The foil has two effects: it insulates and reflects.
Thermal insulation does not offer immunity from heat. It reduces the flow of heat. In other words, it delays. In this case, the actual insulation isn't caused by the aluminum foil (which conducts quite well) but by the air layers that it traps.
Reflecting radiation would help if it wasn't happening in an oven. Radiation which is reflected away doesn't turn into heat, but inside the closed environment of an oven the radiation just gets converted to heat somewhere else. It will take a while to get to the handle, so it's another delay.
So, in summary, the foil just buys you a bit of time. From personal experience, I'd estimate it at minutes, certainly less than an hour.

A: MSalters answer is all correct, but even in an oven the reflective nature of foil may help (as it would under a grill, but the effect is smaller in an oven).  To explain, let's assume the plastic is perfectly black: Wherever the heat is coming from must be hotter than the air in the oven and the other items in the oven.  This is particularly obvious if the oven heats with a visibly glowing element, but will be true even if the element is behind a metal panel.  A black plastic handle could easily reach a higher temperature than the air temperature (the nominal temperature) in this case.  The foil will reflect this radiated heat quite efficiently, significantly slowing the rate of temperature rise.

A: Everything will want to go to equiliberium for temperature in the oven.
Aluminium foil is not a good insulator.
Suggest three courses of action:

*

*Remove plastic handle

*find a different pan with a metal handle and use an insulator (i.e. oven mitten) when removing pan from oven

*find a material with a good insulating value to protect the plastic handle
COA 3 will be the most difficult due to you solution will most likely be large/clumsy and will cost $$$
Use the KISS (Keep It Simple Stupid) principle to solve your problem.

A: No. If your saucepan can take the heat of an oven, the handle needs no protection. If it can't take the heat of an oven, there's really nothing you can do to provide any practical protection to the handle.
Not only will there be heat transfer from the surrounding air (and radiant heat from the heating element/burner and all the hot interior surfaces of the oven), but heat will also be conducting into the handle from the body of the pan.
In all likelihood, to achieve what you want by putting the pan in the oven will require it to be there long enough that the handle is going to approach oven temperature no matter what you do. So, you need a pan with a handle that can withstand such temperatures.
There are some materials we commonly describe as plastics, like bakelite, which can take a lot of heat, but still much less than what you'd commonly use in an oven.
Bottom line: if it doesn't say oven safe on the label, it doesn't belong there, no matter what you try to do with it or to it.


text:
Q: Rotation about an axis by matrix multiplication Suppose I have three axis of rotation vectors $\vec{v_1},\vec{v_2},\vec{v_3}$ and angle of rotation as vectors $\theta_1,\theta_2,\theta_3$.

*

*Take a vector $P$ then apply rotation around  $\vec{v_1}$  with rotation angle  $|\theta_1|$

*From new orientation of $P$ apply rotation around  $\vec{v_2}$  with rotation angle  $|\theta_2|$

*From new orientation of $P$ apply rotation around  $\vec{v_3}$  with rotation angle  $|\theta_3|$

*Now you get final orientation of $P$

Question

*

*Shall we get the same orientation of P if rotate  around  resultant of $\vec{v_1},\vec{v_2},\vec{v_3}$ let us call V with an angle which is equal to the magnitude of the resultant of $\theta_1,\theta_2,\theta_3$.

A: No (it is called "non-commutativity").
First hint: rotate 90° around z, then 90° around x, then −90° around z.
When the first exercise was complete, try to rotate −90° around z, then 90° around x, then 90° around z ☺

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to define a custom base path when NEXTAUTH_URL doesn't work? Context
I'm using NextJS v12.0.7, React v17.0.2, NextAuth v4.1.0 and Typescript v4.3.5.
I wanted to create a simple auth system, based on NextAuth documentation and being redirected to homepage after logged in, so I've created a file in pages/api/auth folder named [...nextauth].ts that is containing these parts of code:
export default NextAuth({
  providers: [
    CredentialsProvider({
      id: "credentials",
      name: "Login",
      credentials: {
        username: { type: "email" },
        password: { type: "password" },
      },
      async authorize(credentials) {
          // [...]
      },
    }),
  ],

  // [...]

  callbacks: {
    // [...]
    redirect({ url, baseUrl }) {
      console.log("redirect - url ", url, "baseUrl ", baseUrl); // This is what I was checking
      if(url.startsWith(baseUrl)) {
        return url
      } else if(url.startsWith("/")) {
        return new URL(url, baseUrl).toString();
      }
      return baseUrl;
    }
  },
})

For my NextJS project, I'm using a basepath /espace-personnel defined in next.config.js file, so I've defined NEXTAUTH_URL in .env.local file following the official NextAuth documentation :
NEXTAUTH_URL=http://localhost/espace-personnel/api/auth

My problem
Where I'm checking url and baseUrl variables in redirect callback, I can see that my NEXTAUTH_URL variable isn't defined well, or I missunderstand something.
Here is the result of console.log("redirect - url ", url, "baseUrl ", baseUrl); :
redirect - url  http://localhost:3000 baseUrl  http://localhost

I've done researches and I can't find any case like me on Google or Stackoverflow, I'm new in NextAuth so I'm probably misunderstanding something. Does someone have an idea of what I'm doing wrong ?
Edit (15/01/2022)
After thinking again about it, I've decided to check my env variable directly using process.env.NEXTAUTH_URL, so I've added that line after the previous console.log() :
  console.log("NEXTAUTH_URL", process.env.NEXTAUTH_URL)

And here is the result:
NEXTAUTH_URL http://localhost/espace-personnel/api/auth

So, in fact, this is not a problem of defining NEXTAUTH_URL, I think I misunderstand something about how NextAuth is working, I will continue to try to find a solution to my problem and share there if I'm finding something.
Edit (16/01/2022)
After some research, I've find that we can pass callbackUrl using signIn method, so I've defined my pages like that in [...nextauth].ts :
  pages: {
    signIn: process.env.NEXT_PUBLIC_BASE_URL + '/connexion',
    signOut:  process.env.NEXT_PUBLIC_BASE_URL + '/deconnexion',
    error:  process.env.NEXT_PUBLIC_BASE_URL + '/connexion/erreur', // Error code passed in query string as ?error=
  },

And here is the code of my login form :
import React, { useState } from "react";
import Alert from "../../ui/Alert/Alert";
import Button from "../../ui/Button/Button";
import Card from "../../ui/Card/Card";
import Divider from "../../ui/Divider/Divider";
import { getCsrfToken, signIn } from "next-auth/react";
import Input from "../../ui/Input/Input";
import styles from "./LoginForm.module.scss";
import Router from 'next/router';

type TAlertTitle = string;
type TAlertMessage = string;
type TAlertType = "info" | "warning" | "success" | "error";

export default function LoginForm({ csrfToken }: { csrfToken: string }) {
  const [alertTitle, setAlertTitle] = useState<TAlertTitle>("Information");
  const [alertMessage, setAlertMessage] = useState<TAlertMessage>("Juste un exemple");
  const [alertType, setAlertType] = useState<TAlertType>("info");

  async function onSubmit(event: React.SyntheticEvent<HTMLFormElement>) {
    const target = event.target as typeof event.target & {
      username: { value: string },
      password: { value: string },
    };

    // Login attempt
    const result = signIn('credentials', {
      callbackUrl: process.env.NEXT_PUBLIC_BASE_URL,
      username: target.username.value,
      password: target.password.value
    });

    console.log(result);

    event.preventDefault();
  }

  return (
    <Card className={styles.card}>
      <p className={'textSize40 fontWeightExtraBold textAlignCenter'}>
        Connexion à votre espace personnel
      </p>
      <Divider className={styles.divider} />
      <form onSubmit={onSubmit}>
        <Alert title={alertTitle} message={alertMessage} type={alertType}></Alert>
        <input name="csrfToken" type="hidden" defaultValue={csrfToken} />
        <Input id="username" name="username" className="width100" type="email" autoComplete="email" placeholder="Adresse mail" leftIconLib="line-awesome" leftIcon="envelope" required />
        <Input id="password" name="password" className="width100" type="password" autoComplete="current-password" placeholder="Mot de passe" leftIconLib="line-awesome" leftIcon="key" required />
        <Button className="width100" theme="accent" type="submit">Se connecter</Button>
        <Button className="width100" type="submit">Identifiants oubliés</Button>
      </form>
    </Card>
  );

}

New problem is that when I'm trying to login, I'm redirected to http://localhost/api/auth/error and I'm obtaining that error :
404 | This page could not be found.

Is there something I'm doing wrong there ?

A: After hours of research, I finally came across a very recent Github discussion concerning the same problem.
Solution to use a custom base path with NextAuth v4
This is the short version, longer is at the bottom.

*

*Define NEXTAUTH_URL in .env file, replacing /espace-personnel by your own basePath :

NEXTAUTH_URL=http://localhost/espace-personnel/api/auth

*Define basePath props of <SessionProvider> in _app.tsx, replacing /espace-personnel by your own basePath :

function App({ Component, pageProps: { session, ...pageProps } }: AppProps) {
  return (
    <SessionProvider session={session} basePath='/espace-personnel/api/auth'>
      <Component {...pageProps} />
    </SessionProvider>
  );
}
export default App

Solution to use a custom base path with NextAuth v4 (previous solution)
In this example, basePath used is /espace-personnel and domain is localhost.
You need to set the NEXTAUTH_URL environment variable within your .env file, including your basePath followed by /api/auth like this example:
NEXTAUTH_URL=http://localhost/espace-personnel/api/auth

Then edit your _app.tsx and define your base path using the props basePath on your <SessionProvider>, here is my final code to use my custom path /espace-personnel :
function App({ Component, pageProps: { session, ...pageProps} }: AppProps) {
  return (
    <SessionProvider session={session} basePath="/espace-personnel/api/auth">
      <Component {...pageProps} />
    </SessionProvider>
  )
}
export default App

A: If you are using next.js auth with multiple zones or custom base path there is a couple changes to make NextAuth.js aware of that
1- update rest api path base, .env file
NEXTAUTH_URL=https://example.com

become
NEXTAUTH_URL=https://example.com/{zone name or basePath}/api/auth

2- update client api path base, _app.tsx
<SessionProvider session={pageProps.session}>

become
<SessionProvider session={pageProps.session} basePath="/{zone name or basePath}/api/auth">


text:
Q: How to load the different format of json to Highchart here is my json data can anyone guide me how to load this data to HighCharts. this is sample data.
{
"Type": [
    "Tower",
    "Apartment",
    "Atrium",
    "Terrace"
       ],
"Freq": [
    21,
    21,
    28,
    34,
    22,
    36,
    10,
    11,
    36,
    61,
    23,
    17,
    43,
    35,
    40,
    26,
    18,
    54,
    13,
    9,
    10,
    8,
    8,
    12,
    6,
    7,
    9,
    18,
    6,
    7,
    15,
    13,
    13,
    7,
    5,
    11,
    14,
    19,
    37,
    17,
    23,
    40,
    3,
    5,
    23,
    78,
    46,
    43,
    48,
    45,
    86,
    15,
    25,
    62,
    20,
    23,
    20,
    10,
    22,
    24,
    7,
    10,
    21,
    57,
    23,
    13,
    31,
    21,
    13,
    5,
    6,
    13
]

}
Actual the json format is this only i am getting. so please anyone guide me. This is the data which is passing to Highcharts to draw chart. when i pass this data it not at all showing the chart.

A: Make the proper series like this
 series: [{
            name: 'Tokyo',
            data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
        }, {
            name: 'New York',
            data: [-0.2, 0.8, 5.7, 11.3, 17.0, 22.0, 24.8, 24.1, 20.1, 14.1, 8.6, 2.5]
        }, {
            name: 'Berlin',
            data: [-0.9, 0.6, 3.5, 8.4, 13.5, 17.0, 18.6, 17.9, 14.3, 9.0, 3.9, 1.0]
        }, {
            name: 'London',
            data: [3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8]
        }]

A: In order to simply display that data on Y-Axis, use the below code (considering your object is named "data":
$('#container').highcharts({
    title: {
        text: "Showing Frequencies",
    },
    series: [{
        name: "Frequencies",
        data: data.Freq
    }]

});

See the DEMO here


text:
Q: deploy 2 flask projects using apache on Ubuntu (not duplicated) please don't close the question as duplicated as it is a different issue.
I have an ubuntu server on Azure and I deployed a flask project on it and it is working fine, I wanted to deploy another project but it doesn't work, here is my sites.conf, please review it and tell me where is the issue.

<VirtualHost *:80>
       ServerName server
       ServerAdmin admin@email.com
       ServerAlias project1.net
       DocumentRoot /var/www/html/project1/
       WSGIScriptAlias / /var/www/html/project1/project1.wsgi
       WSGIPassAuthorization on
       <Directory /var/www/html/project1/>
               Order allow,deny
               Allow from all
       </Directory>
       Alias /static /var/www/html/project1/static
       <Directory /var/www/html/project1/static/>
               Order allow,deny
               Allow from all
       </Directory>

       ErrorLog ${APACHE_LOG_DIR}/error.log
       LogLevel warn
       CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

<VirtualHost *:80>
       ServerName server
       ServerAdmin admin@email.com
       ServerAlias project2.net
       DocumentRoot /var/www/html/project2/
       WSGIScriptAlias / /var/www/html/project2/project2.wsgi
       WSGIPassAuthorization on
       <Directory /var/www/html/project2/>
               Order allow,deny
               Allow from all
       </Directory>
       Alias /static /var/www/html/project2/static
       <Directory /var/www/html/project2/static/>
               Order allow,deny
               Allow from all
       </Directory>
       ErrorLog ${APACHE_LOG_DIR}/error.log
       LogLevel warn
       CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>


text:
Q: Debugging Laravel Octane (Swoole serving) by Yasd - I try to debugging swoole Laravel app with Yasd. I'm getting errors when starting this repo
https://github.com/DenisPetrov100/Laravel-CRUD-SPA-SAMPLE-3
laravel.test_1  | 2022-06-24 10:19:44,403 INFO Set uid to user 0 succeeded
laravel.test_1  | 2022-06-24 10:19:44,405 INFO supervisord started with pid 16
laravel.test_1  | 2022-06-24 10:19:45,407 INFO spawned: 'php' with pid 17
laravel.test_1  | Invalid address/ Address not supported: Inappropriate ioctl for device
laravel.test_1  | 2022-06-24 10:19:45,460 INFO exited: php (exit status 1; not expected)

If I use real ip of my host system instead of host.docker.internal setting yasd.remote_host="192.168.65.2" in docker\8.1\yasd.ini and switch on debugging in VScode, then I get stacked container with this lines
laravel.test_1  | 2022-06-24 10:51:13,078 INFO Set uid to user 0 succeeded
laravel.test_1  | 2022-06-24 10:51:13,081 INFO supervisord started with pid 16
laravel.test_1  | 2022-06-24 10:51:14,084 INFO spawned: 'php' with pid 17
laravel.test_1  | 2022-06-24 10:51:15,086 INFO success: php entered RUNNING state, process has stayed up for > than 1 seconds (startsecs)

And in case switching off debugging
laravel.test_1  | [yasd] recv command error, connection closed
laravel.test_1  | 2022-06-24 10:55:04,720 INFO exited: php (exit status 0; expected)

My dev environment:
Windows 10, WSL 2, Docker Desktop for Windows shared with WSL.
docker-compose.yml and DockerFile is from sail artisan sail:publish
VS Code extension - PHP Debug
launch.json
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Listen for YASD",
            "type": "php",
            "request": "launch",
            "port": 9000,
            "pathMappings": {
                "/var/www/html": "${workspaceRoot}"
            },
        }
    ]
}


text:
Q: android layout absolute position I am new to android development and I have a question.
I am working on a game for android and I have to place some ImageViews on specific positions on my layout. For example I have an image of a kitchen as my background and I want to position an image of an apple on the top of the counter (it has to be always in the counter, in all screen sizes). What's the best way of doing this?
I was using a relativeLayout, and changing the margins of my ImageView, but that doesn't seem to work really well.
Here is my XML:

<LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/wrapper">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/topRelativeLayout"
        android:layout_weight=".1">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="(Character Request)"
            android:id="@+id/requestTxt"
            android:layout_centerVertical="true"
            android:layout_centerHorizontal="true"
            android:textIsSelectable="false"
            android:textSize="48px"
            android:textColor="#FFFFFF"
            android:shadowColor="#000000"
            android:shadowDx="1"
            android:shadowDy="1"
            android:shadowRadius="2"/>
    </RelativeLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="342dp"
        android:id="@+id/characterLayout"
        android:layout_weight="1">

        <ImageView
            android:layout_width="200dp"
            android:layout_height="300dp"
            android:id="@+id/imageBody"
            android:src="@drawable/body_canard"
            android:layout_alignParentBottom="true"
            android:layout_alignLeft="@+id/imageHead"
            android:layout_alignStart="@+id/imageHead" />

        <ImageView
            android:layout_width="200dp"
            android:layout_height="300dp"
            android:id="@+id/imageHead"
            android:src="@drawable/head_canard"
            android:layout_alignParentBottom="true"
            android:layout_alignLeft="@+id/imageEyes"
            android:layout_alignStart="@+id/imageEyes" />

        <ImageView
            android:layout_width="200dp"
            android:layout_height="300dp"
            android:id="@+id/imageEyes"
            android:src="@drawable/eyes_black"
            android:layout_alignParentBottom="true"
            android:layout_alignLeft="@+id/imageHat"
            android:layout_alignStart="@+id/imageHat" />

        <RelativeLayout
            android:layout_width="80dp"
            android:layout_height="40dp"
            android:layout_marginBottom="123dp"
            android:layout_alignParentBottom="true"
            android:layout_alignRight="@+id/imageBody"
            android:layout_alignEnd="@+id/imageBody"
            android:layout_marginRight="57dp"
            android:layout_marginEnd="57dp"
            android:background="#000000"
            android:id="@+id/mouthLayout"
            android:visibility="visible"/>

        <ImageView
            android:layout_width="200dp"
            android:layout_height="300dp"
            android:id="@+id/imageHat"
            android:src="@drawable/hats_bizarre"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true" />

        <ImageView
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:id="@+id/imageApple"
            android:src="@drawable/kitchen_apple"
            android:tag="pomme"
            android:layout_marginLeft="582dp"
            android:layout_marginTop="10dp"
            />

        <ImageView
            android:layout_width="70dp"
            android:layout_height="50dp"
            android:id="@+id/imageCheese"
            android:src="@drawable/kitchen_cheese"
            android:tag="fromage"
            android:layout_marginLeft="670dp"
            android:layout_marginTop="10dp" />

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:id="@+id/imageJuice"
            android:src="@drawable/kitchen_juice"
            android:tag="jus"
            android:layout_marginLeft="760dp"
            android:layout_marginTop="9dp"  />

        <ImageView
            android:layout_width="50dp"
            android:layout_height="70dp"
            android:id="@+id/imageGrapes"
            android:src="@drawable/kitchen_grapes"
            android:tag="raisin"
            android:layout_marginLeft="582dp"
            android:layout_marginTop="70dp" />

        <ImageView
            android:layout_width="50dp"
            android:layout_height="70dp"
            android:id="@+id/imageBananas"
            android:src="@drawable/kitchen_bananas"
            android:tag="bananes"
            android:layout_marginLeft="760dp"
            android:layout_marginTop="70dp" />

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:id="@+id/imageMilk"
            android:src="@drawable/kitchen_milk"
            android:tag="lait"
            android:layout_marginLeft="490dp"
            android:layout_marginTop="260dp"  />

        <ImageView
            android:layout_width="80dp"
            android:layout_height="50dp"
            android:id="@+id/imageCake"
            android:src="@drawable/kitchen_cake"
            android:tag="gâteau"
            android:layout_marginLeft="360dp"
            android:layout_marginTop="0dp"  />

        <ImageView
            android:layout_width="70dp"
            android:layout_height="50dp"
            android:id="@+id/imageLettuce"
            android:src="@drawable/kitchen_lettuce"
            android:tag="laitue"
            android:layout_marginLeft="500dp"
            android:layout_marginTop="150dp"  />

        <ImageView
            android:layout_width="70dp"
            android:layout_height="50dp"
            android:id="@+id/imageCorn"
            android:src="@drawable/kitchen_corn"
            android:tag="blé"
            android:layout_marginLeft="360dp"
            android:layout_marginTop="150dp"  />

        <ImageView
            android:layout_width="70dp"
            android:layout_height="50dp"
            android:id="@+id/imageOrange"
            android:src="@drawable/kitchen_orange"
            android:tag="orange"
            android:layout_marginLeft="190dp"
            android:layout_marginTop="100dp"  />

    </RelativeLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:id="@+id/bottomLayout"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_weight=".1">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:id="@+id/audio"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:src="@drawable/icon_musique" />

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/recommence"
            android:layout_alignParentBottom="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:src="@drawable/icon_arrow"
            android:focusableInTouchMode="false" />

    </RelativeLayout>
</LinearLayout>


text:
Q: Values error to unpack in python file (expected 3) I am new to Python.
I want to write a example using I/O file but I have a problem.
Input.txt is:
10 , 4 , #

This is my code:
f = open("Input.txt", "r")
text = f.read()
m, n, c = text.split("\n")
m = int(m)
n = int(n)
f. close()

out_text = (c * m + "\n") * n
f = open("Output.txt", "w")
f.write(out_text)
f.close()

When I run this code, I have this error:

ValueError: too many values to unpack (expected 3)

Can anyone help me with that?  What is this error ???!!!!!

A: text = "10, 12, #"
# Here split the string using comma and not newline char.
m, n, c = text.split(",")
print(m, n, c)
m = int(m)
n = int(n)
out_text = (c * m + "\n") * n
print(out_text)

You should split the string using comma and not newline char \n. In case your text file has multiple lines then better use lines = file.readlines() and then
 ....
for line in lines:
    m, n, c = line.split(",")
 ....

So finally your code will look something like this
with open("Input.txt", "r") as f:
    lines = f.readlines()

# Keep in mind that using "w" will
# overwrite contents of file and not
# append to it
out_file = open("Output.txt", "w")

for line in lines:
    m, n, c = line.split(",")
    m = int(m)
    n = int(n)
    out_text = (c * m + "\n") * n
    out_file.write(out_text)

out_file.close()

About the error
ValueError: too many values to unpack (expected 3)
Given that you were trying to split the text using separator \n suggests that you have multiple lines. Lets understand with an example and say your file had 5 lines like this:
1, 2, #
3, 2, #
1, 3, #
8, 2, #
3, 5, #

Now when you read this using f.read() the resultant string will effectively be like this
"1, 2, #\n3, 2, #\n1, 3, #\n8, 2, #\n3, 5, #"

And when you split it using \n you got a list as shown below
['1, 2, #', '3, 2, #', '1, 3, #', '8, 2, #', '3, 5, #' ]

AND NOT
['1', ' 2', ' #'] and so on

Therefore when you instruct python to unpack list with 5 elements into 3 variables m, n, c it raises error that 5 values cannot be uniquely assigned (or unpack) to 3 variables.
Hope this answers your query.

A: Your error throw by below code
m, n, c = text.split("\n")

Which caused by split return less then 3 items, while you expecting 3 (i.e. m, n, c)
# This should throw the same error
m, n, c = ["one"]
m, n, c = ["one", "two"]

# This should work
m, n, c = ["one", "two", "three"]

To fix the issue, review your split call, Paandittya's answer should have everything you need


text:
Q: How to configure NICedit to display only "New Window" option? I am using NicEdit in my project. I need to disable the option "Current Window" for links in one particular module. How can this be achieved?
Thank You,
Santhosh

A: Open the nicEdit.js file and Check the line which starts with
var nicLinkButton=nicEditorAdvancedButton.extend({addPane:function()
in that line find this word "Current Window" and remove the entire word ("":"Current Window",). It will removes the current window option in the nicEdit. Then save your file and check in the browser.
It will work.


text:
Q: The minimax function calculating incorrectly for the 2nd board test The assignment telling what I have to do
So I'm following a CodeHS course for building an AI tic tac toe game, however while I was trying to finish up my minimax function, it returns wrong answers for the 2nd board test(the tests at the bottom) I don't know why. Help me out please!
Also, since the site is asking me to fill out random words, im just going to type random stuff here:
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
board = []
##Copy your check_tie and check_win functions from the previous lesson
# and any other function needed for those functions to work.
def check_col_win(player):
    if board[0][0] == board[1][0] == board[2][0] == player:
        return True
    elif board[0][1] == board[1][1] == board[2][1] == player:
        return True
    elif board[0][2] == board[1][2] == board[2][2] == player:
        return True
    else:
        return False
def check_row_win(player):
    if board[0][0] == board[0][1] == board[0][2] == player:
        return True
    elif board[1][0] == board[1][1] == board[1][2] == player:
        return True
    elif board[2][0] == board[2][1] == board[2][2] == player:
        return True
    else:
        return False

def check_diag_win(player):
    if board[0][0] == board[1][1] == board[2][2] == player:
        return True
    elif board[0][2] == board[1][1] == board[2][0] == player:
        return True
    else:
        return False

def check_win(player):
    return check_col_win(player) or check_row_win(player) or check_diag_win(player)

def check_tie():
    for i in range(3):
        for j in range(3):
            if board[i][j] == "-":
                return False
    return True
##Copy over your place_player function
def is_valid_move(row, col):
    if board[row][col] == "-":
        return True
    else:
        print("Please enter a valid move")
        return False

#places player on row,col on the board
def place_player(player, row, col):
    if is_valid_move(row, col):
        board[row][col] = player

def minimax(player, optimalRow = -1, optimalCol = -1):
    #copy your basecase here:
    if check_win("O"):
        return (10, optimalRow, optimalCol)
    if check_win("X"):
        return (-10, optimalRow, optimalCol)
    if check_tie():
        return (0, optimalRow, optimalCol)

    #implement recursive case
    if player == "O":
        best = -10000
        for i in range(3):
            for a in range(3):
                if board[i][a] == "-":
                    place_player("O", i, a)
                    best, optimalRow, optimalCol = max(best, (minimax("X")[0])), (minimax("X")[1]), (minimax("X")[2])
                    board[i][a] = "-"

        return (best, optimalRow, optimalCol)

    if player == "X":
        worst = 10000
        for k in range (3):
            for l in range (3):
                if board[k][l] == "-":
                    place_player("X", k, l)
                    worst, optimalRow, optimalCol = min(worst, (minimax("O")[0])), (minimax("O")[1]), (minimax("O")[2])
                    board[k][l] = "-"

        return (worst, optimalRow, optimalCol)

##Don't edit this code
# It checks to see if your minimax function is working correctly
def print_board():
    print("\n")
    print("\t0\t\t1\t\t2")
    count = 0
    for item in board:
        row = ""
        for space in item:
            row += "\t" + space + "\t"
        print(count,row + "\n")
        count+= 1
board.append(["O","X","-"])
board.append(["-","X","-"])
board.append(["-","-","-"])
print("Calling minimax('O') on this board:")
print_board()
print("Minimax should return (0, 2, 1):", minimax("O"))
board.clear()
print("Calling minimax('O') on this board:")
board.append(["O","X","-"])
board.append(["-","X","X"])
board.append(["-","O","-"])
print_board()
print("Minimax should return (0, 1, 0) ", minimax("O"))
board.clear()
print("Calling minimax('O') on this board:")
board.append(["O","X","X"])
board.append(["O","X","X"])
board.append(["-","O","-"])
print_board()
print("Minimax should return (10, 2, 0) ", minimax("O"))

A: Honestly the question is very vague and you should let us know what the "wrong answer" is and what you expect instead. So here is some guess:
You make the very common mistake of always delivering a winning score when "O" is winning, no matter who's turn it is. Minimax should send a winning score when "O" is winning AND it is "O" turn, OR if "X" is winning AND it is "X" turn.
If "O" is winning AND it is "X" turn it should return losing score, OR if "X"´is winning AND it is "O" turn.
This should probable fix your issue.


text:
Q: Using file upload control how to upload empty folder in asp.net c#? Using file upload controls in asp.net c# how to upload empty folder.

A: You cannot upload folders anywhere. Your site needs to give the user the opportunity to create folders, eg with a TextField for the name of the folder and a button to submit the request. But you are not able to upload an empty folder. Not even a folder containing files. In this case only the files will be uploaded. Maybe you wanna use a ZIP file to upload an "archived folder".


text:
Q: Javadoc: repeated methods I've got the following situation:
interface MyInterface
  {
  void commonMethodA();
  void commonMethodB();
  void specificMethod();
  }

abstract class Base
  {
  void commonMethodA() {...}
  void commonMethodB() {...}
  }

class Derived1 extends Base implements MyInterface
  {
  void specificMethod() {...}
  }

class Derived2 extends Base implements MyInterface
  {
  void specificMethod() {...}
  }

i.e. I have an interface most of whose methods will be common to all implementators. Thus, IMHO the above architecture makes sense and indeed it works.
The only problem is with Javadoc. When it parses the Derived{1,2} classes, it concludes that there are two 'commonMethodAs' (and Bs)- one in the class Base that's extended from, another in the Interface that's implemented.
Would anyone have any recommendation? How to make Javadoc realize there's only one 'commonMethodA' ?
EDIT:
Forgot to add, there's also another
class Derived3withNoSpecifics extends Base
  {
  (...)
  }

which is NOT supposed to include specificMethod(). So making Base implement MyInterface is, sadly, not an option...
EDIT2:
Another of proposed solutions, namely splitting MyInterface into MyInterfaceCommon (as I understand, implemented by Base) and MyInterfaceSpecific (implemented by Derived{1,2}) is not going to work either, and that's because of another yet-unmentioned constraint :) : elsewhere in the program I need to be able to accept instances of both Derived1 and Derived2 as parameters to a method, and I currently do it with
void theMethod(MyInterface parameter)
   {
   (...)
   }

This method is the whole point of the existance of the MyInterface interface actually..
Here's how the produced Javadoc page looks like:
http://distorted.org/javadoc-library/org/distorted/library/DistortedTexture.html
Notice the 'getHeight()' , 'getWidth()' and 'getID()' are repeated. You do not see the class DistortedTexture is derived from and the interface it implements because both are package-local.

A: Your inheritance scheme is essentially the same as that of ArrayList. It implements List and extends AbstractList. It inherits equals() from both the interface and the abstract class, just as you do with commonMethodA. The javadoc for ArrayList shows exactly what you are complaining about: the mention equals is repeated because it's inherited from two places. That's just how Javadoc works. People are already used to that. I don't think there's any need to worry.


text:
Q: yarn errors when attempting to install node-opus? I'm attempting to install node-opus through yarn add node-opus on Windows Subsystem for Linux (I'm not sure if this is even possible but I'm trying) and I'm running into errors in the process:
it's looking like the main error is: gyp ERR! stack Error: not found: make but I feel like this is a misleading error as I've installed other packages before this one just fine?
gyp info it worked if it ends with ok
gyp info using node-gyp@5.0.3
gyp info using node@12.11.1 | linux | x64
gyp info find Python using Python version 2.7.15 found at \"/usr/bin/python\"
gyp info spawn /usr/bin/python
gyp info spawn args [
gyp info spawn args   '/usr/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py',
gyp info spawn args   'binding.gyp',
gyp info spawn args   '-f',
gyp info spawn args   'make',
gyp info spawn args   '-I',
gyp info spawn args   '/home/tai/dev/FutabaBot/node_modules/ref/build/config.gypi',
gyp info spawn args   '-I',
gyp info spawn args   '/usr/lib/node_modules/npm/node_modules/node-gyp/addon.gypi',
gyp info spawn args   '-I',
gyp info spawn args   '/home/tai/.cache/node-gyp/12.11.1/include/node/common.gypi',
gyp info spawn args   '-Dlibrary=shared_library',
gyp info spawn args   '-Dvisibility=default',
gyp info spawn args   '-Dnode_root_dir=/home/tai/.cache/node-gyp/12.11.1',
gyp info spawn args   '-Dnode_gyp_dir=/usr/lib/node_modules/npm/node_modules/node-gyp',
gyp info spawn args   '-Dnode_lib_file=/home/tai/.cache/node-gyp/12.11.1/<(target_arch)/node.lib',
gyp info spawn args   '-Dmodule_root_dir=/home/tai/dev/FutabaBot/node_modules/ref',
gyp info spawn args   '-Dnode_engine=v8',
gyp info spawn args   '--depth=.',
gyp info spawn args   '--no-parallel',
gyp info spawn args   '--generator-output',
gyp info spawn args   'build',
gyp info spawn args   '-Goutput_dir=.'
gyp info spawn args ]
gyp ERR! build error
gyp ERR! stack Error: not found: make
gyp ERR! stack     at getNotFoundError (/usr/lib/node_modules/npm/node_modules/which/which.js:13:12)
gyp ERR! stack     at F (/usr/lib/node_modules/npm/node_modules/which/which.js:68:19)
gyp ERR! stack     at E (/usr/lib/node_modules/npm/node_modules/which/which.js:80:29)
gyp ERR! stack     at /usr/lib/node_modules/npm/node_modules/which/which.js:89:16
gyp ERR! stack     at /usr/lib/node_modules/npm/node_modules/isexe/index.js:42:5
gyp ERR! stack     at /usr/lib/node_modules/npm/node_modules/isexe/mode.js:8:5
gyp ERR! stack     at FSReqCallback.oncomplete (fs.js:169:21)
gyp ERR! System Linux 4.4.0-17763-Microsoft
gyp ERR! command \"/usr/bin/node\" \"/usr/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js\" \"rebuild\"
gyp ERR! cwd /home/tai/dev/FutabaBot/node_modules/ref
gyp ERR! node -v v12.11.1
gyp ERR! node-gyp -v v5.0.3
gyp ERR! not ok"
[2/2] ⠂ node-opus
error /home/tai/dev/FutabaBot/node_modules/node-opus: Command failed.
Exit code: 1
Command: node-gyp rebuild
Arguments:
Directory: /home/tai/dev/FutabaBot/node_modules/node-opus
Output:
gyp info it worked if it ends with ok
gyp info using node-gyp@5.0.3
gyp info using node@12.11.1 | linux | x64
gyp info find Python using Python version 2.7.15 found at "/usr/bin/python"
gyp info spawn /usr/bin/python
gyp info spawn args [
gyp info spawn args   '/usr/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py',
gyp info spawn args   'binding.gyp',
gyp info spawn args   '-f',
gyp info spawn args   'make',
gyp info spawn args   '-I',
gyp info spawn args   '/home/tai/dev/FutabaBot/node_modules/node-opus/build/config.gypi',
gyp info spawn args   '-I',
gyp info spawn args   '/usr/lib/node_modules/npm/node_modules/node-gyp/addon.gypi',
gyp info spawn args   '-I',
gyp info spawn args   '/home/tai/.cache/node-gyp/12.11.1/include/node/common.gypi',
gyp info spawn args   '-Dlibrary=shared_library',
gyp info spawn args   '-Dvisibility=default',
gyp info spawn args   '-Dnode_root_dir=/home/tai/.cache/node-gyp/12.11.1',
gyp info spawn args   '-Dnode_gyp_dir=/usr/lib/node_modules/npm/node_modules/node-gyp',
gyp info spawn args   '-Dnode_lib_file=/home/tai/.cache/node-gyp/12.11.1/<(target_arch)/node.lib',
gyp info spawn args   '-Dmodule_root_dir=/home/tai/dev/FutabaBot/node_modules/node-opus',
gyp info spawn args   '-Dnode_engine=v8',
gyp info spawn args   '--depth=.',
gyp info spawn args   '--no-parallel',
gyp info spawn args   '--generator-output',
gyp info spawn args   'build',
gyp info spawn args   '-Goutput_dir=.'
gyp info spawn args ]
gyp ERR! build error
gyp ERR! stack Error: not found: make
gyp ERR! stack     at getNotFoundError (/usr/lib/node_modules/npm/node_modules/which/which.js:13:12)
gyp ERR! stack     at F (/usr/lib/node_modules/npm/node_modules/which/which.js:68:19)
gyp ERR! stack     at E (/usr/lib/node_modules/npm/node_modules/which/which.js:80:29)
gyp ERR! stack     at /usr/lib/node_modules/npm/node_modules/which/which.js:89:16
gyp ERR! stack     at /usr/lib/node_modules/npm/node_modules/isexe/index.js:42:5
gyp ERR! stack     at /usr/lib/node_modules/npm/node_modules/isexe/mode.js:8:5
gyp ERR! stack     at FSReqCallback.oncomplete (fs.js:169:21)
gyp ERR! System Linux 4.4.0-17763-Microsoft
gyp ERR! command "/usr/bin/node" "/usr/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /home/tai/dev/FutabaBot/node_modules/node-opus
gyp ERR! node -v v12.11.1
gyp ERR! node-gyp -v v5.0.3
gyp ERR! not ok```

A: Looks like the problem was that I lacked build-essential - installing that (via sudo apt-get install build-essential) solved the issue for me and got things moving again.


text: Q: In django unittests how do you specify a database that you are modifying? In django, while testing, how do you resolve the error 'Database connections to {blah} are not allowed in this test. Add {blah class} to ensure proper test isolation and silence this failure'?


text:
Q: Clarity Wizard - Jump to page X on open (clrWizardOpenChange) I've created a wizard with three pages.
When the wizard opens, I want to directy navigate to page two and not start one page one.
I tried to use the clrWizardOpenChange Event on my wizard, but this.wizard.pages seems to be undefined or no pages are initialized at this moment.
Is there some way to achieve this behaviour?
Stackblitz

A: You're opening the wizard in the ngOnInit() of your own component. At that point none of the views or the pages exist, your app is pretty much still bootstraping.
If I use a button to open the wizard and just group the "skip to second page" and the "open" in the same callback, it works fine: https://stackblitz.com/edit/open-wizard-page?file=app/app.component.ts


text:
Q: Android: No debugging symbols found in gdbserver I try to attach a process on my rooted Android and create corefile with GDB but it can't create a gcore file because the symbols could not be found.
on my phone, i open Terminal app and i input
su

to grant root access in Terminal. i input
dumpsys meminfo

to show all running processes. i input
gdbserver :1234 --attach 5132

on my computer, i open gdb.exe (from Android NDK) and i input
(gdb) target remote 192.168.1.13:1234

and i got those infomation
(gdb) target remote 192.168.1.13:1234
Remote debugging using 192.168.1.13:1234
warning: Architecture rejected target-supplied description
Reading /system/bin/app_process32_original from remote target...
warning: File transfers from remote targets can be slow. Use "set sysroot" to access files locally instead.
warning: A handler for the OS ABI "Cygwin" is not built into this configuration
of GDB.  Attempting to continue with the default arm settings.

Reading /system/bin/app_process32_original from remote target...
warning: A handler for the OS ABI "Cygwin" is not built into this configuration
of GDB.  Attempting to continue with the default arm settings.

Reading symbols from target:/system/bin/app_process32_original...(no debugging symbols found)...done.
0xb6e8b0f8 in ?? ()

With my own compiled gdb.exe, i got another info
(gdb) target remote 192.168.1.13:1234
Remote debugging using 192.168.1.13:1234
warning: Can not parse XML target description; XML support was disabled at compile time
Reading /system/bin/app_process32_original from remote target...
warning: File transfers from remote targets can be slow. Use "set sysroot" to access files locally instead.
Reading /system/bin/app_process32_original from remote target...
Reading symbols from target:/system/bin/app_process32_original...(no debugging symbols found)...done.
Remote 'g' packet reply is too long: fcffffff605fd9be10000000ffffffff0000000008000000000000005a010000a87687b414000000000000004010c032105fd9be005fd9be1352e6b6f8b0e8b610000f204a280000000000003d0000001100000000000000000000006000000004000000d002000068010000680100003702000052000010110000001600000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004a28000072002e0073006500720076006900630065002e0056006f006900700043006f006e006e006500630074006f0072005300e83bb770e83bb77088639b70e83bb770e83bb770e83bb770e83bb770e83bb770e83bb770e83bb770e83bb770e83bb770e83bb770e83bb770e83bb770e83bb77011000060
0xb6e8b0f8 in ?? ()

i type
gcore

and it says
Can't create a corefile

I have installed the correct gdbserver binary that match with my kernel architecture in /system/bin
I tried different Android OSes below Android 4.4.4 which does not have PIE protection thing, but i still getting the same problem. I tried to use ported version gdb client and it works perfectly.
I just wanna save the corefile with my powerful device running Android 5.1.1 with 2 GB RAM, instead using gdb client on my low-end tablet that has 512 MB RAM and running Android 4.4.4, and the gdb could not fully create the corefile due to low RAM.

A: When compiling the GDB, i must give the target --target arm-linux-androideabi instead --target arm-eabi and it works perfectly

A: Just download gdb source and compile with below steps:
1).Compile gdb with below command:
cd gdb-7.11/gdb
./configure --target=arm-linux-androideabi --with-python --prefix=$HOME/mybinaries/bin
make
make install

2).Compile gdbserver with below command:
cd gdb-7.11/gdb/gdbserver
CC=arm-linux-androideabi-gcc LDFLAGS="-fPIC -pie" ./configure --target=arm-linux-androideabi --host=arm-linux-androideabi --prefix=$HOME/mybinaries/bin
make
make install


text:
Q: JPA Subquery missing from-clause, but when I try to execute the query it works This is my code looks like
@Query(value = "SELECT pu.id_user AS idUser, " +
        "pu.full_name AS \"name\", " +
        "pu.username, " +
        "pu.email, " +
        "CASE pu.status " +
        "WHEN 0 THEN 'Blocked' " +
        "WHEN 1 THEN 'Unblocked' " +
        "END status, " +
        "(SELECT branch_name AS \"branch\" " +
        "FROM schema_a.branch aa " +
        "WHERE mpb.branch_id IS NOT NULL AND mpb.parent_branch_id IS NOT NULL AND " +
        "branch_id = mpb.parent_branch_id " +
        ") AS branch, " +
        "mpb.branch_id AS childId, " +
        "mpb.branch_name AS childName, " +
        "mpb.parent_branch_id AS parentBranchId, " +
        "r.role_name AS roleName " +
        "FROM schema_a.user pu " +
        "JOIN schema_a.branch mpb ON pu.id_branch = mpb.id_branch " +
        "JOIN schema_a.\"role\" r ON pu.id_role = r.id_role " +
        "WHERE pu.is_deleted = false", nativeQuery = true)
Page<UserAndBranch> findAllByIsDeletedIsFalse(Pageable pageable);

the result i got

Caused by: org.postgresql.util.PSQLException: ERROR: missing FROM-clause entry for table "aa"

That native query is executed succesfully in DBeaver, nothings different just remove the quotation mark, what am I missing?


text:
Q: Power_profile cpu cluster on Android Looking at the github and power_profile of devices based on the same SoC.
I noticed that Motorola devices have a different order in cluster.
As with others in Cluster0 there are slower cores (voltage and frequency) and in Cluster1 faster. But Motorola has it the other way around, i.e. faster in Cluster0 and slower in Cluster1.
Does this mean that faster cores are considered (or rather only marked) as slower ones? And does this have any effect on energy consumption?


text:
Q: $(0,0,\dots,0,1), (1,2,3,\dots,n-1,0)$ are in the same orbit under the map given by $(a_1, \dots, a_n) \to (a_2, \dots, a_n, (a_n+a_1 \bmod n)).$ Let $f: \mathbb{Z}_n^n \to \mathbb{Z}_n^n$ be the map given by $(a_1, \dots, a_n) \to (a_2, \dots, a_n, a_n+a_1).$ Prove that there exists $k$ such that $f^k(1,2,3,\dots,n-1,0) = (0,0,\dots,0,1).$
I have proved this result for $n \le 6$ and when $n$ is prime. I have shown $f$ is invertible, and more specifically, as linear transformation it has determinant $1.$ Unfortunately, I cannot make any further progress. If it helps, the real problem I am trying to solve has $(0,0,\dots, 1)$ replaced by $(0,0,\dots,a)$ for some $a \in \mathbb{Z}_n,$ i.e. we only need to show one of $n$ possible choices works. However, I figured that we can always show $a=1$ works.
Any ideas, hints, or approaches? A linear algebra approach via diagonalizing $f$ doesn't seem promising because the eigenvalues and eigenvectors are very messy to work with. Maybe there's another path through linear algebra.

A: Since $f$ is invertible and $(\mathbb Z/n\mathbb Z)^n$ is finite, the inverse of $f$ is a power of $f$.
This means it suffices to go the other way, from $(0,0,...,1)$ to $(1,2,...,n-1,0)$ but that is easy to do:
$$f^n(0,0,...,1)) = (1,1,...,1)$$
and then
$$f(1,1,...,1) = (1,1,...,1,2)$$
$$f(1,1,...,2) = (1,1,...,1,2,3)$$
and so on until we reach
$$(1,2,3,...,n) = (1,2,3,...,n-1,0)$$
since $n=0$.
In total, we've shown that $f^{2n}(0,0,...,0,1) = (1,2,...,n-1,0)$ which means that
$$(0,0,...,0,1) = f^{-2n}(1,2,...,n-1,0) = (f^{-1})^{2n}$$
but as remarked above, $f^{-1}$ can be written as $f^k$ for some $k$, so $f^{2nk}$ will do the job.


text:
Q: Value Validation Data:
var dataArr = [
    {id: 123, str:"Alexey Ayzin", bg:"#FFFFFF"},
    {id: 234, str:"Mira Mdivani"},
    {id: 345, str:"Maria Iliakova"},
    {id: 456, str:"Dennis Ayzin"}
];

As you can see, bg:"FFFFFF" exists in one of the subsets, but not the others. How can I change this:
for (var i = 0; i < datalength; i++) {
    if(dataArr[i].bg === "undefined"){
        data[i].bg = stringToColour(dataArr[i].str);
    }
}

So that it checks each subset for the existence of a BG and if it doesn't exist, fills it with one. JSFiddle

A: If item has bg, don't do anything, else - set new bg
var dataArr = [
    {id: 123, str:"Alexey Ayzin", bg:"#FFFFFF"},
    {id: 234, str:"Mira Mdivani"},
    {id: 345, str:"Maria Iliakova"},
    {id: 456, str:"Dennis Ayzin"}
];
dataArr.forEach(function (item){
    item.bg = item.bg || '#FFFFFF';
});

function assignColor(arr, prop, color){
    arr.forEach(function (item){
        item[prop]= item[prop] || color;
    });
}

// usage
assignColor(dataArr, 'bg', '#FFFFFF'); // <== or any other color

// UPDATE
//----------------------------

// get first value of color from array and assign to other
var item = dataArr.find(function(item){ // this will find first item which has defined color
    return !!item.bg;
});
assignColor(dataArr, 'bg', item.bg);

A: You could use the in operator, if you have falsy values, which are valid.
if (!('bg' in dataArr[i])) {
    // set dataArr[i].bg
}

A: What I ended up doing was the following:
for(var elem in payload.data){
    var isPresent = 0;
    for(var key in payload.data[elem]){
        if(key == "bG"){
            //change boolean if bG is present
            isPresent = 1;
        }
    }
    if(!isPresent){
        bGHex = stringToColour(payload.data[elem].str);
        payload.data[elem].bG = bGHex
    }

and then the rest of my code. This worked extremely well, especially after digging deeper into the logic of it.


text:
Q: Calculate 'interval and increment' for slide in animation in Java Swing I'm building an application which has a slideshow in its homepage, currently I use Thread.sleep(10) and add/sub the x position of panel I want to slide.
For example: slideIn(30, panel_1, 10) < this will cause panel_1 to slide in with interval of 30ms and subtracts its x by 10 overtime until the panel is in center/occupy the slideshow_panel. But the con of this method is that the sliding animation won't smooth, I want the sliding animation/transition as smooth as Bootstrap Carousel. Is there a way to calculate the speed and increment/decrement value for slide transition speed?

A: Actually, I've something that's almost perfect for this. I assume you can create a Path2D for your animation path, right? And it also seems like you want a constant speed. There are a couple of references to my project (http://sourceforge.net/p/tus/code/HEAD/tree/) for calculating distance and showing the JPanel for instance, but it shouldn't be hard to remove them and replace with standard java. Try it out
public abstract class PathAnimation {
    private Path2D mPath;
    private double totalLength;

    /**
     * Be careful to call path.closePath before invoking this constructor
     * @param path
     */
    public PathAnimation(Path2D path) {
        mPath = path;
        totalLength = 0;
        PathIterator iterator = mPath.getPathIterator(null);
        //Point2D currentLocation;// = path.getCurrentPoint();
        double[] location = new double[6];
        iterator.currentSegment(location);
        while (!iterator.isDone()) {
            double[] loc = new double[6];
            iterator.next();
            iterator.currentSegment(loc);
            if (loc[0] == 0 && loc[1] == 0) continue;
            double distance = MathUtils.distance(location[0], location[1], loc[0], loc[1]);
            totalLength += distance;
            location = loc;
        }
    }

    @Override
    public Point2D getLocationAtTime(int time) {
        return getLocationAtTime(time / (double) getTotalAnimationTime());
    }

    public Point2D getLocationAtTime(double pctTime) {
        double len = totalLength * pctTime;
        PathIterator iterator = mPath.getPathIterator(null);
        double[] location = new double[6];
        iterator.currentSegment(location);
        while (!iterator.isDone()) {
            double[] loc = new double[6];
            iterator.next();
            iterator.currentSegment(loc);
            double distance= MathUtils.distance(location[0], location[1], loc[0], loc[1]);
            if (distance > len) {
                double pctThere = len / distance;
                double xSpot = location[0] * (1 - pctThere) + loc[0] * pctThere;
                double ySpot = location[1] * (1 - pctThere) + loc[1] * pctThere;
                return new Point2D.Double(xSpot, ySpot);
            }
            len -= distance;
            location = loc;
        }
        throw new ArrayIndexOutOfBoundsException("Path is too short or time is too long!");
    }

    /**
     * Number of milliseconds that this animation spans
     * @return
     */
    public abstract int getTotalAnimationTime();

    public static void main(String args[]) {
        Rectangle rect = new Rectangle(10,10,20,20);
        final Path2D.Double myPath = new Path2D.Double((Shape)rect);
        myPath.closePath();
        final PathAnimation myAnimation = new PathAnimation(myPath) {
            Area star = new Area(PaintUtils.createStandardStar(15, 15, 5, .5, 0));
            @Override
            public Dimension getSizeAtTime(int time) {
                return new Dimension(15,15);
            }

            @Override
            public void paintAtTime(Graphics2D g, int time) {
                Area toPaint = star;
                if ((time / 150) % 2 == 1) {
                    Dimension size = getSizeAtTime(0);
                    toPaint = new Area(toPaint);
                    PaintUtils.rotateArea(toPaint, Math.PI / 6);
                }
                g.setColor(Color.YELLOW);
                g.fill(toPaint);
                g.setColor(Color.RED);
                g.draw(toPaint);
            }

            @Override
            public int getTotalAnimationTime() {
                return 10000;
            }
        };
        System.out.println(myAnimation.getLocationAtTime(0));
        System.out.println(myAnimation.getLocationAtTime(2500));
        System.out.println(myAnimation.getLocationAtTime(4000));
        System.out.println(myAnimation.getLocationAtTime(5000));
        System.out.println(myAnimation.getLocationAtTime(7000));
        System.out.println(myAnimation.getLocationAtTime(7500));
        System.out.println(myAnimation.getLocationAtTime(9000));
        System.out.println(myAnimation.getLocationAtTime(10000));

        final JPanel jp = new JPanel() {
            public void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2 = (Graphics2D) g;
                int time = ((int) System.currentTimeMillis()) % myAnimation.getTotalAnimationTime();
                int time2 = (time + myAnimation.getTotalAnimationTime() / 2) % myAnimation.getTotalAnimationTime();
                Point2D pt = myAnimation.getLocationAtTime(time);
                Point2D pt2 = myAnimation.getLocationAtTime(time2);
                Dimension size = myAnimation.getSizeAtTime(time);
                g2.translate(pt.getX() - size.width / 2, pt.getY() - size.height / 2);
                myAnimation.paintAtTime(g2, time);
                g2.translate(- (pt.getX() - size.width / 2), - (pt.getY() - size.height / 2));
                g2.translate(pt2.getX() - size.width / 2, pt2.getY() - size.height / 2);
                myAnimation.paintAtTime(g2, time2);
                g2.translate(- (pt2.getX() - size.width / 2), - (pt2.getY() - size.height / 2));
                g2.setColor(Color.BLACK);
                g2.draw(myPath);
            }
        };
        WindowUtilities.visualize(jp);
        AbstractAction action = new AbstractAction() {
            public void actionPerformed(ActionEvent ae) {
                jp.repaint();
            }
        };
        javax.swing.Timer t = new javax.swing.Timer(30, action);
        t.start();
    }
}


text: Q: how to initialize hibernate connection in ServletContextListener and access any where (NON - SERVLET CLASS)? how to initialize hibernate connection in ServletContextListener and access any where (NON - SERVLET CLASS) ?


text:
Q: From 2 mySQL databases, to one I have two database that i want to combine.
I have two values who are exactely the same in both databases.
It's id & id_p
The first database is called: locatie
and has: ID, latitude, longitude, timestamp
the other database is called: persooninfo
and has id_p, voornaam, achternaam, opleiding, diploma, bezig
Does anyone know how I can combine these two databases?

A: --To get all the columns from locatie table
select l.* from   locatie l
join   persooninfo p
on     l.id=p.id_p

--To get all the columns from persooninfo table
select l.* from   locatie l
join   persooninfo p
on     l.id=p.id_p

----To get all the columns from persooninfo and locatie  table
select * from   locatie l
join   persooninfo p
on     l.id=p.id_p


text:
Q: Regex: don't match if the pattern start with / My regex (PCRE):
\b([\w-.]*error)\b(?:[^-\/.]|\.\W|\.$|$)

is a match (the actual match is surrounded by stars) :
**this.is.an.error**
**this.IsAnerror**
**this.is.an.error**.
**this.is.an.error**(
bla **this_is-an-error**
**this.is.an.error**:
this is an (**error**)

not a match:
this.is.an.error.but.dont.match
this.is.an.error-but.dont.match
this.is.an.error/but.dont.match
this.is.an.error/
/this.is.an.error

for this sample: /this.is.an.error
I can't manage to have a condition that will reject the whole match if it starts with the character /.
every combination I've tried resulted in some partial catch (which is not the desired).
Is there any simple or fancy way to do that?

A: You can try to add lookabehinds at the beginning instead of a word boundary:
(?<!\/)(?<=[^\w-.])([\w-.]*error)\b(?:[^-\/.]|\.\W|\.$|$)

Explanation:

*

*(?<!\/) - negative lookbehind assuring there is no / before the first character;

*(?<=[^\w-.]) - word boundary implementation taking into account your extended definition of characters accepted for a word [\w-.];

Demo

A: Prepend your regex with \/.*|:
\/.*|\b([\w-.]*error)\b(?=[^-\/.]|(?:\.\W?)?$)

Now just like before the first capturing group holds the desired part.
See live demo here
Note: I made some modifications to your regex to remove unnecessary alternations.


text:
Q: Can django background tasks be deleted directly from the database? We use django-background-tasks in our application and I have had no issue with deleting tasks from the admin page when running the app in my system. But when I tried to delete some tasks from the production version (hosted with gcp), I keep getting internal server (500) errors. What could be the reason for this?
Alternately, is it advisable/safe to directly delete the tasks from the background_task table in the database?

A: I deleted the tasks from the background_task table and it hasn't caused any issues.
The 500 could be due to some access issues (maybe some settings have to be configured to allow table modifications via admin page, over ssh?).


text:
Q: Scala: duplicate lists n times inside another list I have a list in scala and from that list I want to generate a list of lists in which each list will be duplicated n times.
I tried to use tabulate:
val list = orders.map(ord => List.tabulate(ord.quantity * ord.prod.tasks.size)(ord.prod.tasks))

But it gives me an error: here.
I tried to use List.fill, but it returns a List[List[List[Task]]].
val list = orders.map(ord => List.fill(ord.quantity*ord.prod.tasks.size)(ord.prod.tasks))

Is there a way to make fill return a List[List[Task]]?

A: val list = orders.flatMap(ord => List.fill(ord.quantity*ord.prod.tasks.size)(ord.prod.tasks))


text:
Q: C++ operator overloading options I have created a Date type, which had 3 int members day_, month_, and year_.
I have overloaded the operator<< for Date and I don't know what is the best choice: I have currently a function called ostream& showDate(ostream& os) defined as follows:
std::ostream& Date::showDate(std::ostream& os) const {

    return os << day_ << '/' << month_ << '/' << year_ << std::endl;
}

The operator<< call it:
std::ostream& operator<<(std::ostream& os, const Date& d) {

    return d.showDate(os);
}

But there is another option:
std::ostream& operator<<(std::ostream& os, const Date& d) {

   return os << d.getDay() << '/' << d.getMonth() << '/' << d.getYear() << std::endl;
}

What's the best choice?

A: The second option is the most common way of doing this, and therefore probably the most readable (matches a common pattern).
It also has the advantage that the Date class doesn't have to know anything about streams. The showDate member function introduces a coupling between the two classes, that are otherwise independent.

A: The answers to this are really going to be opinion-based.   Technically, there are few advantages with any of the options, as they are functionally equivalent (assuming sane implementation of accessors, appropriate access control, etc).
Of the three functionally equivalent choices you've given, I would lean toward either the first or the third, since there would typically be no need for your showDate() member function by any other function than the operator<<().
As to choice between the first and third, that really depends on whether it makes sense for the operator<<() to directly access class data members.   If the members are public, there is possibly no reason to prefer one over the other.  If they are private, then the choice will be determined by whether it makes sense in your design that the operator<<() be a friend (i.e. part of the class's interface).
An aside:  I would not stream std::endl within your operator<<().     Let the user of your class decide if a newline and flush are appropriate.


text:
Q: game development need help examples? i'm developing game in visual c++ can anyone give me links for developed games in visual c++ so i can download the sample games to study the structure of games
any useful readymade games in visual-c++ links useful

A: Try Nehe's tutorials:
http://nehe.gamedev.net/

A: Parallax released the source code for some of their old games a while back. These are old games from the mid to late 90's and they are missing proprietary drivers and data files. I am sure there are other examples online.
Descent 1 2
FreeSpace 2


text:
Q: How to use va_arg to modify the value of a variadic parameter #include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>

void tag_log(const char *format, ...) {
    va_list ap;
    va_start(ap, format);
    for (int i = 0; i < 4; i++) {
        va_arg(ap, int) += 100; // is wrong?
    }
    va_end(ap);
    va_start(ap, format);
    vprintf(format, ap);
    va_end(ap);
}

int main() {
    tag_log("%d, %d, %d, %d\n", 1, 2, 3, 4);
}

Since va_arg returns an rvalue, the content cannot be modified. How to modify the content of the variable parameter?
Expected output: 101, 102, 103, 104
thanks!!!

A:
va_arg(ap, int) = 100; // is wrong?

Yes, it's wrong. va_arg returns an rvalue (which isn't assignable).
I suggest making a variadic template instead.
#include <cstdio>
#include <utility>

template<class... Args>
void tag_log(const char *format, Args&&... args) {
    ((args += 100), ...); // fold expression
    std::printf(format, std::forward<Args>(args)...);
}

int main() {
    tag_log("%d, %d, %d, %d\n", 1, 2, 3, 4);
}

Output:
101, 102, 103, 104


text:
Q: How to call TagLib in Windows Runtime Component C++ So I am using TagLib in WinRT Component and trying to get Album arts of mp3 files and then save them to separate files. So far I am using this code:
            auto albumartFolder = ApplicationData::Current->LocalFolder;
            StorageFile^ destStorageFile = create_task(albumartFolder->CreateFileAsync("\\AlbumArts\\" + destFileName + ".jpg")).get();
            TagLib::MPEG::File mpegFile(file->Path->Data());
            static const char *IdPicture = "APIC";

            TagLib::ID3v2::Tag *id3v2tag = mpegFile.ID3v2Tag();
            TagLib::ID3v2::FrameList Frame;
            TagLib::ID3v2::AttachedPictureFrame *PicFrame;
            void *RetImage = NULL, *SrcImage;
            unsigned long Size;
            FILE *jpegFile;
            jpegFile = fopen((char*)destStorageFile->Path->Data(), "wb");
            if (id3v2tag)
            {
                Frame = id3v2tag->frameListMap()[IdPicture];
                if (!Frame.isEmpty())
                {
                    for (TagLib::ID3v2::FrameList::ConstIterator it = Frame.begin(); it != Frame.end(); ++it)
                    {
                        PicFrame = (TagLib::ID3v2::AttachedPictureFrame *)(*it);
                        if ( PicFrame->type() ==
                        TagLib::ID3v2::AttachedPictureFrame::FrontCover)
                        {
                            Size = PicFrame->picture().size();
                            SrcImage = malloc(Size);
                            if (SrcImage)
                            {
                                memcpy(SrcImage, PicFrame->picture().data(), Size);
                                fwrite(SrcImage, Size, 1, jpegFile);
                                fclose(jpegFile);
                                free(SrcImage);
                            }
                        }
                    }
                }
            }

This code should work without a bug I know but here are the exceptions I am recieving:
1>LibraryModule.obj : error LNK2019: unresolved external symbol "public: __thiscall TagLib::FileName::FileName(wchar_t const *)" (??0FileName@TagLib@@QAE@PB_W@Z) referenced in function "public: bool __thiscall <lambda_88d334404ef137d46dbb027b26f435b8>::operator()(void)const " (??R<lambda_88d334404ef137d46dbb027b26f435b8>@@QBE_NXZ)
1>LibraryModule.obj : error LNK2019: unresolved external symbol "public: __thiscall TagLib::MPEG::File::File(class TagLib::FileName,bool,enum TagLib::AudioProperties::ReadStyle)" (??0File@MPEG@TagLib@@QAE@VFileName@2@_NW4ReadStyle@AudioProperties@2@@Z) referenced in function "public: bool __thiscall <lambda_88d334404ef137d46dbb027b26f435b8>::operator()(void)const " (??R<lambda_88d334404ef137d46dbb027b26f435b8>@@QBE_NXZ)
1>LibraryModule.obj : error LNK2019: unresolved external symbol "public: virtual __thiscall TagLib::MPEG::File::~File(void)" (??1File@MPEG@TagLib@@UAE@XZ) referenced in function "public: bool __thiscall <lambda_88d334404ef137d46dbb027b26f435b8>::operator()(void)const " (??R<lambda_88d334404ef137d46dbb027b26f435b8>@@QBE_NXZ)

Any help regarding this would be appreciated very much!
Edit:
So, this is marked as duplicate but I still cannot fix the problem. How do I link Taglib correctly? I installed the Nuget package, was I wrong to do so?


text:
Q: Why doesn't my listCollectionView show new items added to the underlying list (in flex)? I have an (empty) ArrayCollection that I wrap with a ListCollectionView.
Then I add a series of items to the ArrayCollection, but these are not showing up in the view.
public var transactions : ArrayCollection = new ArrayCollection();
public var filteredTransactions : ListCollectionView = new ListCollectionView(transactions);

transactions contains 150 items, filteredTransactions contains none. I originally thought it was the filter I was applying, but even when I remove the filter, I still get no items in the filtered list.
Have I missed a step?
Do I need to add the items to the view as well as the underlying collection (this would seem to defeat the purpose of using a view though...)?

A: If you aren't using addAll, addItem, or addItemAt to put items in the ArrayCollection, try that as a solution first.  Adding items directly to the Array that the ArrayCollection wraps will not dispatch CollectionEvents.
Also, try to use the ListCollectionView's refresh() method after setting its list property to the ArrayCollection.
If neither of these solutions work then please post additional code.


text:
Q: A string with string interpolation format from database use it in C# code For example I have a string that was retrieved from the database.
string a = "The quick brown {Split[0]}   {Split[1]} the lazy dog";
string b = "jumps over";

And then I will perform this code.
String[] Split= b.Split(' ');
String c= $"{a}";
Console.Writeline(c):

This method is not working. Do you have any idea how can this become possible? I appreciate your help. ^-^

A: The interpolated strings are interpreted by the compiler. I.e., for example in
string a = "fox";
string b = "jumps over";

// this line ...
string s = $"The quick brown {a} {b} the lazy dog";

... is converted to
string s = String.Format("The quick brown {0} {1} the lazy dog", a, b);

... by the compiler.
Therefore, you cannot use string interpolation at runtime with variable names in a (regular) string.
You must use String.Format at runtime:
string a = "The quick brown {0} {1} the lazy dog";
string b = "fox;jumps over";

string[] split = b.Split(';');
string c = String.Format(a, split[0], split[1]);
Console.Writeline(c):

Note that a runtime, the names of the local variables are not known. If you decompile a compiled C# programm, the decompiled code will contain generic names for local variables like l1, l2 etc. (depending on the decompiler).

A: As LasseV.Karlsen and Hans Kesting
has explained you can use string.Format in this scenario. Let me give you a quick example:
string b = "jumps over";
string[] Split = b.Split(' ');
string c = string.Format("The quick brown fox {0} {1} the lazy dog.",Split[0], Split[1]);
Console.WriteLine(c);

Note that this is just one example with string.Format while there exist countless other uses for the same. Your best resource to learn more about this method could be Microsoft Documentation.


text:
Q: Copy a linked list typedef struct Node
{
  int data;
  Node *next;
  Node *other;
};

Node *pHead;

pHead is a singly linked list. The next field points to the next element in the list. The other field may point to any other element (could be one of the previous nodes or one of the nodes ahead) in the list or NULL.
How does one write a copy function that duplicates the linked list and its connectivity? None of the elements (next and other) in the new list should point to any element in the old list.

A: Create a new node for every node in the old list, copy the corresponding data and make the next pointer of the nodes in the new list point to their successor in the new list, forgetting the other pointer for time being. At the time of creating a new node remember the mapping of node address something like:
Old_list   New_list
-------------------
0x123      0x345     [ addresses of the first node]
0xabc      0xdef     [ addresses of the second node]
...

In the second pass pass for every node in the new list consider its other pointer and find its corresponding node in the new list from the map and use it as the other pointer of this node (node in the new list).

A: Came across this. Hope it helps!
Citing one solution from this link, below.
1) Create the copy of 1 and insert it between 1 & 2, create the copy of 2 and insert it between 2 & 3.. Continue in this fashion, add the copy of N to Nth node
2) Now copy the arbitrary link in this fashion
 if original->arbitrary is not NULL
   original->next->arbitrary = original->arbitrary->next;  /*TRAVERSE TWO NODES*/
 else
   original->next->arbitrary=NULL;

This works because original->next is nothing but copy of original and Original->arbitrary->next is nothing but copy of arbitrary.
3) Now restore the original and copy linked lists in this fashion in a single loop.
 original->next = original->next->next;
 copy->next = copy->next->next;

4) Make sure that last element of original->next is NULL.
Sample code, Time Complexity O(N), Space Complexity O(1)
pNode copy_list(pNode head) {
  // pre-condition: node->other either points into the list or NULL
  if (!head) return NULL;

  pNode node = head, copied = NULL, cnode = NULL;
  for ( ; node; node = node->next->next) {
    // make copy
    cnode = newnode(node->next, node->data);
    cnode->other = node->other;
    if (node == head)
      copied = cnode;

    // insert the copy between originals
    node->next = cnode;
    // node -> cnode -> (orig)node->next
  }

  for (node = head; node && node->next;
       node = node->next->next /* only original nodes */)
    if (node->other)
      node->next->other = node->other->next;
    else
      node->next->other = NULL;

  // restore lists
  node = head; cnode = copied;
  for ( ; cnode && cnode->next; node = node->next, cnode = cnode->next) {
    node->next = node->next->next;
    cnode->next = cnode->next->next;
  }
  node->next = NULL;
  return copied;
}

Complete program is at http://gist.github.com/349630

A: I like the solution of Codaddict, but this would be my answer:

*

*iterate over the linked list.
a. store the data in an array (position i for the i'th node of course)
b. replace data with i to create an id (this way you'll definitely know which node you are talking about)

*create the 2nd linked list the size of the first (ignore the other pointer for now)
*. maybe use a temporary array to find each node quickly

*iterate over the first linked list.
a. find out which id other points to (which is in that nodes data)
b. recreate this link in the 2nd linked list (the temporary array could really help here)

*iterate over both linked list simultaneously and replace the ids in data with the stored data
Of course you could collapse some processing and iterating here. But this would roughly be what I would do/think of.


text:
Q: Issue with display textview Android? I have a problem with my project I have a long text which goes off screen and I need a scrollable I fixed that however now my text goes off screen to the right it doesn't stay all compact in anyone have any suggestions? I want my text to be in and fully visible as well as having a scroll since its a lot. Also I could force orientation however I don't want to do that since the design will look bad. I tried a few solutions but there is no hope.
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:gravity="center_horizontal">

<ScrollView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:weightSum="1">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/abouthusky"
            android:id="@+id/abouthusky"
            android:ellipsize="middle"
            android:layout_weight=".5"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"

            />
    </LinearLayout>
</ScrollView>

Here is the image of how it looks like:
http://i57.tinypic.com/2qt8hvm.png
Here is the Fragment code:
public class Fragment_list_1 extends android.app.Fragment {
    View rootview;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootview = inflater.inflate(R.layout.menu_layout_1, container, false);
        return rootview;

    }
}

Also I know I asked this in the past but I messed up on the question and did not provide enough detail.
Thank you.

A: Change your xml to this::
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal" >

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" >

            <TextView
                android:id="@+id/abouthusky"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="20dp"
                android:maxLines="25"
                android:scrollbars="vertical"
                android:layout_margin="5dp"
                android:text="@string/abouthusky" />

        </LinearLayout>

</RelativeLayout>

And in code :
  yourTextView.setMovementMethod(new ScrollingMovementMethod())

do this.It should work

A: You can use
            textView.setMovementMethod(new ScrollingMovementMethod());
to enable scrolling in the Text View, instead of using Scroll view.

A: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="20dp"
    android:gravity="center_horizontal" >

    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" >

            <TextView
                android:id="@+id/abouthusky"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="20dp"
                android:text="@string/abouthusky" />

        </LinearLayout>
    </ScrollView>

</RelativeLayout>


text:
Q: Rearrange data from single observation to many I've a text file in following form:
x1, y1, z1, x2, y2, z2, x3, y3, z3

If I import it with read.csv I've a single observation with nine variables (in the example, the number of triplets in real file is unknown).
I want to rearrange data in order to have many observation with three variables:
x1 y1 z1
x2 y2 z2
x3 y3 z3

So I can perform operations on each triplet.
For example I want to transform this
fileData <- read.table(text = "1 2 3 10 20 30 100 200 300")

> fileData
  V1 V2 V3 V4 V5 V6  V7  V8  V9
1  1  2  3 10 20 30 100 200 300

to this:
> fileData
   V1  V2  V3
1   1   2   3
2  10  20  30
3 100 200 300

How can I split it?

A: Not sure what your actual goal is but using base R:
data.frame(matrix(fileData, ncol = 3, byrow = T))

This should get what you want
   X1  X2  X3
1   1   2   3
2  10  20  30
3 100 200 300

A: akash gave a great answer but it may not work if you have mixed data types (numeric and character) because the matrix will force everything to be one type.  An alternative is something like the following where we lapply across an index based on the number of columns desired.
fileData <- read.table(text = "m 2 3 a 20 30 cat 200 300")
rows = lapply(seq(3,ncol(fileData),by=3),
       function(x){
         range = paste("V",(x-2):x,sep="")
         output = fileData[,range]
         names(output) = c("x","y","z")
         return(output)
       })
do.call(rbind,rows)
#>     x   y   z
#> 1   m   2   3
#> 2   a  20  30
#> 3 cat 200 300


text:
Q: how to separate html from php with working form validation I am new to php. i am working on a simple contact form for my practise.It worked fine,exactly the way i want but when i tried to separate html from my Form.php file and paste it in process.html and then pressed the submit button,without filling in any of the fields, the form submits without doing the form validation and the empty data is not inserted in the db.
All i want to do is to keep html and php both is separate files and want to submit the form using the form validation i did.Any help please????
Here is my code
Form.html
<?php require_once "process.php";?>
<!doctype html>

<meta charset="utf-8">
<title>Untitled Document</title>
<link href="style.css" rel="stylesheet" type="text/css" media="all">

    <?php $arrmessage = "" ?>

<?php if($arrmessage !=""){ echo $arrmessage; }?        >

New User Registration

        <form name="form1" id="form1" action="process.php?value=submit"     method="post">

Student Name

        <input type="text" id="student_name" name="student_name" value="" placeholder="Student Name">

Email

        <input type="email" id="email" name="email" value="" placeholder="Email">

Contact Number

        <input type="text" id="contact_number" name="contact_number" value="" placeholder="Contact Number">

Gender:

Male
        <input type="radio" name="gender" value="Male" / >
        Female
        <input type="radio" name="gender" value="Female" / >

Interest:

        Laptop<input type="checkbox" id="" name="interest[]" value="laptop" >
        I-Pad<input type="checkbox" id="" name="interest[]" value="ipad" >
        Mobile<input type="checkbox" id="" name="interest[]" value="mobile" >

Date of Birth

        <select name="day">
            <option value="">Day</option>
            <option>1</option>
            <option>2</option>
            <option>3</option>
        </select>-
        <select name="month">
            <option value="">Month</option>
            <option>January</option>
            <option>February</option>
            <option>March</option>
        </select>-
        <select name="year">
            <option value="">Year</option>
            <option>2001</option>
            <option>2002</option>
            <option>2003</option>
        </select>

Street Adress

        <textarea id="street_adress" name="street_adress" placeholder="Street Adress"></textarea>

City

        <input type="text" id="city" name="city" value="" placeholder="City" >

State

        <input type="text" id="state" name="state" value="" placeholder="State" >

Country

        <select name="country">
             <?php  foreach($countries as $list) echo "<option>". $list ."
" . "</option>"; ?>
            </select>

            <input name="submit" id="submit" type="submit" value="Submit">

      </form>

Log Out

process.php
    <?php
    session_start();
    require_once("database.php");
            if(!isset($_SESSION['user_id']) && empty($_SESSION['user_id'])){
                            header("Location:login.php");
                            exit;
                        }
                        if(isset($_REQUEST['value'])){
                        //exit;
                    if (isset($_POST['submit']))
                {

                    if(empty($_POST['student_name'] )){
                        $arrmessage = "Please Enter Student Name";
                    }elseif(empty($_POST['email'] )){
                        $arrmessage = "Please Enter Email";
                    }elseif(empty($_POST['contact_number'] )){
                        $arrmessage = "Please Enter Contact Number";
                    }elseif(empty($_POST['gender'] )){
                        $arrmessage = "Please Select Gender";
                    }elseif(empty($_POST['interest'] )){
                        $arrmessage = "Please Select interest";
                    }elseif(empty($_POST['day'])){
                        $arrmessage = "Please Enter Day";
                    }elseif(empty($_POST['month'])){
                        $arrmessage = "Please Enter Month";
                    }elseif(empty($_POST['year'])){
                        $arrmessage = "Please Enter Year";
                    }elseif(empty($_POST['street_adress'] )){
                        $arrmessage = "Please Enter street_adress";
                    }elseif(empty($_POST['city'])){
                        $arrmessage = "Please Enter City";
                    }elseif(empty($_POST['state'] )){
                        $arrmessage = "Please Enter State";
                    }elseif(empty($_POST['country'] )){
                        $arrmessage = "Please Enter Country";
                    }else{
                        $arrmessage ="";
                }

                if($arrmessage =="")
            {
                $student_name = $_POST['student_name'];
                $email = $_POST['email'];
                $contact_number = $_POST['contact_number'];
                $gender = $_POST['gender'];
                $interest = $_POST['interest'];
                $checked ="";
                foreach($interest as $list){$checked .= $list .",";}
                $DOB = $_POST['day'].'-'.$_POST['month'].'-'.$_POST['year'];
                $street_adress = $_POST['street_adress'];
                $city = $_POST['city'];
                $state = $_POST['state'];
                $country = $_POST['country'];

        $sql = "INSERT INTO form (student_name,email,contact_number,gender,interest,DOB,street_adress,city,state,country)VALUES('{$student_name}','{$email}','{$contact_number}','{$gender}','{$checked}','{$DOB}','{$street_adress}','{$city}','{$state}','{$country}')";
            mysql_query($sql);
            if(mysql_insert_id() != ""){
                    echo "Records inserted successfully.";
                    }
                    header("Location:views.php");
                    exit;
                }
            }
                }
    $countries = array("Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra", "Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina", "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia", "Bosnia and Herzegowina", "Botswana", "Bouvet Island", "Brazil", "British Indian Ocean Territory", "Brunei Darussalam", "Bulgaria", "Burkina Faso", "Burundi", "Cambodia", "Cameroon", "Canada", "Cape Verde", "Cayman Islands", "Central African Republic", "Chad", "Chile", "China", "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo", "Congo, the Democratic Republic of the", "Cook Islands", "Costa Rica", "Cote d'Ivoire", "Croatia (Hrvatska)", "Cuba", "Cyprus", "Czech Republic", "Denmark", "Djibouti", "Dominica", "Dominican Republic", "East Timor", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea", "Estonia", "Ethiopia", "Falkland Islands (Malvinas)", "Faroe Islands", "Fiji", "Finland", "France", "France Metropolitan", "French Guiana", "French Polynesia", "French Southern Territories", "Gabon", "Gambia", "Georgia", "Germany", "Ghana", "Gibraltar", "Greece", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-Bissau", "Guyana", "Haiti", "Heard and Mc Donald Islands", "Holy See (Vatican City State)", "Honduras", "Hong Kong", "Hungary", "Iceland", "India", "Indonesia", "Iran (Islamic Republic of)", "Iraq", "Ireland", "Israel", "Italy", "Jamaica", "Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Korea, Democratic People's Republic of", "Korea, Republic of", "Kuwait", "Kyrgyzstan", "Lao, People's Democratic Republic", "Latvia", "Lebanon", "Lesotho", "Liberia", "Libyan Arab Jamahiriya", "Liechtenstein", "Lithuania", "Luxembourg", "Macau", "Macedonia, The Former Yugoslav Republic of", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands", "Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia, Federated States of", "Moldova, Republic of", "Monaco", "Mongolia", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia", "Nauru", "Nepal", "Netherlands", "Netherlands Antilles", "New Caledonia", "New Zealand", "Nicaragua", "Niger", "Nigeria", "Niue", "Norfolk Island", "Northern Mariana Islands", "Norway", "Oman", "Pakistan", "Palau", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines", "Pitcairn", "Poland", "Portugal", "Puerto Rico", "Qatar", "Reunion", "Romania", "Russian Federation", "Rwanda", "Saint Kitts and Nevis", "Saint Lucia", "Saint Vincent and the Grenadines", "Samoa", "San Marino", "Sao Tome and Principe", "Saudi Arabia", "Senegal", "Seychelles", "Sierra Leone", "Singapore", "Slovakia (Slovak Republic)", "Slovenia", "Solomon Islands", "Somalia", "South Africa", "South Georgia and the South Sandwich Islands", "Spain", "Sri Lanka", "St. Helena", "St. Pierre and Miquelon", "Sudan", "Suriname", "Svalbard and Jan Mayen Islands", "Swaziland", "Sweden", "Switzerland", "Syrian Arab Republic", "Taiwan, Province of China", "Tajikistan", "Tanzania, United Republic of", "Thailand", "Togo", "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey", "Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Uganda", "Ukraine", "United Arab Emirates", "United Kingdom", "United States", "United States Minor Outlying Islands", "Uruguay", "Uzbekistan", "Vanuatu", "Venezuela", "Vietnam", "Virgin Islands (British)", "Virgin Islands (U.S.)", "Wallis and Futuna Islands", "Western Sahara", "Yemen", "Yugoslavia", "Zambia", "Zimbabwe");

    ?>

A: You can not execute php code in html file.So, make form.html file extension to form.php
and pass a get parameter while you redirecting to form.php from process.php if error occurs.
check that if get parameter available in form.php then render the message.
       if($arrmessage =="")
        {
            $student_name = $_POST['student_name'];
            $email = $_POST['email'];
            $contact_number = $_POST['contact_number'];
            $gender = $_POST['gender'];
            $interest = $_POST['interest'];
            $checked ="";
            foreach($interest as $list){$checked .= $list .",";}
            $DOB = $_POST['day'].'-'.$_POST['month'].'-'.$_POST['year'];
            $street_adress = $_POST['street_adress'];
            $city = $_POST['city'];
            $state = $_POST['state'];
            $country = $_POST['country'];

    $sql = "INSERT INTO form (student_name,email,contact_number,gender,interest,DOB,street_adress,city,state,country)VALUES('{$student_name}','{$email}','{$contact_number}','{$gender}','{$checked}','{$DOB}','{$street_adress}','{$city}','{$state}','{$country}')";
        mysql_query($sql);
        if(mysql_insert_id() != ""){
                echo "Records inserted successfully.";
                }
                header("Location:views.php");
                exit;
         } else {
                 header("Location:form.php?error=1&msg=$arrmessage");
         }

At form.php file you need to check that get if $_GET['error'] then display the message you get in $_GET['msg']


text:
Q: how to clear error How to clear the following error:

Only one instance of a ScriptManager
  can be added to the page.
  Description: An unhandled exception
  occurred during the execution of the
  current web request. Please review the
  stack trace for more information about
  the error and where it originated in
  the code.
Exception Details:
  System.InvalidOperationException: Only
  one instance of a ScriptManager can be
  added to the page.
Source Error:  An unhandled exception
  was generated during the execution of
  the current web request.
  Information regarding the origin and
  location of the exception can be
  identified using the exception stack
  trace below.

The following is my html Markup:
<%@ Page Language="C#" AutoEventWireup="true" MasterPageFile="~/MasterPage.master"
    CodeFile="ManualReport.aspx.cs" Inherits="ManualReport" %>
<%@ Register assembly="Telerik.Web.UI" namespace="Telerik.Web.UI"
    tagprefix="telerik" %>

<asp:Content  ContentPlaceHolderID="ContentPlaceHolder1" runat="server"
    ID="ContentPlaceHolder1">

<%@ Register Assembly="Microsoft.ReportViewer.WebForms, Version=9.0.0.0,
    Culture=neutral,   PublicKeyToken=b03f5f7f11d50a3a"
    Namespace="Microsoft.Reporting.WebForms" TagPrefix="rsweb" %>

<form id="mainform" runat="server">

    <asp:ScriptManager ID="ScriptManager2" runat="server">
    </asp:ScriptManager>

    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>

</form>

Customer Name
        <asp:RadioButton ID="rdbcustomerAll" runat="server"  Visible ="false"
 GroupName="CustomerValidation"
                 Text="All" Checked="false" />
             <asp:RadioButton ID="rdbcustomerSpecific" runat="server"
  GroupName="CustomerValidation" Visible="false" Text="Spec" Checked="true" />
                     <asp:DropDownList ID="cmbName" runat="server">
                     </asp:DropDownList>

Date	<asp:RadioButton ID="rdbDateAll" runat="server"
  Visible ="false" GroupName="DateValidation"
                 Text="All"  />
             <asp:RadioButton ID="rdbDateSpec" runat="server" Visible ="false" Checked="true" GroupName="DateValidation" Text="Spec" />
        <telerik:RadDatePicker ID="rdpDate" runat="server" xmlns:telerik="telerik.web.ui">
                              </telerik:RadDatePicker>

A: ScriptManager is a server side component and it has to be placed inside a form tag. Only one ScriptManager component must be added per page. In your case, you have provided two ScriptManager components. Therefor, you have to remove one of them, the ScriptManager which resides outside the form.

A: You have two script managers in the page:
<asp:ScriptManager ID="ScriptManager2" runat="server">
  </asp:ScriptManager>

and
 <asp:ScriptManager ID="ScriptManager1" runat="server">
  </asp:ScriptManager>

Per the description of the error, you have to remove one. You may only have one.

A: Why did you add the ScriptManager two times on your page? You can only add one, and that's what the error says. Only one ScriptManager instance is allowed per page.
Please remove the ScriptManager2 and it will work for you.
Secondly ScriptManger should be under Form Tag. like..
<form id="mainform" runat="server">

  <asp:ScriptManager ID="ScriptManager1" runat="server">
  </asp:ScriptManager>

</form>

A: Aside from the answers the others have already give, which are 100% correct, you are also closing your "form" too early...
<form id="mainform" runat="server"></form>

Move the closing "form" tag to AFTER all your Server side ASP.NET controls, ensuring your HTML remains valid... (difficult to know exactly where to without seeing your full markup, but I would guess close to the closing Content tag : /asp:Content)
EDIT: Actually, also worth pointing out that because you are using a master page here, you probably already have a server side form inside your master page... You cannot then have a second form inside the aspx child page aswell.  I would suggest maybe putting your Single Script manager into your master page, inside the form tag, as the others have pointed out, and removing all references to script manager and "form" from the child (aspx) page) ?
HTH.
Dave