text:
Q: Create dynamic CSS style from string with Angular items When using dynamic class with property "Style". Including for example item.Style="color: red"
it is working fine.
But Visual Studio code throws error } expectedcss(css-rcurlyexpected) or similar.
Result is correct but Designer does not work:

The label-result is 'red' in my case but how to avoid the syntax errors?

Error: ERROR Error: Cannot find a differ supporting object 'color: #DFFDD00;'

A: ngStyle needs key + value as object. In that case a dictionary is needed. Try my style string to dictionary parser.
You can use it like default css and use all known basic CSS- Syntax.
Example for item.Style
background-color:blue;font-size: 22px;color:red;

Angular

Hello World

TypeScript
private setStyle(value: string): unknown {
    console.log(value);
    if (value == "") return null;
    //Example: value = "background-color:blue";
    var properties = value.split(";");
    var keyValuePairs = {};
    properties.forEach(o => {
      var key = String(o.split(":")[0]).trim();
      var value = String(o.split(":")[1]).trim();
      if (key.length > 0) {
        keyValuePairs[key] = value;
      }
    })
    console.log("keyValuePairs: " + JSON.stringify(keyValuePairs));
    return keyValuePairs;
  }

Result

A: Update: You can use pipe and attr.style binding for this
(Which would also scale well through your entire app):

*

*Create a pipe as sanitizer

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl } from '@angular/platform-browser';

@Pipe({
  name: 'safe'
})
export class SafePipe implements PipeTransform {

  constructor(protected sanitizer: DomSanitizer) {}

 public transform(value: any, type: string): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl {
    switch (type) {
            case 'html': return this.sanitizer.bypassSecurityTrustHtml(value);
            case 'style': return this.sanitizer.bypassSecurityTrustStyle(value);
            case 'script': return this.sanitizer.bypassSecurityTrustScript(value);
            case 'url': return this.sanitizer.bypassSecurityTrustUrl(value);
            case 'resourceUrl': return this.sanitizer.bypassSecurityTrustResourceUrl(value);
            default: throw new Error(`Invalid safe type specified: ${type}`);
        }
  }
}

*Register the pipe within your module

@NgModule({
  declarations: [SafePipe],
})
export class AppModule {}

*Use it everywhere...

app.component.html

{{key.Style}}

app.component.ts
export class AppComponent {
  key = {Style: "background-color:blue;font-size: 22px;color:red;"};
}

Result:

Demo: https://stackblitz.com/edit/angular-playground-iodcgy?file=app%2Fapp.component.ts
References:

*

*https://angular.io/api/platform-browser/DomSanitizer

*https://medium.com/@swarnakishore/angular-safe-pipe-implementation-to-bypass-domsanitizer-stripping-out-content-c1bf0f1cc36b

*https://ultimatecourses.com/blog/angular-pipes-custom-pipes

The value for the [ngStyle] must be key-value pairs or an expression that returns key-value pairs.
You can use both style and [ngStyle] respectively. Angular would then merge them, e.g.:
key = {Style: { 'font-size': '18px' }}

result:

Demo: https://stackblitz.com/edit/angular-playground-jd2g2t?file=app/app.component.html

A: This should fix it:
[ngStyle]="'color: #000000; ' + key.Style"


text:
Q: WebpackOptionsValidationError: Invalid configuration object. I cant deploy my server to try my bundle I have runned the webpack --mode production to build the dist folder, but it is showing this error when i run the server, the app is running on the developer mode.
I got this error:

C:\Users\Bymet\Documents\Gestor de Inventario\frontend-admin\node_modules\webpack\lib\webpack.js:31
throw new WebpackOptionsValidationError(webpackOptionsValidationErrors);
^

WebpackOptionsValidationError: Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.

*

*configuration should be an object.

and next something like this:

validationErrors: [
{
keyword: 'type',
dataPath: '',
schemaPath: '#/type',
params: { type: 'object' },
message: 'should be object',
schema: 'object',
parentSchema: {
definitions: {
ArrayOfStringOrStringArrayValues: { type: 'array', items: [Object] },
ArrayOfStringValues: { type: 'array', items: [Object] },
Entry: { anyOf: [Array] },
EntryDynamic: {
description: 'A Function returning an entry object, an entry string, an entry array or a promise to these things.',
instanceof: 'Function',
tsType: '(() => EntryStatic | Promise)'

I have changed the dotenv to the dependencies to deploit on heroku but it "work"
here is my server and my webpack config
import express from 'express';
import webpack from 'webpack';
import { env, port } from '../../config';

const app = express();

if (env === 'development') {
    // console.log('Development config');
    const webpackConfig = require('../../webpack.config');
    const webpackDevMiddleware = require('webpack-dev-middleware')
    const webpackHotMiddleware = require('webpack-hot-middleware');
    const compiler = webpack(webpackConfig);
    const serverConfig = { port: port, hot: true };

    app.use(webpackDevMiddleware(compiler, serverConfig));
    app.use(webpackHotMiddleware(compiler));
}

app.get('*', (req, res) => {
    res.send(`
    <!DOCTYPE html>

                <link rel="stylesheet" href="assets/app.css" type="text/css">
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                    <title>Cestina | Administración </title>

    `)
})

app.listen(port, () => {
    console.log(`The server is running on the route http://localhost:${config.port}`)
})

const path = require('path');
const webpack = require('webpack');
const MINICssExtractPlugin = require('mini-css-extract-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
// const dotenv = require('dotenv');
const { port, host_name, env} = require('./config');

module.exports = () => {
     /* This configuracion give access to the actions and other react component access to the .env variables */
    const envi = env;
    const envKeys = Object.keys(envi).reduce((prev, next) => {
        prev[`process.env.${next}`] = JSON.stringify(envi[next]);
        return prev;
    }, {});

    return {
        entry: ['./src/front/index.js', `webpack-hot-middleware/client?path=${host_name}/__webpack_hmr&reload=true'`],
        context: path.resolve(__dirname),
        output: {
            path: path.resolve(__dirname, 'dist'),
            filename: 'bundle.js'
        },
        node: {
            fs: "empty"
        },
        module: {
            rules: [
                {
                    test: /\.(js|jsx)$/,
                    exclude: /node_modules/,
                    use: {
                        loader: 'babel-loader'
                    }
                },
                {
                    test: /\.(css|scss)$/,
                    use: [
                        {
                            loader: MINICssExtractPlugin.loader
                        },
                        // 'style-loader',
                        'css-loader',
                        'sass-loader'
                    ]
                },
                {
                    test: /\.html$/,
                    use: [
                        {
                            loader: 'html-loader',
                        }
                    ]
                },
                {
                    test: /\.(png|gif|jpg)$/,
                    use: [
                        {
                            'loader': 'file-loader',
                            options: {
                                name: 'assets/[hash].[ext]'
                            }
                        }
                    ]
                }
            ]
        },
        resolve: {
            extensions: ['.js', '.jsx']
        },
        devServer: {
            historyApiFallback: true,
            hot: true,
            port: port,
            headers: {
                "Access-Control-Allow-Origin": "*",
                "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
                "Access-Control-Allow-Headers": "X-Requested-With, content-type, Authorization"
            }
        },
        plugins: [
            new webpack.DefinePlugin(envKeys),
            new webpack.HotModuleReplacementPlugin(),
            new MINICssExtractPlugin({
                filename: 'assets/app.css'
            }),
            new HtmlWebpackPlugin({
                template: "./public/index.html",
                filename: "index.html",
            })
        ]
    }
};

A: It looks like you're exporting a function to create the configuration object which means you have to call it first before passing to webpack:

const webpackConfig = require('../../webpack.config')(); // call it before passing

redpajama_set_name: RedPajamaStackExchange


text:
Q: Remove right margin off one element in HTML/CSS List Navigation I am trying to get the gray buttons at the top of this page to all fit across the top (in line with the body), rather than on two lines: http://www.nbm.org/test/nbm-online-drafts/dropdown-testing.html
I have it set up as a list:

Buy Tickets

Hours & Admission

Accessibility & Directions

Tours

Current Exhibitions

Upcoming Exhibitions

Buy Tickets

Collections

Upcoming Programs

Spotlight on Design

Watch / Listen

Continuing Education Credits

Festivals

Everyday Activities

Teens & Young Adults

Summer Camp

Scouts & Youth Groups

Birthday Parties

For Educators

For Teens & Young Adults

Plan a School Visit

Donate Now

Membership

Corporate Giving

Awards & Honors

Volunteer

Books

Home

Toys

Museum

Stationery

Fashion

Design

About the Museum

E-newsletters

Press Room

Staff & Governance

Employment & Internships

I want to keep the li right margin at 4px, but that pushes the "About Us" button to a second line. Changing the li right margin to 3px is too little and the buttons do not line up with the body on the right.
CSS:
#main-nav {
    background: none repeat scroll 0 0 white;
    height: 53px;
    left: 0;
    position: relative;
    top: 128px;
    width: 100%;
    z-index: 11;
}
#main-nav .subnav {
    background: none repeat scroll 0 0 #D7D6D4;
    border: 0 solid #D4D5D6;
    display: none;
    left: 0;
    list-style-type: none;
    margin: 0;
    padding: 0;
    position: absolute;
    top: 49px;
    width: 109px;
    z-index: 11;
}
#main-nav .subnav li {
    border-bottom: 1px solid #EEEEEE;
    display: block;
    margin: 0;
}
#main-nav .subnav li a {
    color: #000000;
    font-size: 11px;
    height: 18px;
    padding: 6px 4px 19px;
    width: 101px;
}
#main-nav .subnav li a:hover {
    background: none repeat scroll 0 0 #BFBEBA;
    width: 101px;
}
#nav-primary {
    float: left;
    list-style-type: none;
    margin: 0;
    padding: 0;
}
#nav-primary li {
    float: left;
    margin-right: 4px;
    position: relative;
}
#nav-primary li a {
    color: #000000;
    float: left;
    font-size: 13px;
    font-weight: bold;
    height: 48px;
    line-height: 16px;
    text-align: center;
    text-decoration: none;
    width: 109px;
}
#nav-primary li a:hover {
    text-decoration: none;
}
#nav-primary li:hover .subnav {
    display: block;
}

Is it possible to remove the right margin on the last li element? Or to hide it?
Any ideas are much appreciated!

A: It is this simple:
#nav-primary > li:last-child
{
    margin-right:0;
}


text:
Q: Jquery Ajax POST function not working successfully I'm using validation thing on button click event with jQuery Ajax. This method shows an alert message if return value is 1, else return true and go to button method.
That validation and alert showing thing and block button method is working fine. If not want to do anything and return true to hit the button method is not working.
This is my jQuery ajax method.
$(function () {
    $('#customerSubmit').on('click', function (event) {

        debugger;
        event.preventDefault();
        var title = $('#Title').val();
        var firstName = $('#FirstName').val();
        var phoneNo1 = $('#PhoneNo1').val();
        var Email = $('#Email').val();
        var address1 = $('#AddressLine1').val();

        $.ajax({
            type: 'POST',
            url: '/Customer/IsExistCustomer',
            data: { FirstName: firstName, Title: title, PhoneNo1: phoneNo1, AddressLine1: address1, Email: Email },
            success: function (data) {
                if (data == 1) {
                    alert('This Customer Already Exist');
                    return false;
                }
                else {
                    return true;
                }
            }
        });
    });
});

Please help me to sort out this,
Thanks.

A: You can't synchronously return from an asynchronous action.
Here's a good QA on the general problem : How do I return the response from an asynchronous call?
For your specific problem, you should use a button instead of a submit element and do the action (submit the form) in the callback :
$(function () {
    $('#customerSubmit').on('click', function (event) {
        var form = this.form; // <- depends on your DOM
        var title = $('#Title').val();
        var firstName = $('#FirstName').val();
        var phoneNo1 = $('#PhoneNo1').val();
        var Email = $('#Email').val();
        var address1 = $('#AddressLine1').val();
        $.ajax({
            type: 'POST',
            url: '/Customer/IsExistCustomer',
            data: { FirstName: firstName, Title: title, PhoneNo1: phoneNo1, AddressLine1: address1, Email: Email },
            success: function (data) {
                if (data == 1) {
                    alert('This Customer Already Exist');
                }
                else {
                    form.submit(); // <- now submit the form
                }
            }
        });
    });
});

A: A few issues in your code:

*

*You're trying to return a value from an asynchronous function. When 'success' is called, the function that initiated the ajax call is already terminated.

*if you handle the click on a button, the user can still submit the form by typing the ENTER/RETURN key in an <input> field. You should handle the form's 'submit' event instead.

IMHO, You should intercept the 'submit' event handler, preventDefault(), and do an ajax call to submit your form, and handle the errors to give some kind of feedback to the user.
If you absolutely want to do two requests to the server instead of one (one to check, and one to submit), you can do a second ajax call in the 'success' handler:
    $.ajax({
        type: 'POST',
        url: '/Customer/IsExistCustomer',
        data: { FirstName: firstName, Title: title, PhoneNo1: phoneNo1, AddressLine1: address1, Email: Email },
        success: function (data) {
            if (data !== 1) {
                $.ajax({
                    type: $(form).attr("method"),
                    url: $(form).attr("action"),
                    data: $(form).serialize(),
                    success: function (data) {

                    }
                });
            }
        }
    });


text:
Q: comparing multiple tab delimited csv files in python As a start, I want to compare the first two columns of two .csv files then write what is common in these files to an output file, say common.csv, then also write the differences in each file to different output files, say f1.csv and f4.csv.
So far I have tried to using set(), difflib, and also taking the two files, create lists from the files then comparing the first two columns in each file. This gave me the output for what is common but not for what the differences are in each file when compared to each other. I have tried most of the solutions posted that seemed like the problem was similar to mine but I am still stuck. Can someone please assist?
this is the headers in my files and only want to compare the first two columns but write out the entire line to the output file.
fieldnames = (["Chromosome" ,"GenomicPosition", "ReferenceBase",
               "AlternateBase", "GeneName", "GeneID",
               "TrancriptID",   "Varianteffect-Variantimpact",
               "Biotype",   "TranscriptBiotype" ,   "Referencebase",
               "Alternatebase", "Depth coverage"])

A: One solution is to use pandas, which is very powerful.
To convert csv <-> pandas dataframes:
 import pandas as pd
 df = pd.read_csv('csv_file.csv') # csv -> pandas
 df.to_csv('csv_file.csv', index=False) # pandas -> csv

To compare pandas dataframes on columns, this post should point you in the right direction: https://stackoverflow.com/a/47107164/2667536


text:
Q: Got some problems with CLISP's nested list and lambda expression Nested lists in Common Lisp really confused me.  Here is the problem:
By using recursion, let (nested-list 'b '(a (b c) d)) return t
  if the first argument appears in the second argument (which could be
  a nested list), and nil otherwise.
I tried find, but it only works if the first argument is '(b c).
I turned my eyes on lambda expressions.  I want to flatten the second
argument first, and then use eq to compare the arguments.
(defun nested-list (x y)
  (cond
    ((null y) ())
    (t (append (lambda (flatten) (first y))

Then I got stuck.  Even though I read a lot of stuff about lambda
expessions, it still confused me.  I do not know how to recall it when
I need, I knew the funcall function, but you know I just cannot get
it.  I just learnt Common Lisp for 5 days, so I hope you can give me a
hint.  Thanks a lot!

A: First of all unless you mistyped if instead of iff the problem is quite trivial, just return t and you're done :-)
Seriously speaking instead when you need to solve a problem using recursion the idea often is simply:

*

*if we're in a trivial case just return the answer

*otherwise the answer is the same answer we'd get by solving a problem that it's just a little bit simpler that this, and we call ourself to solve this simplified version.

In the specific consider:

*

*If the second argument is an empty list the answer is NIL

*If the first argument is equal to the first element of the second argument then just return T instead

*Otherwise if the first element of the second list is a list (therefore also possibly a nested list) and the element is contained in this multilist then return true (to check this case the function is calling itself)

*Otherwise just check the same problem, but first dropping the first element of the second argument, because it has been checked (this also calls recursively the same function)

So basically 1 and 2 are the trivial cases; 3 and 4 are the cases in which you solve a simpler version of the problem.


text:
Q: Debian 11 issue with locale: No such file or directory The problem I encounter with Debian bullseye (v11):
If I execute locale -a, I get the following output:
locale: Cannot set LC_CTYPE to default locale: No such file or directory
locale: Cannot set LC_MESSAGES to default locale: No such file or directory
locale: Cannot set LC_COLLATE to default locale: No such file or directory
C
C.UTF-8
POSIX
aa_DJ
aa_DJ.iso88591
aa_DJ.utf8
aa_ER
aa_ER.utf8
...
zh_TW
zh_TW.big5
zh_TW.euctw
zh_TW.utf8
zu_ZA
zu_ZA.iso88591
zu_ZA.utf8

Also, if I try to use tlmgr (package manager for LateX), I get the following:
perl: warning: Setting locale failed.
perl: warning: Please check that your locale settings:
        LANGUAGE = "en_US:fr:en_GB",
        LC_ALL = "en-US.UTF-8",
        LC_MESSAGES = "en_US.UTF-8",
        LC_CTYPE = "en_US.UTF-8",
        LC_COLLATE = "en_US.UTF-8",
        LANG = "fr_FR.UTF-8"
    are supported and installed on your system.
perl: warning: Falling back to a fallback locale ("fr_FR.UTF-8").
tlmgr: no action given; try --help if you need it.

I searched the issue, and tried the following:

*

*dpkg-reconfigure locales and selecting only used locales (fr utf8, en-us utf8 and en-gb utf8)

*dpkg-reconfigure locales and selecting all locales (as you can see above)

*locale-gen

*restarting the PC with each change

*editing /etc/default/locale

More information
cat /etc/default/locale gives:
#  File generated by update-locale
LANG=en_US.UTF-8
LANGUAGE=en_US.UTF-8
LC_ALL=en_US.UTF-8
LC_CTYPE=en_US.UTF-8
LC_MESSAGES=en_US.UTF-8
LC_COLLATE=en_US.UTF-8

ls /usr/share/locale/en gives:
LC_MESSAGES

ls /usr/share/locale/en/LC_MESSAGES gives:
accounts-service.mo  gtk30-properties.mo  iso_3166-2.mo  kcoreaddons5_qt.qm  kwidgetsaddons5_qt.qm
cups-pk-helper.mo    gtk30.mo

Questions

*

*Should I reconfigure locales and only select used locales?

*The error message says that it expects file/folder that does not exist. Where should this file/folder be located? in /usr/share/locale/en?

*How to solve this issue (non-blocking, because all applications seem to work, but annoying)?

If you have suggestions for documentations to read to dive deeper on this issue I'm also all hear.
Thank you.
Edits
Questions from @StéphaneChazelas
Output of locale
locale: Cannot set LC_CTYPE to default locale: No such file or directory
locale: Cannot set LC_MESSAGES to default locale: No such file or directory
locale: Cannot set LC_ALL to default locale: No such file or directory
LANG=fr_FR.UTF-8
LANGUAGE=en_US:fr:en_GB
LC_CTYPE="en-US.UTF-8"
LC_NUMERIC="en-US.UTF-8"
LC_TIME="en-US.UTF-8"
LC_COLLATE="en-US.UTF-8"
LC_MONETARY="en-US.UTF-8"
LC_MESSAGES="en-US.UTF-8"
LC_PAPER="en-US.UTF-8"
LC_NAME="en-US.UTF-8"
LC_ADDRESS="en-US.UTF-8"
LC_TELEPHONE="en-US.UTF-8"
LC_MEASUREMENT="en-US.UTF-8"
LC_IDENTIFICATION="en-US.UTF-8"
LC_ALL=en-US.UTF-8

Output of strace locale 2>&1 | grep ENOENT:
access("/etc/ld.so.preload", R_OK)      = -1 ENOENT (No such file or directory)
openat(AT_FDCWD, "/usr/lib/locale/en-US.UTF-8/LC_CTYPE", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)
openat(AT_FDCWD, "/usr/lib/locale/en-US.utf8/LC_CTYPE", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)
openat(AT_FDCWD, "/usr/lib/locale/en-US/LC_CTYPE", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)
openat(AT_FDCWD, "/usr/lib/locale/en-US.UTF-8/LC_MESSAGES", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)
openat(AT_FDCWD, "/usr/lib/locale/en-US.utf8/LC_MESSAGES", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)
openat(AT_FDCWD, "/usr/lib/locale/en-US/LC_MESSAGES", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)
openat(AT_FDCWD, "/usr/lib/locale/en-US.UTF-8/LC_IDENTIFICATION", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)
openat(AT_FDCWD, "/usr/lib/locale/en-US.utf8/LC_IDENTIFICATION", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)
openat(AT_FDCWD, "/usr/lib/locale/en-US/LC_IDENTIFICATION", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)

ls /usr/lib/locale gives:
C.UTF-8
locale-archive

Strange dpkg-reconfigure locales output
If I'm not wrong, dpkg-reconfigure locales should list locales and say for each of them "up to date" if already generated. But in my case, it re-process each locale and says "done":
perl: warning: Setting locale failed.
perl: warning: Please check that your locale settings:
  LANGUAGE = "en_US:fr:en_GB",
  LC_ALL = "en-US.UTF-8",
  LC_MESSAGES = "en_US.UTF-8",
  LC_CTYPE = "en_US.UTF-8",
  LC_COLLATE = "en_US.UTF-8",
  LANG = "fr_FR.UTF-8"
    are supported and installed on your system.
perl: warning: Falling back to a fallback locale ("fr_FR.UTF-8").
locale: Cannot set LC_CTYPE to default locale: No such file or directory
locale: Cannot set LC_MESSAGES to default locale: No such file or directory
locale: Cannot set LC_ALL to default locale: No such file or directory
/usr/bin/locale: Cannot set LC_CTYPE to default locale: No such file or directory
/usr/bin/locale: Cannot set LC_MESSAGES to default locale: No such file or directory
/usr/bin/locale: Cannot set LC_ALL to default locale: No such file or directory
Generating locales (this might take a while)...
  aa_DJ.UTF-8... done
  aa_DJ.ISO-8859-1... done
  aa_ER.UTF-8... done
  aa_ER.UTF-8@saaho... done
  aa_ET.UTF-8... done
  af_ZA.UTF-8... done
  af_ZA.ISO-8859-1... done
  agr_PE.UTF-8... done
  ak_GH.UTF-8... done
  am_ET.UTF-8... done
  an_ES.UTF-8... done
  an_ES.ISO-8859-15... done
  anp_IN.UTF-8... done
  ar_AE.UTF-8... done
  ar_AE.ISO-8859-6... done
  ar_BH.UTF-8... done
  ar_BH.ISO-8859-6... done
  ar_DZ.UTF-8... done
  ar_DZ.ISO-8859-6... done
  ar_EG.UTF-8... done
  ar_EG.ISO-8859-6... done
  ar_IN.UTF-8... done
  ar_IQ.UTF-8... done
  ...

Question by @K-att-
dpkg -l | grep "language-pack" does not return anything.
Question from @ThatsWhatSheCoded
sudo apt-get install -y locales locales-all:
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
locales is already the newest version (2.31-13+deb11u2).
The following NEW packages will be installed:
  locales-all
0 upgraded, 1 newly installed, 0 to remove and 1 not upgraded.
Need to get 10.8 MB of archives.
After this operation, 227 MB of additional disk space will be used.
Get:1 http://deb.debian.org/debian bullseye/main amd64 locales-all amd64 2.31-13+deb11u2 [10.8 MB]
Fetched 10.8 MB in 21s (515 kB/s)
apt-listchanges: Can't set locale; make sure $LC_* and $LANG are correct!
perl: warning: Setting locale failed.
perl: warning: Please check that your locale settings:
        LANGUAGE = "en_GB:en_US:fr",
        LC_ALL = "en-US.UTF-8",
        LC_CTYPE = "en_US.UTF-8",
        LC_COLLATE = "en_US.UTF-8",
        LC_MESSAGES = "en_US.UTF-8",
        LANG = "fr_FR.UTF-8"
    are supported and installed on your system.
perl: warning: Falling back to a fallback locale ("fr_FR.UTF-8").
locale: Cannot set LC_CTYPE to default locale: No such file or directory
locale: Cannot set LC_MESSAGES to default locale: No such file or directory
locale: Cannot set LC_ALL to default locale: No such file or directory
Selecting previously unselected package locales-all.
(Reading database ... 182206 files and directories currently installed.)
Preparing to unpack .../locales-all_2.31-13+deb11u2_amd64.deb ...
Unpacking locales-all (2.31-13+deb11u2) ...
Setting up locales-all (2.31-13+deb11u2) ...

After restarting, locale -a still gives:
locale: Cannot set LC_CTYPE to default locale: No such file or directory
locale: Cannot set LC_MESSAGES to default locale: No such file or directory
locale: Cannot set LC_COLLATE to default locale: No such file or directory
...

Print of env after reinstalling locales
Executed: sudo apt-get remove locale, then sudo apt-get install -y locales and then env:
SHELL=/bin/bash
WINDOWID=79691783
QT_ACCESSIBILITY=1
KDED_STARTED_BY_KDEINIT=1
COLORTERM=truecolor
XDG_SESSION_PATH=/org/freedesktop/DisplayManager/Session1
LANGUAGE=en_GB:en_US:fr
SSH_AUTH_SOCK=/tmp/ssh-eAB2uCmvHnDY/agent.872
SHELL_SESSION_ID=08a2a2b1e969432881e34e2775568d69
DESKTOP_SESSION=plasma
SSH_AGENT_PID=911
GTK_RC_FILES=/etc/gtk/gtkrc:/home/nkoniishvt/.gtkrc:/home/nkoniishvt/.config/gtkrc
XCURSOR_SIZE=24
GTK_MODULES=gail:atk-bridge
XDG_SEAT=seat0
PWD=/home/nkoniishvt
XDG_SESSION_DESKTOP=KDE
LOGNAME=nkoniishvt
XDG_SESSION_TYPE=x11
GPG_AGENT_INFO=/run/user/1000/gnupg/S.gpg-agent:0:1
XAUTHORITY=/home/nkoniishvt/.Xauthority
GTK2_RC_FILES=/etc/gtk-2.0/gtkrc:/home/nkoniishvt/.gtkrc-2.0:/home/nkoniishvt/.config/gtkrc-2.0
HOME=/home/nkoniishvt
LANG=fr_FR.UTF-8
LS_COLORS=rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=00:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.zst=01;31:*.tzst=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.wim=01;31:*.swm=01;31:*.dwm=01;31:*.esd=01;31:*.jpg=01;35:*.jpeg=01;35:*.mjpg=01;35:*.mjpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.webp=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=00;36:*.au=00;36:*.flac=00;36:*.m4a=00;36:*.mid=00;36:*.midi=00;36:*.mka=00;36:*.mp3=00;36:*.mpc=00;36:*.ogg=00;36:*.ra=00;36:*.wav=00;36:*.oga=00;36:*.opus=00;36:*.spx=00;36:*.xspf=00;36:
XDG_CURRENT_DESKTOP=KDE
KONSOLE_DBUS_SERVICE=:1.63
KONSOLE_DBUS_SESSION=/Sessions/1
PROFILEHOME=
XDG_SEAT_PATH=/org/freedesktop/DisplayManager/Seat0
KONSOLE_VERSION=201203
KDE_SESSION_UID=1000
XDG_SESSION_CLASS=user
TERM=xterm-256color
USER=nkoniishvt
COLORFGBG=15;0
KDE_SESSION_VERSION=5
PAM_KWALLET5_LOGIN=/run/user/1000/kwallet5.socket
DISPLAY=:0
SHLVL=1
LC_MESSAGES=en_US.UTF-8
XDG_VTNR=7
XDG_SESSION_ID=3
LC_CTYPE=en_US.UTF-8
XDG_RUNTIME_DIR=/run/user/1000
LC_ALL=en-US.UTF-8
QT_AUTO_SCREEN_SCALE_FACTOR=0
LC_COLLATE=en_US.UTF-8
XCURSOR_THEME=breeze_cursors
KDE_FULL_SESSION=true
PATH=/home/nkoniishvt/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games
DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus
KDE_APPLICATIONS_AS_SCOPE=1
KONSOLE_DBUS_WINDOW=/Windows/1
_=/usr/bin/env

A: Remove export LANGUAGE=en_GB:en_US:fr from your.bashrc then run dpkg-reconfigure locales.


text:
Q: How to automatically "live" synchronize a single file in one direction How can I use a script to automatically and immediately update the backup of a single file?

A: You can create an script (or even an alias) to copy the file before edit it using command cp and --backup=t like this
cp --backup=t /path/to/file /path/to/backup.txt

to get each time a backup of the file.
If you want everything inside one file named backup.txt you should use
cat /path/to/file >> /path/to/backup.txt

to attach the current file to backup.txt


text:
Q: How to use result of NDSolve within a module? I want to numerically solve a differential equation and use the resulting interpolating function for further calculations:
a = 5;
s = First@NDSolve[{f''[x] == a, f'[0] == 0, f[0] == 0}, f[x], {x, 0, 1}];
g[x_] = D[f[x] /. s, x];
g[0.5]

(Obviously this is not my actual code but a minimal example that shows my problem.)
The code like this correctly displays the result 2.5.
However, if I put the same code inside a module:
test[var_] := Module[{a, s, g}, a = 5;
s = First@NDSolve[{f''[x] == a, f'[0] == 0, f[0] == 0}, f[x], {x, 0, 1}];
g[x_] = D[f[x] /. s, x];
g[0.5]]

The output is
test[1]
f'[0.5]

What am I doing wrong? How do I use the result of NDSolve properly within a module?
(I suspect this question has been asked before, but I don't really know what to search for.)

Thanks to yarchik's answer I figured that simply replacing f for f[x] in the second argument of NDSolve fixes the issue. A shorter solution based on NDSolveValue would be
test[var_] := Module[{a, s, f}, a = 5;
f = NDSolveValue[{f''[x] == a, f'[0] == 0, f[0] == 0}, f, {x, 0, 1}];
f'[0.5]]

A: I am confident there will be some answers explaining what is wrong with your approach. In the meantime I would like to suggest a different way to deal with your problem. Namely, you are solving a second-order ODE and differentiating the result. One can reformulate this ODE as a system of 1st-order ODEs and get the derivative directly.
test[] := Module[{a, gg, f, g},
  a = 5.;
  gg = NDSolveValue[{g'[x] == a, f'[x] == g[x], g[0.] == 0., f[0.] == 0.},
     g, {x, 0., 1.}];
  gg[0.5]
  ]

Now check this out
 test[]
 (* 2.5 *)


text:
Q: Why does $(x^n)^{x^n} = a^a$ imply $x^n = a$? I came across a problem using a property of exponents that I was not aware of. In one of the steps, an equation was simplified to this equality:
$$(x^5)^{x^5}=10^{10}$$
Knowing the solution, the above equation was simplified to:
$$x^5=10$$
What property is being used here to determine this simplification? I understand that given an equation of the form $$x^n = x^m$$ implies $$n = m$$
So, how can one determine that $$(x^n)^{x^n} = a^a$$ implies $$x^n = a$$?
Thank you.

A: Let $x^5=y$.
Thus, since $f(y)=y^y$ increases on $\left[\frac{1}{e},+\infty\right)$ and for $0<y<1$ our equation has no roots, we obtain $x^5=10$ and $x=\sqrt[5]{10}.$

A: The general claim in the title is not true.
In the first place, $x^n$ is any non-negative real, and you can as well reason on
$$b^b=a^a.$$
A counterexample is
$$\frac12^{1/2}=\frac14^{1/4}.$$

A: $\require{begingroup} \begingroup$
$\def\e{\mathrm{e}}\def\W{\operatorname{W}}\def\Wp{\operatorname{W_0}}\def\Wm{\operatorname{W_{-1}}}\def\Catalan{\mathsf{Catalan}}$
Consider more general form
\begin{align}
z^z&=a^a
\tag{1}\label{1}
,
\end{align}
which is equivalent to
\begin{align}
z\ln(z)&=a\ln(a)
\tag{2}\label{2}
\\
\text{or }\quad
\ln(z)\exp(\ln(z))
&=
\ln(a)\exp(\ln(a))
\tag{3}\label{3}
\quad\text{for } a>0
.
\end{align}
Clearly, \eqref{3} is
in a form $u\exp u=v\exp v$,
just a textbook equation
to solve in terms of the Lambert $\W$ function:
\begin{align}
\W\left(\ln (z)\exp(\ln (z))\right)
&=
\W\left(\ln (a)\exp(\ln(a))\right)
\tag{4}\label{4}
\\
\ln(z)&=\W\left(\ln(a)\exp(\ln(a))\right)
\tag{5}\label{5}
,\\
z&=\exp\left(\W\left(\ln(a)\exp(\ln(a))\right)\right)
\tag{6}\label{6}
.
\end{align}
The number of real solutions of \eqref{5} (and hence \eqref{1})
depends on the argument $u=\ln(a)\exp(\ln(a))$ of $\W$ on the right-hand side.
If $u>0$ or in other words, if $a>1$, as in the OP,
then there is just one solution
\begin{align}
z&=
\exp\left(\W\left(\ln(a)\exp(\ln(a))\right)\right)
=\exp(\ln(a))=a
\tag{7}\label{7}
.
\end{align}
But if $u<0$ or in other words, if $0<a<1$
then there are two real solutions:
\begin{align}
z_0&=
\exp\left(\Wp\left(\ln(a)\exp(\ln(a))\right)\right)
\tag{8}\label{8}
,\\
z_1&=
\exp\left(\Wm\left(\ln(a)\exp(\ln(a))\right)\right)
\tag{9}\label{9}
.
\end{align}
One of the solutions would always be $a$:
if $-1<\ln(a)<0$ then $z_0=a$,
else if $\ln(a)<-1$ then $z_1=a$.
For example, if $a=\tfrac1{10}$, then
\begin{align}
z_0&=
\exp\left(\Wp\left(\ln(\tfrac1{10})\exp(\ln(\tfrac1{10}))\right)\right)
\approx 0.7292411
\tag{10}\label{10}
,\\
z_1&=
\exp\left(\Wm\left(\ln(\tfrac1{10})\exp(\ln(\tfrac1{10}))\right)\right)
=
\exp\left(\ln(\tfrac1{10})\right)
=\tfrac1{10}
\tag{11}\label{11}
.
\end{align}
$\endgroup$


text:
Q: Google charts error: every row given must be either null or an array I've setup a Google charts (org chart) implementation that accepts the list of rows as a variable, ultimately coming from PHP.  If I try to render the org chart using that variable, I get the error "every row given must be either null or an array."  If I alert(userlist) prior to the addRows command, copy that output, and replace the variable with the output, all is well, so I know that it's receiving the data properly.  Here's what I've got so far:
google.charts.load('current', {packages:["orgchart"]});
google.charts.setOnLoadCallback(drawChart);

function drawChart() {
  var data = new google.visualization.DataTable();
  data.addColumn('string', 'Name');
  data.addColumn('string', 'Manager');
  data.addColumn('string', 'ToolTip');

  // Pull user information from Drupal
  var userlist = Drupal.settings.orgchart.userlist;

  // For each orgchart box, provide the name, manager, and tooltip to show.
  alert(userlist);
  data.addRows([userlist]);

  // Create the chart.
  var chart = new google.visualization.OrgChart(document.getElementById('org-chart'));
  // Draw the chart, setting the allowHtml option to true for the tooltips.
  chart.draw(data, {allowHtml:true});
}

Again, if I replace userlist in data.addRows([userlist]); with the output from alert(userlist) it works great.
UPDATE: here is the raw output:
[{v:'CN=My Name,OU=IT,OU=Fesslers,DC=hpsi,DC=local', f:'My Name'}, 'CN=Supervisor Name,OU=Sr. Management,OU=Fesslers,DC=hpsi,DC=local', ''], [{v:'', f:'Another Name'}, '', ''], [{v:'CN=Yet Another,OU=IT,OU=Fesslers,DC=hpsi,DC=local', f:'Yet Another'}, 'CN=My Name,OU=IT,OU=Fesslers,DC=hpsi,DC=local', '']
UPDATE: adding in the PHP that creates my userlist variable:
$allusers = entity_load('user');
$userlist = '';
if ($allusers) {
  foreach ($allusers as $useritem) {
    $dn = '';
    $manager = '';
    $fullname = '';
    if ($useritem->uid > 1) { // Skip user 0 and 1
      if (isset($useritem->field_distinguished_name['und']['0']['value'])) {
        $dn = $useritem->field_distinguished_name['und']['0']['value'];
      }
      if (isset($useritem->field_manager_dn['und']['0']['value'])) {
        $manager = $useritem->field_manager_dn['und']['0']['value'];
      }
      if (isset($useritem->field_full_name['und']['0']['value'])) {
        $fullname = $useritem->field_full_name['und']['0']['value'];
      }
      ($userlist == '') ? $userlist = '[[{v:\'' . $dn . '\', f:\'' . $fullname . '\'}, \'' . $manager . '\', \'\']' : $userlist .= ', [{v:\'' . $dn . '\', f:\'' . $fullname . '\'}, \'' . $manager . '\', \'\']';
    }
  }
  if ($userlist != '') {
    $userlist .= ']';
  }
}

A: You have several problems:

*

*the value of userlist is a string, not an object. When you are trying
to addRows([userlist]) you are sending an array having a single
element, a string.

*when trying to transform the object you receive from string to
javascript, JSON.parse doesn't work, because the property names are
not in quotes ({f:'My name'} should be {"f":"My name"})

*sure, it works with userlist=eval('['+userlist+']'), but using eval
in your Javascript is not always the best idea.

*you are declaring Name as string, but you are sending an
object. What's up with that? If you are not sending objects, you also get rid of the Javascript/JSON parsing situation

Finally, I am not sure why your value needs the additional square brackets. From what I see of your PHP code it should have the brackets of the array of arrays already there.
Conclusion: change the format of the returned value so that it is a valid JSON and read it with JSON.parse(value). I am not a Drupal user, but I've found this answer about how to pass a complex PHP variable to Javascript: https://drupal.stackexchange.com/questions/21566/how-to-pass-php-variables-to-javascript-jquery
Here is a working (?) jsfiddle: https://jsfiddle.net/pxjhffj9/ using eval with the string you provided originally.
Here is a valid JSON:
[
    [{
            "v" : "CN=My Name,OU=IT,OU=Fesslers,DC=hpsi,DC=local",
            "f" : "My Name"
        }, "CN=Supervisor Name,OU=Sr. Management,OU=Fesslers,DC=hpsi,DC=local", ""],
    [{
            "v" : "",
            "f" : "Another Name"
        }, "", ""],
    [{
            "v" : "CN=Yet Another,OU=IT,OU=Fesslers,DC=hpsi,DC=local",
            "f" : "Yet Another"
        }, "CN=My Name,OU=IT,OU=Fesslers,DC=hpsi,DC=local", ""]
]

A: Based on the PHP you added you're trying to addRows as a nested array.
Your PHP will generate an array like var userlist = [['bar', 'foo'], ['foo', 'bar]] and when you add your rows it'll be addRows([ [['bar', 'foo'], ['foo', 'bar]] ], becoming one [ ] to much.
Try removing the [ ] around userlist in your call to addRows().


text:
Q: Solana CPI Invocation Error. Error: Error processing Instruction 0: Cross-program invocation with unauthorised signer or writable account I have basically converted a Crowd Funding Campaign written in Native Rust (Solana CLI) into an Anchor Version.
So my tests are running fine except the donation test.
Please if some Solana super shadowy dev can help me figure this out, I shall be grateful. I have spent almost a week debugging, but unable to figure out. Obviously somewhere my logic or syntax is wrong, but I am unable to understand.
Honestly, I feel my logic is right, because I have read the code so many times. But surely, something is wrong......
lib.rs
use anchor_lang::solana_program::system_program;
use anchor_lang::solana_program::program::{invoke /* , invoke_signed */};
use anchor_lang::solana_program::system_instruction;
use anchor_lang::solana_program::program_error::ProgramError;
declare_id!("HwHzMftiyTEYy6w8K6E3AipuF3vgswS1d7c6T6hUeRxf");

#[program]
pub mod solanacrowdfundingproject {
    use super::*;

    // `seeds` and `bump` tell us that our `writing_account` is a PDA that can be derived from their respective values
    pub fn initialize(ctx: Context<Initialize>, writing_account_bump: u8) -> ProgramResult {
        let writing_account = &mut ctx.accounts.writing_account;
        let authority = &mut ctx.accounts.authority;

        writing_account.bump = writing_account_bump;
        writing_account.count = 0;
        writing_account.authority = *authority.key;
        writing_account.campaign_details = Vec::new();
        writing_account.withdraw_request = Vec::new();

        Ok(())
    }

    pub fn create_campaign
    (
        ctx : Context<CreateCampaign>,
        name : String,
        description : String,
        image_link: String,
    )
        -> ProgramResult {

        let writing_account = &mut ctx.accounts.writing_account;
        let authority = &mut ctx.accounts.authority;

        if name.len()  > 30 || description.len() > 50 {
            return Err(ErrorCode::NameOrDescriptionTooLong.into())
        }

        let campaign_data = CampaignDetails {
            admin : *authority.key,
            name : name.to_string(),
            description : description.to_string(),
            image_link : image_link.to_string(),
            amount_donated : 0,
        };

        writing_account.count += 1;
        writing_account.campaign_details.push(campaign_data);

        Ok(())
    }

    pub fn withdraw(ctx : Context<Withdraw>, amount : u64) -> ProgramResult {
        let writing_account = &mut ctx.accounts.writing_account;
        let authority = &mut ctx.accounts.authority;

        let withdraw_data = WithdrawRequest {
            amount_withdrawn : amount,
            admin : *authority.to_account_info().key,
        };

        writing_account.withdraw_request.push(withdraw_data);

         **writing_account.to_account_info().try_borrow_mut_lamports()? -= amount;
         **authority.to_account_info().try_borrow_mut_lamports()? += amount;

        Ok(())

    }

    pub fn donate(ctx : Context<Donate>, amount : u64, donator_program_account_bump : u8) -> ProgramResult {

        let writing_account = &mut ctx.accounts.writing_account;
        let donator_program_account = &mut ctx.accounts.donator_program_account;
        let authority = &mut ctx.accounts.authority;

        donator_program_account.amount_donated = amount;
        donator_program_account.bump = donator_program_account_bump;

       let transfer_ix = system_instruction::transfer(
            &authority.to_account_info().key(),
            &donator_program_account.to_account_info().key(),
            amount,
       );

       #[warn(unused_must_use)]
       invoke(
           &transfer_ix,
           &[
               authority.to_account_info(),
               donator_program_account.to_account_info(),
           ],
       )?;

        let mut campaign_data = CampaignDetails::try_from_slice(*writing_account.to_account_info().try_borrow_mut_data()?)
        .expect("Error deserializing data");
        campaign_data.amount_donated += **donator_program_account.to_account_info().lamports.borrow();

        **writing_account.to_account_info().try_borrow_mut_lamports()? += **donator_program_account.to_account_info().lamports.borrow();
        **donator_program_account.to_account_info().try_borrow_mut_lamports()? = 0;
        *donator_program_account.to_account_info().try_borrow_mut_data()? = &mut [];

        Ok(())
    }

    #[derive(Accounts)]
    #[instruction(writing_account_bump : u8)]
    pub struct Initialize<'info> {
        #[account(init,
            seeds = [b"please_____".as_ref(), authority.key().as_ref()],
            bump = writing_account_bump,
            payer = authority,
            space = 9000)]
            pub writing_account : Account<'info, CampaignState>,
            #[account(mut)]
            pub authority : Signer<'info>,
            #[account(address = system_program::ID)]
            pub system_program : AccountInfo<'info>,

    }

    #[derive(Accounts)]
    pub struct CreateCampaign<'info> {
       #[account(mut, has_one = authority)]
        pub writing_account  : Account<'info, CampaignState>,
        #[account(mut)]
        pub authority : Signer<'info>,
    }

    #[derive(Accounts)]
    pub struct Withdraw<'info> {
        #[account(mut, has_one = authority)]
        pub writing_account : Account<'info, CampaignState>,
        #[account(mut)]
        pub authority : Signer<'info>,
    }

    #[derive(Accounts)]
    #[instruction(donator_program_account_bump : u8)]
    pub struct Donate<'info> {
        #[account(mut)]
        pub writing_account : Account<'info, CampaignState>,
        #[account(mut)]
        pub authority : Signer<'info>,
        #[account(init,
            seeds = [b"donate____".as_ref(),
            authority.key().as_ref()],
            bump = donator_program_account_bump,
            payer = authority,
            space = 100)]
        pub donator_program_account : Account<'info, DonatorProgramAccount>,
        #[account(address = system_program::ID)]
        pub system_program : AccountInfo<'info>,
    }

    #[derive(Debug, Clone, AnchorSerialize, AnchorDeserialize)]
    pub struct CampaignDetails  {
        pub admin: Pubkey,
        pub name: String,
        pub description: String,
        pub image_link: String,
        pub amount_donated: u64,
    }

    #[derive(Debug, Clone, AnchorSerialize, AnchorDeserialize)]
    pub struct WithdrawRequest {
        pub amount_withdrawn : u64,
        pub admin : Pubkey,
    }

    #[account]
    pub struct CampaignState {
       pub campaign_details : Vec<CampaignDetails>,
       pub bump : u8,
       pub count : u8,
       pub authority: Pubkey,
       pub withdraw_request : Vec<WithdrawRequest>,
    }

    #[account]
    pub struct DonatorProgramAccount {
        pub amount_donated : u64,
        bump : u8,
    }

    #[error]
    pub enum ErrorCode {

        #[msg("Name cannot be more than 30 characters and Description cannot be more than 50 characters")]
            NameOrDescriptionTooLong,
    }

}

also my tests as below
const anchor = require('@project-serum/anchor');
const { PublicKey, Connection } = require("@solana/web3.js");
//const cluster = "http://localhost:8899";
const cluster = "https://api.devnet.solana.com";
const connection = new Connection(cluster, "confirmed");
const { SystemProgram, Keypair, /*SYSVAR_RENT_PUBKEY*/ } = anchor.web3;
const { Buffer } = require('buffer');

// Specify provider environment.
const provider = anchor.Provider.env();
//Set provider.
anchor.setProvider(provider);
//Specify the workspace
const program = anchor.workspace.Solanacrowdfundingproject;
//const programID = await connection.programID(program);
const programID = new PublicKey("HwHzMftiyTEYy6w8K6E3AipuF3vgswS1d7c6T6hUeRxf");
// const otherUser (i.e Donator)
const donator = Keypair.generate();

describe('Solanacrowdfundingproject', () => {

  console.log(" Starting tests...");
  try {
    it('gets initialized', async () => {
      const { writingAccount, bump } = await getProgramDerivedCampaignWritingAccountAddress();
      let tx = await program.rpc.initialize(new anchor.BN(bump), {
        accounts: {
          writingAccount: writingAccount,
          authority: provider.wallet.publicKey,
          systemProgram: SystemProgram.programId,

        },

      });
      //Console.log the Transaction signature of the Initialization procedure.
      console.log("Initialization transaction signature : ", tx);

      //Asserts and console.logs
      const account = await program.account.campaignState.fetch(writingAccount);
      console.log(" Created A Writing Account : ", account);
      assert.equal(account.authority.toBase58(), provider.wallet.publicKey.toBase58());
      console.log(" Account's count is :", account.count);
    });
  } catch (error) {
    console.log(error);
  }

  try {
    it('Creates a campaign', async () => {

      const { writingAccount } = await getProgramDerivedCampaignWritingAccountAddress();
      //Lets invocate the createCampaign function using provider.wallet.publicKey
      let tx = await program.rpc.createCampaign("Suveett", "Blockchain Speaker", "Enter a fancy giflink for Campaign",
        {
          accounts: {
            writingAccount: writingAccount,
            authority: provider.wallet.publicKey,

          },

        });
      //Asserts and Console Logs
      //Console.log the Transaction signature of the Initialization procedure.
      console.log("Your CreateCampaign transaction signature", tx);
      let account = await program.account.campaignState.fetch(writingAccount);
      console.log("Writing Account after Campaign Creation :", account);
      console.log("This Writing account's address is : ", writingAccount.toBase58());
      console.log("This Writing account's admin is : ", account.campaignDetails[0].admin.toBase58());
      console.log("This Writing account's Campaign Details contains `name` :", account.campaignDetails[0].name);
      console.log("This Writing account's Campaign Details contains `description` :", account.campaignDetails[0].description);
      assert.equal(account.authority.toBase58(), provider.wallet.publicKey.toBase58());

    });

  } catch (error) {
    console.log(error);
  }

  try {
    it('Can Make a Donation', async () => {
      const signature = await connection.requestAirdrop(donator.publicKey, 1000000000);
      await connection.confirmTransaction(signature);
      console.log("Airdrop confirmed :", await connection.getBalance(donator.publicKey));
      const { writingAccount } = await getProgramDerivedCampaignWritingAccountAddress();
      const { donatorProgramAccount, bump } = await getProgramDerivedDonatorProgramAccountAddress();

      let balanceOfCampaignCreatorPreDonation = await connection.getBalance(writingAccount);
       console.log("Balance of Campaign before Donation : ", balanceOfCampaignCreatorPreDonation);

      let donateTx = await program.rpc.donate(new anchor.BN(1000000), new anchor.BN(bump),
        {
          accounts: {
            writingAccount: writingAccount,
            authority: donator.publicKey,
            donatorProgramAccount: donatorProgramAccount,
            systemProgram: SystemProgram.programId,

          },
           signers: [donator],
        });
      //Asserts and Console Logs
      //Console.log the Transaction signature of the Donation procedure.
      let account = await program.account.donatorProgramAccount.fetch(donatorProgramAccount);
      console.log(" Created a New Donator Program Account : ", account);
      console.log(" Your Donation transaction signature is : ", donateTx);

      let balanceOfCampaignCreatorPostDonation = await connection.getBalance(writingAccount);
      console.log("Balance of Campaign after Donation : ", balanceOfCampaignCreatorPostDonation);

    });
  } catch (error) {
    console.log(error);
  }

  try {
    it('Can Make a Withdrawal', async () => {
      const { writingAccount } = await getProgramDerivedCampaignWritingAccountAddress();

      let withdrawTx = await program.rpc.withdraw(new anchor.BN(50000),
        {
          accounts: {
            writingAccount: writingAccount,
            authority: provider.wallet.publicKey,

          }

        });
      //Asserts and Console Logs
      //Console.log the Transaction signature of the Withdrawal procedure.
      console.log("Your Withdrawal transaction signature", withdrawTx);
      let balanceOfCampaignCreator = await connection.getBalance(writingAccount);
      console.log("Balance of Campaign after Withdrawal: ", balanceOfCampaignCreator);

    });
  } catch (error) {
    console.log(error);
  }

});

async function getProgramDerivedCampaignWritingAccountAddress() {
  const [writingAccount, bump] = await PublicKey.findProgramAddress(
    [Buffer.from('please_____'), provider.wallet.publicKey.toBuffer()],
    programID
  );

  console.log(`Got ProgramDerivedWritingAccountAddress: bump: ${bump}, pubkey: ${writingAccount.toBase58()}`);
  return { writingAccount, bump };

};

async function getProgramDerivedDonatorProgramAccountAddress() {
  const [donatorProgramAccount, bump] = await PublicKey.findProgramAddress(
    [Buffer.from('donate____'), donator.publicKey.toBuffer()],
    programID
  );

  console.log(`Got ProgramDerivedDonatorProgramAccountAddress: bump: ${bump}, pubkey: ${donatorProgramAccount.toBase58()}`);
  return { donatorProgramAccount, bump };

};

Can someone go through the code and help me?
Also, the line Code below (where I am getting the error):
https://github.com/Suveett/solana-crowd-funding-master-using-Anchor/blob/ad87fb2226c800fce1faabd355eb88b812441e0c/tests/solanacrowdfundingproject.js#L91

A: Try to add mut in your declaration:
#[account(init, mut,seeds = [b"please_____".as_ref(), authority.key().as_ref()],bump = writing_account_bump, payer = authority,space = 9000)]


text:
Q: Gradient color in links of sankey chart using networkD3 I am using networkD3 to create sankey diagrams in R. I am using something like below to generate the diagrams:
sankeyNetwork(Links = data$links, Nodes = data$nodes,
          Source = "source", Target = "target", Value = "value", NodeID = "name",
          units = "Questions", fontSize = 12, nodeWidth = 10,
          colourScale = "d3.scale.category10()",
          LinkGroup = "type",             #<--assign colors to links
          width = 1000, height = 600)

I am using LinkGroup = "type" to color the links, where the type is basically the source node's name. This makes the link color same as source node color. This is working pretty well.
I was wondering if there is anyway a gradient of color can be created from sources to targets for the associated links?


text:
Q: how to test python's "__main__" codes with nose for codes like in a some.py:
if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  # ...
  args = parser.parse_args()
  foo()

I'm using nosetests --with-coverage to collect results. but the 'main' codes are not covered, how to test codes here, or omit nose coverage?


text:
Q: GAE Application Stopped Working Suddenly - Failed startup of context com.google.apphosting.utils.jetty.RuntimeAppEngineWebAppContext A couple of days ago my app-engine android app stopped working after a normal deploy. There was no change to my local code (did a diff with previous version), and the only thing that changed was a Java update.
The deploy operation completes successfully, but when the app launches, I get the following errors in the App Engine logs on the Developer Console:
EXCEPTION
java.lang.ClassNotFoundException: Serve
at com.google.appengine.runtime.Request.process-bdec5268b83f2316(Request.java)
at java.lang.ClassLoader.loadClass(ClassLoader.java:360)
at org.mortbay.util.Loader.loadClass(Loader.java:91)
at org.mortbay.util.Loader.loadClass(Loader.java:71)
at org.mortbay.jetty.servlet.Holder.doStart(Holder.java:73)
at org.mortbay.jetty.servlet.ServletHolder.doStart(ServletHolder.java:242)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at org.mortbay.jetty.servlet.ServletHandler.initialize(ServletHandler.java:685)
at org.mortbay.jetty.servlet.Context.startContext(Context.java:140)
at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1250)
at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:517)
at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:467)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at com.google.tracing.TraceContext$TraceContextRunnable.runInContext(TraceContext.java:438)
at com.google.tracing.TraceContext$TraceContextRunnable$1.run(TraceContext.java:445)
at com.google.tracing.CurrentContext.runInContext(CurrentContext.java:220)
at     com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContextNoUnref(TraceContext.java:309)
at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContext(TraceContext.java:301)
at com.google.tracing.TraceContext$TraceContextRunnable.run(TraceContext.java:442)

And this
javax.servlet.ServletContext log: unavailable
javax.servlet.UnavailableException: Serve
at org.mortbay.jetty.servlet.Holder.doStart(Holder.java:79)
at org.mortbay.jetty.servlet.ServletHolder.doStart(ServletHolder.java:242)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at org.mortbay.jetty.servlet.ServletHandler.initialize(ServletHandler.java:685)
at org.mortbay.jetty.servlet.Context.startContext(Context.java:140)
at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1250)
at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:517)
at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:467)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at com.google.apphosting.runtime.jetty.AppVersionHandlerMap.createHandler(AppVersionHandlerMap.java:199)
at com.google.apphosting.runtime.jetty.AppVersionHandlerMap.getHandler(AppVersionHandlerMap.java:174)
at com.google.apphosting.runtime.jetty.JettyServletEngineAdapter.serviceRequest(JettyServletEngineAdapter.java:134)
at com.google.apphosting.runtime.JavaRuntime$RequestRunnable.run(JavaRuntime.java:446)
at com.google.tracing.TraceContext$TraceContextRunnable.runInContext(TraceContext.java:438)
at com.google.tracing.TraceContext$TraceContextRunnable$1.run(TraceContext.java:445)
at com.google.tracing.CurrentContext.runInContext(CurrentContext.java:220)
at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContextNoUnref(TraceContext.java:309)
at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContext(TraceContext.java:301)
at com.google.tracing.TraceContext$TraceContextRunnable.run(TraceContext.java:442)
at com.google.apphosting.runtime.ThreadGroupPool$PoolEntry.run(ThreadGroupPool.java:251)
at java.lang.Thread.run(Thread.java:724)

The root cause seems to be this:
    Failed startup of context com.google.apphosting.utils.jetty.RuntimeAppEngineWebAppContext@e0d280{/,/base/data/home/apps/s~diesel-media-647/1.378309428699474015}
org.mortbay.util.MultiException[java.lang.NullPointerException, java.lang.NullPointerException]
    at org.mortbay.jetty.servlet.ServletHandler.initialize(ServletHandler.java:656)
    at org.mortbay.jetty.servlet.Context.startContext(Context.java:140)
    at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1250)
    at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:517)
    at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:467)
    at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
    at com.google.apphosting.runtime.jetty.AppVersionHandlerMap.createHandler(AppVersionHandlerMap.java:199)
    at com.google.apphosting.runtime.jetty.AppVersionHandlerMap.getHandler(AppVersionHandlerMap.java:174)
    at com.google.apphosting.runtime.jetty.JettyServletEngineAdapter.serviceRequest(JettyServletEngineAdapter.java:134)
    at com.google.apphosting.runtime.JavaRuntime$RequestRunnable.run(JavaRuntime.java:446)
    at com.google.tracing.TraceContext$TraceContextRunnable.runInContext(TraceContext.java:438)
    at com.google.tracing.TraceContext$TraceContextRunnable$1.run(TraceContext.java:445)
    at com.google.tracing.CurrentContext.runInContext(CurrentContext.java:220)
    at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContextNoUnref(TraceContext.java:309)
    at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContext(TraceContext.java:301)
    at com.google.tracing.TraceContext$TraceContextRunnable.run(TraceContext.java:442)
    at com.google.apphosting.runtime.ThreadGroupPool$PoolEntry.run(ThreadGroupPool.java:251)
    at java.lang.Thread.run(Thread.java:724)
java.lang.NullPointerException
    at java.lang.Class.isAssignableFrom(Native Method)
    at org.mortbay.jetty.servlet.ServletHolder.doStart(ServletHolder.java:256)
    at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
    at org.mortbay.jetty.servlet.ServletHandler.initialize(ServletHandler.java:685)
    at org.mortbay.jetty.servlet.Context.startContext(Context.java:140)
    at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1250)
    at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:517)
    at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:467)
    at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
    at com.google.apphosting.runtime.jetty.AppVersionHandlerMap.createHandler(AppVersionHandlerMap.java:199)
    at com.google.apphosting.runtime.jetty.AppVersionHandlerMap.getHandler(AppVersionHandlerMap.java:174)
    at com.google.apphosting.runtime.jetty.JettyServletEngineAdapter.serviceRequest(JettyServletEngineAdapter.java:134)
    at com.google.apphosting.runtime.JavaRuntime$RequestRunnable.run(JavaRuntime.java:446)
    at com.google.tracing.TraceContext$TraceContextRunnable.runInContext(TraceContext.java:438)
    at com.google.tracing.TraceContext$TraceContextRunnable$1.run(TraceContext.java:445)
    at com.google.tracing.CurrentContext.runInContext(CurrentContext.java:220)
    at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContextNoUnref(TraceContext.java:309)
    at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContext(TraceContext.java:301)
    at com.google.tracing.TraceContext$TraceContextRunnable.run(TraceContext.java:442)
    at com.google.apphosting.runtime.ThreadGroupPool$PoolEntry.run(ThreadGroupPool.java:251)
    at java.lang.Thread.run(Thread.java:724)
java.lang.NullPointerException
    at java.lang.Class.isAssignableFrom(Native Method)
    at org.mortbay.jetty.servlet.ServletHolder.doStart(ServletHolder.java:256)
    at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
    at org.mortbay.jetty.servlet.ServletHandler.initialize(ServletHandler.java:685)
    at org.mortbay.jetty.servlet.Context.startContext(Context.java:140)
    at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1250)
    at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:517)
    at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:467)
    at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
    at com.google.apphosting.runtime.jetty.AppVersionHandlerMap.createHandler(AppVersionHandlerMap.java:199)
    at com.google.apphosting.runtime.jetty.AppVersionHandlerMap.getHandler(AppVersionHandlerMap.java:174)
    at com.google.apphosting.runtime.jetty.JettyServletEngineAdapter.serviceRequest(JettyServletEngineAdapter.java:134)
    at com.google.apphosting.runtime.JavaRuntime$RequestRunnable.run(JavaRuntime.java:446)
    at com.google.tracing.TraceContext$TraceContextRunnable.runInContext(TraceContext.java:438)
    at com.google.tracing.TraceContext$TraceContextRunnable$1.run(TraceContext.java:445)
    at com.google.tracing.CurrentContext.runInContext(CurrentContext.java:220)
    at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContextNoUnref(TraceContext.java:309)
    at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContext(TraceContext.java:301)
    at com.google.tracing.TraceContext$TraceContextRunnable.run(TraceContext.java:442)
    at com.google.apphosting.runtime.ThreadGroupPool$PoolEntry.run(ThreadGroupPool.java:251)
    at java.lang.Thread.run(Thread.java:724)

Here are the solutions that I tried based on similar posts:

*

*I have updated my GAE SDK to the latest (1.9.9) as per this post
Weird 500 Error on GAE

*I have used appcfg to do a roll-back and clean of my deployment. The clean operating was completed successfully, but when I redeployed the same errors occured.

*I have reverted back to Java 1.6 (currently at 1.7) - didn't work.

*I have double checked my web.xml file to make sure that the servlet paths are correct. I tried fully qualifying the class names with my package - didn't work

*I have tried adding the load-on-startup tag in my web.xml file as per this post
EXCEPTION java.lang.ClassNotFoundException: servlet - But the Servlet is present; And web.xml is absolutely correct
I've been battling with this for a couple of days now, and I'm at my wit's end. Any help is appreciated.
For reference, I'm using GAE SDK 1.9.9, upgraded from 1.9.3 when I encountered this problem.
I'm using Java 1.7 (tried 1.6).

A: You must include the class "Serve" in your package (build path) because you get java.lang.ClassNotFoundException: Serve.

A: Finally resolved the issue, but unfortunately I don't exactly know why (which always sucks)
It was a series of steps (not one).
I'm pretty sure the app was stuck in a partial deployment state so I used the appcfg application to do a rollback. I had done this step solo but it didn't work.
The next thing was manually deleting the generated classes folder - the servlet .class files were corrupt (I had done this step alone but it didn't work).
Redeployed and it automagically worked.
This was a very annoying error given that I hadn't changed any of my code, and the compiler didn't complain about the .classes files not being deleted/recreated.
Hope this helps someone.


text:
Q: Outputting an array of term meta values in a custom WooCommerce tab? Forgive me – my Wordpress/PHP skills are hilariously rudimentary, so I may not use the correct terminology.
I have added a custom tab to the WooCommerce single product page and need it to display a number (sometimes single, sometimes multiple) of term meta values related to a custom taxonomy, 'book-author'. These values are created in a WYSIWYG editor and contain HTML formatting. Each 'book-author' has an author bio (the term meta 'wpcf-author-biography'), and each WooCommerce product has one or more 'book-authors' attributed to it.
This is the code I'm currently using:
// Add author bio tab

add_filter( 'woocommerce_product_tabs', 'woo_new_product_tab' );
function woo_new_product_tab( $tabs ) {

// Adds the new tab

$tabs['author_tab'] = array(
    'title'     => __( 'About the author', 'woocommerce' ),
    'priority'  => 50,
    'callback'  => 'woo_new_product_tab_content'
);

return $tabs;

}

// Add the content

function woo_new_product_tab_content() {

$terms = get_the_terms(get_the_ID(), 'book-author' );
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
foreach ( $terms as $term ) {
    $all_term_meta = get_term_meta($term->term_id, 'wpcf-author-biography', false);
    print_r($all_term_meta);
}
}
}

It took me forever to get to this point, and while the relevant data is finally being output, the frontend result leaves a lot to be desired. This is how it ends up:

            Array
(
[0] => XX staff writer John Doe has covered
everything from men's style and grooming to food, drinks and travel. John
has also interviewed some of the biggest names in film, television and
music.
)
Array
(
[0] =>

Jane Doe is an author and university
lecturer in underwater basket-weaving. She has recently completed a PhD.

)

While the tab itself is created without any issues, as you can see, I'm getting some rogue Arrays being displayed as well as some other guff, and the second term meta value is for some reason being stuck in its own hidden tab wrapper, when it should appear in the same tab.
Obviously I'm not going about this the right way otherwise I wouldn't be here, so any help or push in the right direction would be greatly appreciated.
Additionally, if there's any way to implement a condition so that if there is no 'book-author' attributed to the product, no 'About the author' tab appears, that would be most helpful...
Thanks in advance!
Edit: Based on the advice given by WebElaine I tried using a foreach instead of print_r:
function woo_new_product_tab_content() {

$terms = get_the_terms(get_the_ID(), 'book-author' );
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
foreach ( $terms as $term ) {
    $all_term_meta = get_term_meta($term->term_id, 'wpcf-author-biography',
false);
    foreach($all_term_meta as $meta) {
        echo $meta[0]; //tried with return as well with no success
}
}
}
}

This yields the following results:

            G<

If I remove the [0] after $meta, we manage to get rid of the ugly characters and stray Array, but I still have the issue of my second author's info getting lost:

        XX staff writer John Doe has covered
everything from men's style and grooming to food, drinks and travel. John
has also interviewed some of the biggest names in film, television and
music.

Jane Doe is an author and university lecturer in
underwater basket-weaving. She has recently completed a PhD.

A: For your author content display, instead of print_r($all_term_meta); try a foreach:
foreach($all_term_meta as $meta) {
    return $meta[0];
}

It's possible you may need to use "echo" instead of "return" but try "return" first.
To control whether or not there is an author tab, update your woo_new_product_tab function with the same condition:
function woo_new_product_tab( $tabs ) {
    $terms = get_the_terms(get_the_ID(), 'book-author' );
    if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
        // Adds the new tab
        $tabs['author_tab'] = array(
            'title'     => __( 'About the author', 'woocommerce' ),
            'priority'  => 50,
            'callback'  => 'woo_new_product_tab_content'
        );
    }
    return $tabs;
}

A: Thanks to WebElaine I managed to find a solution that addressed the hidden tab issue:
function woo_new_product_tab_content() {

$terms = get_the_terms(get_the_ID(), 'book-author' );
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
    foreach ( $terms as $term ) {
        $all_term_meta = get_term_meta($term->term_id, 'wpcf-author-
biography', false);
        foreach($all_term_meta as $meta) {
            echo '
' . strip_tags($meta, '

') . '
';
    }
   }
  }
}

This outputs the following satisfying HTML:

XX staff writer John Doe has
   covered everything from men's style and grooming to food, drinks and
   travel. John has also interviewed some of the biggest names in film,
   television and music.

Jane Doe is an author and university
   lecturer in underwater basket-weaving. She has recently completed a
   PhD.


text:
Q: why 10000101 is both -5 and 133 Vidoe
00000101 is 5
10000101 is -5
but 10000101 is also 133
I don't understand why 1 binary is able to represent 2 numbers.
Any help is appreciated, thank you.

A: The word "Gift" has at least two meanings. In English, it means a present you give somebody. In German, it means poison. To know which concept a speaker means, you must know which language they are speaking.
The bit string 10000101 does not mean anything by itself. It is just some bits. Bit strings have values only when we associate them with types, which are (in part) methods of associating values with bit strings. To know what value it represents, you must know which type it is being used with.
If we interpret 10000101 as a pure binary numeral, it means 1•27 + 1•22 + 1•20 = 128 + 4 + 1 = 133.
If we interpret 10000101 as a sign-and-magnitude representation, it means negative with 1•22 + 1•20 = − (4+1) = −5.
If we interpret 10000101 as a two's complement representation, it means −1•27 + 1•22 + 1•20 = −128 + 4 + 1 =  −123.
In C, every declared object and every constant has a type, and every expression built from these things has a type. The type says how to interpret the bits.

A: In these representations of a signed number that occupies one byte
00000101 is 5

10000101 is -5

the most significant bit is the sign bit that determines whether the stored number is positive or negative.
That is if the sign bit is set then the corresponding value stored in value bits is negated.
This representation of signed values is named like sign and magnitude.
It is implementation-defined how signed values are stored. Most computer architectures use the so called 2's complement representation. For such an architecture the negative number -5 is represented like
11111011 is -5

If the number is considered as having an unsigned integer type then no bit is allocated as the sign bit. In this case all bits are value bits. So for unsigned integer this representation 10000101 yields the value 133.

A:
I don't understand why 1 binary is able to represent 2 numbers.

Pure binary numbers have no sign.
So as pure binary, 10000101 is unambiguously 133, pure and simple.
But, of course, we want to be able to handle negative numbers.  So there are various ways of rigging things up so that some bit patterns represent negative numbers.  But as soon as you do that, you're going to end up with bit patterns which can be interpreted two ways: as straight binary (giving a positive number) or as signed binary (giving a negative number).  Any bit pattern that represents a negative number can also be interpreted as a positive number, by just not using whatever negative-number rule you were using.
Here's another way of thinking about it.  Consider the word "march".  It's the thing that bands do in parades.  But if I capitalize the first letter, March, it's the third month of the year.  So If I write "March", and I pay attention to the capitalization, it's a month, but if I ignore the capitalization, it's a verb.
Similarly, if I write 10000101, and I ignore the possibility of signedness, I get 133.
But if I pay attention to sign, I get a negative number.
Or if I interpret it as a character, I might get something else!
Here are 5 possibilities:

bit pattern
interpreted as
gives

10000101
pure binary
133

10000101
sign/magnitude
-5

10000101
ones' complement
-122

10000101
two's complement
-123

10000101
character
à

(Now, I confess, in the last row I had to cheat, by using the old MS-DOS character set.  In Unicode, 10000101 does not represent a character, and in the Windows character set, it's one character that's an ellipsis, or three dots: … .)

Now, one thing you may be worried about is whether we're getting "something for nothing", by having a bit pattern that can do double duty as either as positive or a negative number.  Are we cheating and extending the range somehow?  The answer is that, no, we're not.  Let's stay with 8-bit numbers.  If we treat our 8-bit numbers as pure binary, we can cover the range from 0 to 255 (that is, 00000000 to 11111111).  We can't represent the number 300, because it takes too many bits, and we can't represent the number -5, because we have no way to represent negative numbers.  With 8 bits, in pure binary, we can represent only 0 to 255, and that's it.
If we switch to two's complement, we can represent any number from -128 to +127 — which is exactly 256 different numbers.  We still can't represent 300 (positive or negative), because it's still too many bits.  But, now, we can't represent the number 200, either, because if we try to, it's 11001000, and that's the two's complement bit pattern for -56.  Similarly, we can't represent 133 (your original example), because its bit pattern is 10000101, and that's a negative number, too, -123.


text:
Q: Bootstrap 3 modal slideshow i have problem regarding bootstrap 3 with modal that has slideshow (Swiper) inside. When i put it on modal it isn't working but when i put it on clasic page it is working.
I have tried to use shown.bs.modal with mySwiper.update() and no luck.
Can somebody help me ?

A: this is solution to my problem
 $('#myModal').on('shown.bs.modal', function () {
        mySwiper.update();
    });


text:
Q: Importing ODK XML file to MS Access using XLST transformation I'm trying to import a submission.xml file generated from an ODK survey into Access. I'm using the 'XML import' function in MS Access and need to transform the data so that the each data set of a node that will be imported to a table will contain the ID of the survey.
I have a XML with the survey data that looks like this:
<SoLa_Tu_Insp_2016-03-13 id="SOLA-160313"
    instanceID="uuid:63c27738-df02-4298-9090-7ab96d4e1ab2"
    submissionDate="2016-04-08T02:11:47.600Z"
    isComplete="true"
    markedAsCompleteDate="2016-04-08T02:13:12.322Z"
    xmlns="http://opendatakit.org/submissions">
<start>2016-04-08T23:47:50.615Z</start>
<end>2016-04-08T02:11:30.954Z</end>
<deviceid>353375050176865</deviceid>
<telnr />
<insp>
    <objekt>25</objekt>
    <objdel>212</objdel>
    <objdel-tx>Bronstunneln</objdel-tx>
    <datum>2016-04-08</datum>
    <sign>MFR RLS</sign>
    <anm>8</anm>
</insp>
<skdr>
    <skd>
        <metod>100</metod>
        <ts>
            <ts-nr>523</ts-nr>
            <ts-typskada>Lucka - Lös -  Takelement</ts-typskada>
            <ts-kdel>15</ts-kdel>
            <ts-kelem>1530</ts-kelem>
            <ts-mtrl>13</ts-mtrl>
            <ts-typ>35</ts-typ>
            <ts-orsak>999</ts-orsak>
            <ts-aktivitet>87</ts-aktivitet>
            <ts-enhet>st</ts-enhet>
            <ts-aktivitet-tx>Åtdragning</ts-aktivitet-tx>
            <ts-mangd>1.0000000000</ts-mangd>
        </ts>
        <ovr>
            <ovr-kdel />
            <ovr-kdel-tx />
            <ovr-kelem />
            <ovr-kelem-tx />
            <ovr-mtrl />
            <ovr-mtrl-tx />
            <ovr-typ />
            <ovr-typ-tx />
            <ovr-orsak />
            <ovr-aktivitet />
            <ovr-aktivitet-tx />
            <ovr-enhet />
            <ovr-mangd />
        </ovr>
        <kdel>15</kdel>
        <kelem>1530</kelem>
        <mtrl>13</mtrl>
        <typ>35</typ>
        <orsak>999</orsak>
        <skd-tx>Gång/inspektionsbrygga etc / Lucka/dörr / Rostfritt stål / Lös / Övrigt</skd-tx>
        <tk>3</tk>
        <anm>Luckan håller på att ramla av</anm>
        <aktivitet>87</aktivitet>
        <mangd>1</mangd>
        <enhet>st</enhet>
        <sekt1>675</sekt1>
        <sekt2 />
        <lage>VT</lage>
        <lage-tx />
        <bildskada>1460073108135.jpg</bildskada>
        <bildnr />
    </skd>
    <skd>
        <metod>100</metod>
        <ts>
            <ts-nr>321</ts-nr>
            <ts-typskada>f.a. sprutbetong - Läckage - Tak</ts-typskada>
            <ts-kdel>6</ts-kdel>
            <ts-kelem>665</ts-kelem>
            <ts-mtrl>6</ts-mtrl>
            <ts-typ>50</ts-typ>
            <ts-orsak>129</ts-orsak>
            <ts-aktivitet>45</ts-aktivitet>
            <ts-enhet>kg</ts-enhet>
            <ts-aktivitet-tx>Injektering</ts-aktivitet-tx>
            <ts-mangd>5.0000000000</ts-mangd>
        </ts>
        <ovr>
            <ovr-kdel />
            <ovr-kdel-tx />
            <ovr-kelem />
            <ovr-kelem-tx />
            <ovr-mtrl />
            <ovr-mtrl-tx />
            <ovr-typ />
            <ovr-typ-tx />
            <ovr-orsak />
            <ovr-aktivitet />
            <ovr-aktivitet-tx />
            <ovr-enhet />
            <ovr-mangd />
        </ovr>
        <kdel>6</kdel>
        <kelem>665</kelem>
        <mtrl>6</mtrl>
        <typ>50</typ>
        <orsak>129</orsak>
        <skd-tx>Huvudbärverk / Tak ytförstärkning / Fiberarmerad sprutbetong / Läckage / Vatten</skd-tx>
        <tk>2</tk>
        <anm>3/s</anm>
        <aktivitet>45</aktivitet>
        <mangd>5</mangd>
        <enhet>kg</enhet>
        <sekt1>694</sekt1>
        <sekt2>694</sekt2>
        <lage>CT</lage>
        <lage-tx>Kalk, järn,mangan utfälning droppar rikligt</lage-tx>
        <bildskada />
        <bildnr>4517</bildnr>
    </skd>
    <skd>
        <metod>100</metod>
        <ts>
            <ts-nr>321</ts-nr>
            <ts-typskada>f.a. sprutbetong - Läckage - Tak</ts-typskada>
            <ts-kdel>6</ts-kdel>
            <ts-kelem>665</ts-kelem>
            <ts-mtrl>6</ts-mtrl>
            <ts-typ>50</ts-typ>
            <ts-orsak>129</ts-orsak>
            <ts-aktivitet>45</ts-aktivitet>
            <ts-enhet>kg</ts-enhet>
            <ts-aktivitet-tx>Injektering</ts-aktivitet-tx>
            <ts-mangd />
        </ts>
        <ovr>
            <ovr-kdel />
            <ovr-kdel-tx />
            <ovr-kelem />
            <ovr-kelem-tx />
            <ovr-mtrl />
            <ovr-mtrl-tx />
            <ovr-typ />
            <ovr-typ-tx />
            <ovr-orsak />
            <ovr-aktivitet />
            <ovr-aktivitet-tx />
            <ovr-enhet />
            <ovr-mangd />
        </ovr>
        <kdel>6</kdel>
        <kelem>665</kelem>
        <mtrl>6</mtrl>
        <typ>50</typ>
        <orsak>129</orsak>
        <skd-tx>Huvudbärverk / Tak ytförstärkning / Fiberarmerad sprutbetong / Läckage / Vatten</skd-tx>
        <tk>1</tk>
        <anm>Kalk, järn,mangan utfälning</anm>
        <aktivitet>45</aktivitet>
        <mangd />
        <enhet>kg</enhet>
        <sekt1>698</sekt1>
        <sekt2 />
        <lage>VT</lage>
        <lage-tx>8/sek</lage-tx>
        <bildskada />
        <bildnr>4519-4520</bildnr>
    </skd>
    <skd>
        <metod>100</metod>
        <ts>
            <ts-nr>513</ts-nr>
            <ts-typskada>Lucka - Defekt - Takelement</ts-typskada>
            <ts-kdel>15</ts-kdel>
            <ts-kelem>1530</ts-kelem>
            <ts-mtrl>13</ts-mtrl>
            <ts-typ>48</ts-typ>
            <ts-orsak>999</ts-orsak>
            <ts-aktivitet>88</ts-aktivitet>
            <ts-enhet>st</ts-enhet>
            <ts-aktivitet-tx>Översyn</ts-aktivitet-tx>
            <ts-mangd />
        </ts>
        <ovr>
            <ovr-kdel />
            <ovr-kdel-tx />
            <ovr-kelem />
            <ovr-kelem-tx />
            <ovr-mtrl />
            <ovr-mtrl-tx />
            <ovr-typ />
            <ovr-typ-tx />
            <ovr-orsak />
            <ovr-aktivitet />
            <ovr-aktivitet-tx />
            <ovr-enhet />
            <ovr-mangd />
        </ovr>
        <kdel>15</kdel>
        <kelem>1530</kelem>
        <mtrl>13</mtrl>
        <typ>48</typ>
        <orsak>999</orsak>
        <skd-tx>Gång/inspektionsbrygga etc / Lucka/dörr / Rostfritt stål / Defekt / Övrigt</skd-tx>
        <tk>2</tk>
        <anm>Går ej skruva saknas 2st skruvar</anm>
        <aktivitet>88</aktivitet>
        <mangd />
        <enhet>st</enhet>
        <sekt1>653</sekt1>
        <sekt2 />
        <lage>HT</lage>
        <lage-tx>Nya skruvhål luckan som matchar</lage-tx>
        <bildskada />
        <bildnr>4523-4521</bildnr>
    </skd>
    <skd>
        <metod>100</metod>
        <ts>
            <ts-nr>513</ts-nr>
            <ts-typskada>Lucka - Defekt - Takelement</ts-typskada>
            <ts-kdel>15</ts-kdel>
            <ts-kelem>1530</ts-kelem>
            <ts-mtrl>13</ts-mtrl>
            <ts-typ>48</ts-typ>
            <ts-orsak>999</ts-orsak>
            <ts-aktivitet>88</ts-aktivitet>
            <ts-enhet>st</ts-enhet>
            <ts-aktivitet-tx>Översyn</ts-aktivitet-tx>
            <ts-mangd>1.0000000000</ts-mangd>
        </ts>
        <ovr>
            <ovr-kdel />
            <ovr-kdel-tx />
            <ovr-kelem />
            <ovr-kelem-tx />
            <ovr-mtrl />
            <ovr-mtrl-tx />
            <ovr-typ />
            <ovr-typ-tx />
            <ovr-orsak />
            <ovr-aktivitet />
            <ovr-aktivitet-tx />
            <ovr-enhet />
            <ovr-mangd />
        </ovr>
        <kdel>15</kdel>
        <kelem>1530</kelem>
        <mtrl>13</mtrl>
        <typ>48</typ>
        <orsak>999</orsak>
        <skd-tx>Gång/inspektionsbrygga etc / Lucka/dörr / Rostfritt stål / Defekt / Övrigt</skd-tx>
        <tk>2</tk>
        <anm>Luckan behövs passas om</anm>
        <aktivitet>88</aktivitet>
        <mangd>1</mangd>
        <enhet>st</enhet>
        <sekt1>681</sekt1>
        <sekt2 />
        <lage>VT</lage>
        <lage-tx>TV3 tidigare 2 skruv har sätts men mådet åtgärdas</lage-tx>
        <bildskada />
        <bildnr>4527</bildnr>
    </skd>
    <skd>
        <metod>100</metod>
        <ts>
            <ts-nr>513</ts-nr>
            <ts-typskada>Lucka - Defekt - Takelement</ts-typskada>
            <ts-kdel>15</ts-kdel>
            <ts-kelem>1530</ts-kelem>
            <ts-mtrl>13</ts-mtrl>
            <ts-typ>48</ts-typ>
            <ts-orsak>999</ts-orsak>
            <ts-aktivitet>88</ts-aktivitet>
            <ts-enhet>st</ts-enhet>
            <ts-aktivitet-tx>Översyn</ts-aktivitet-tx>
            <ts-mangd>1.0000000000</ts-mangd>
        </ts>
        <ovr>
            <ovr-kdel />
            <ovr-kdel-tx />
            <ovr-kelem />
            <ovr-kelem-tx />
            <ovr-mtrl />
            <ovr-mtrl-tx />
            <ovr-typ />
            <ovr-typ-tx />
            <ovr-orsak />
            <ovr-aktivitet />
            <ovr-aktivitet-tx />
            <ovr-enhet />
            <ovr-mangd />
        </ovr>
        <kdel>15</kdel>
        <kelem>1530</kelem>
        <mtrl>13</mtrl>
        <typ>48</typ>
        <orsak>999</orsak>
        <skd-tx>Gång/inspektionsbrygga etc / Lucka/dörr / Rostfritt stål / Defekt / Övrigt</skd-tx>
        <tk>3</tk>
        <anm />
        <aktivitet>88</aktivitet>
        <mangd>1</mangd>
        <enhet>st</enhet>
        <sekt1>710</sekt1>
        <sekt2 />
        <lage>HT</lage>
        <lage-tx>Nedre skruvhål passar inte</lage-tx>
        <bildskada />
        <bildnr>4543-4542</bildnr>
    </skd>
</skdr>
<ritningar>212B2B01 212B2B02 212B2B03 212B2B04</ritningar>
<skd-antal>6</skd-antal>
<sekt-min>653</sekt-min>
<sekt-max>710</sekt-max>
<tk-min>1</tk-min>
<tk-max>3</tk-max>
<n0:meta xmlns:n0="http://openrosa.org/xforms">
    <n0:instanceID>uuid:63c27738-df02-4298-9090-7ab96d4e1ab2</n0:instanceID>
    <n0:instanceName>SöLä-25-212-2016-04-08-MFR RLS-4ae669a1-7d89-424a-bfab-26d506da0604</n0:instanceName>
</n0:meta>

At each 'skd' node I want to add the 'instanceID' attribute of the root element so that each 'skd' node will look something like:
<skdr>
    <skd>
        <id>uuid:63c27738-df02-4298-9090-7ab96d4e1ab2</id>
        <metod>100</metod>

So I'm trying to use this XSL-file for the transformation, which is not working as intended:
xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:output indent="yes" encoding="utf-8"/>
<xsl:strip-space elements="*"/>

<xsl:template match="/">
    <dataroot>
        <xsl:apply-templates select="@*|node()"/>
    </dataroot>
</xsl:template>

<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="//skd">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
            <ID><xsl-copy-of select="/SoLa_Tu_Insp_2016-03-13/@instanceID"/></ID>
        <xsl:apply-templates select="node()"/>
    </xsl:copy>

</xsl:template>

The result I get when using the above transformation is like this:
    <?xml version="1.0" encoding="utf-8"?>
<dataroot>
  <SoLa_Tu_Insp_2016-03-13 xmlns="http://opendatakit.org/submissions" id="SOLA-160313" instanceID="uuid:63c27738-df02-4298-9090-7ab96d4e1ab2" submissionDate="2016-04-08T02:11:47.600Z" isComplete="true" markedAsCompleteDate="2016-04-08T02:13:12.322Z">
    <start>2016-04-08T23:47:50.615Z</start>
    <end>2016-04-08T02:11:30.954Z</end>
    <deviceid>353375050176865</deviceid>
    <telnr/>
    <insp>
      <objekt>25</objekt>
      <objdel>212</objdel>
      <objdel-tx>Bronstunneln</objdel-tx>
      <datum>2016-04-08</datum>
      <sign>MFR RLS</sign>
      <anm>8</anm>
    </insp>
    <skdr>
      <skd>
        <metod>100</metod>
        <ts>
          <ts-nr>523</ts-nr>
          <ts-typskada>Lucka - Lös -  Takelement</ts-typskada>
          <ts-kdel>15</ts-kdel>
          <ts-kelem>1530</ts-kelem>
          <ts-mtrl>13</ts-mtrl>
          <ts-typ>35</ts-typ>
          <ts-orsak>999</ts-orsak>
          <ts-aktivitet>87</ts-aktivitet>
          <ts-enhet>st</ts-enhet>
          <ts-aktivitet-tx>Åtdragning</ts-aktivitet-tx>
          <ts-mangd>1.0000000000</ts-mangd>
        </ts>

Thers is no 'instanceID' at each 'skd' node. I've tested the XPATHs at http://www.freeformatter.com/xpath-tester.html and it seems to be OK.
Anyone have any idea what I'm doing wrong here?

A: Your template does not match the skd element in the source XML document, because that element is in a namespace.
Try it this way instead:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:odk="http://opendatakit.org/submissions"
exclude-result-prefixes="odk">
<xsl:output indent="yes" encoding="utf-8"/>
<xsl:strip-space elements="*"/>

<xsl:template match="/">
    <dataroot>
        <xsl:apply-templates select="@*|node()"/>
    </dataroot>
</xsl:template>

<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="odk:skd">
    <xsl:copy>
        <xsl:apply-templates select="@*"/>
        <ID xmlns="http://opendatakit.org/submissions">
            <xsl:value-of select="/odk:SoLa_Tu_Insp_2016-03-13/@instanceID"/>
        </ID>
        <xsl:apply-templates select="node()"/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

Additional notes:

*

*Starting a match pattern with // is redundant;

*xsl-copy-of is not a valid XSLT instruction;

*Your version <xsl:apply-templates select="@*|node()"/> would have duplicated the child nodes.


text:
Q: How to pass UIAction without touching the UIButton I've got a UIButton that acts as a switch.
When user taps on it, its state changes to "selected" and action "one" is called. When user taps again UIButton state changes to "not selected" and the action is no longer available.
Is there a way to set the UIButton to "selected" by taping on a completely different UIButton and have it change to "selected" and call the same action as well?
Cheers

A: From what I have understood from the question, I would like to give you my suggestion
if (!<your_button>.selected)
{
    <your_button>.selected = YES;
    // do your stuff here
}
else
{
    <your_button>.selected = NO;
    // do your stuff here, in your case action should be no longer available so that,
    <your_button>.userInteractionEnabled = NO;
}

Enjoy Programming !

A: simple thing when you tap on the uibutton make an action for that and in the action for that button , you can set the button state to selected and then in the next line of code you can call that method (action)
- (IBAction)btn1Touched:(id)sender {
    [_btn2 setSelected:YES];
    [self btn2Touched:self];
}
- (IBAction)btn2Touched:(id)sender {

    NSLog(@"btn Action called");
}

A: try like this,'
 -(IBAction)nextbutton:(id)sender{
    UIButton *btn=(UIButton *)[self.view viewWithTag:tagValue];//pass tag value of that particuler button
    btn.selected=YES;
    //do whatevr you want.

    }

A: UIbutton has state called selected and it is managed via property selected
so to make a button to selected state
[buttonInstance setSelected:YES];

To make it unselected use
[buttonInstance setSelected:NO];

A: Kindly write a function for that button action like,
-(void)Buttonaction

{

do your action here

  also set your button has selected state.

  buttonname.setselected=yes;

}

call this function while you are tabbing your button.

A: Do This:
-(IBAction)switchButtonClicked:(UIButton*)sender
{

    if(sender.isSelected)
      {
        .....
      }
    else
      {
        ...
      }
    [sender setSelected:!sender.isSelected];//This will work as Switch.
}

set Selected(Switch ON) and default(Switch OFF) property (image and title) of UIButton from XIB, OR from Code as you want.
  With a single button you can do you functionality with this code


text:
Q: Hibernate @OneToMany join table throws StackOverflowException I'm working on a hibernate entity relationship that is set up as follows:
A user can create assignments.  The user can split the assignment with other users, giving them tasks.  My goal is to have a user that is as follows:
{ id: 1, assignments: [{name: 'test'}], partialAssignment: [{task: 'bla'}]}
And assignments like this:
{id: 1, user: {...}, assignedUsers: [{...}], ...}
Assignment:
    @Entity
    @Table(name = "Assignment")
    data class Assignment (

      @Id
      @GeneratedValue(strategy = GenerationType.IDENTITY)
      @Column(name = "id", nullable = false, updatable = false)
      val id: Long? = null,

      @Column(name = "name")
      val name: String? = null,

      @Column(name = "dueDate")
      @Temporal(TemporalType.TIMESTAMP)
      val dueDate: Date? = null,

      @ManyToOne
      @JoinColumn(name = "userId")
      var user: User? = null,

      @OneToMany(mappedBy = "assignment")
      var assignedUsers: List<AssignmentUser> = emptyList()
    )

User
@Entity
@Table(name = "Users")
data class User (

    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false, updatable = false)
    @JsonView(UserView.UserSummary::class)
    val id: Long? = null,

    @Column(name = "email", nullable = false)
    @JsonView(UserView.UserSummary::class)
    val email: String = "",

    @Column(name = "password", nullable = false)
    val password: String = "",

    @OneToMany(mappedBy = "user")
    val assignments: List<Assignment> = emptyList(),

    @OneToMany(mappedBy = "user")
    val partialAssignment: List<AssignmentUser> = emptyList()
)

AssignmentUser
@Entity
@Table(name = "AssignmentUsers")
data class AssignmentUser(
    @Column(name = "task")
    val task: String? = null,

    @Id
    @ManyToOne(cascade = arrayOf(CascadeType.ALL))
    @JoinColumn(name = "userId")
    var user: User? = null,

    @Id
    @ManyToOne(cascade = arrayOf(CascadeType.ALL))
    @JoinColumn(name = "assignmentId")
    var assignment: Assignment? = null
) : Serializable {

}

When I fetch the Assignment class using a JPARepository .findOne(id) call, I get a StackOverflow exception on the Assignment.toString() method.  I don't understand why, as it worked fine until I added the psuedo ManyToMany relationship (assignedUsers).
Any thoughts?

A: Here problem is not excatly with @OneToMany.
In case of serialization (in this case printing object's string form) the stated code will go in cyclic loop.
In stated code snippet cyclic relationships are as follow:
1. Assignment has List
2. Assignement has User
3. User has List
4. User has List
5. AssignmentUser has User
6. AssignmentUser has Assignment
In hibernate all mappings are by default set to LAZY, hence it will not cause problem bacause we will not load associated object unless needed.
But, in case of serialization it will try to load associated objects, and hence to break this we need to implement the custom serialization. In your case you need to override the toString method of above objects properly i.e. objects should not be loaded unnecessarily.


text:
Q: Where to store Morphlines Java custom command class? I have csv files that are indexed in Solr through a Morphline Sink.
I would like to write a custom Java function in Morphlines that hashes one of the csv fields before indexing it into SOLR.
I tried to adapt this example: http://blog.cloudera.com/blog/2014/04/how-to-process-data-using-morphlines-in-kite-sdk/ (see Import Data into the Hadoop Cluster section)
but I am not sure when i should store the Java class.
So in this example, a publicly available "million song" dataset is picked from Last.fm. the idea is to select songs before and after a given date.
The configuration of the new Morphline command is:
morphlines : [
    {
        id : morphline1
        importCommands : ["org.kitesdk.**", "com.sequenceiq.lastfm.etl.**"]
        commands : [
            {
                readJson {
                    outputClass : java.util.Map
                }
            }
            {
                latestSongs {
                    field : timestamp
                    operator: >
                    pattern: "2011-08-03"
                }
            }
        ]
    }]

And the corresponding Java code:
@Override
protected boolean doProcess(Record record) {
    Map attachmentBody = (Map) record.get(Fields.ATTACHMENT_BODY).get(0);
    String fieldValue = attachmentBody.get(fieldName).toString();

    try {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Date fieldDate = sdf.parse(fieldValue);
        Date patternDate = sdf.parse(pattern + " 00:00:00");

        if (operator.equals(HIGHER)) {
            if (!fieldDate.after(patternDate)) {
                return true;
            }
        } else if (operator.equals(LOWER)) {
            if (!fieldDate.before(patternDate)) {
                return true;
            }
        } else if (operator.equals(EQUALS)) {
            if (fieldDate.getYear() != patternDate.getYear()
                    || fieldDate.getMonth() != patternDate.getMonth()
                    || fieldDate.getDay() != patternDate.getDay()) {
                return true;
            }
        } else {
            LOG.info("bad operator syntax");
        }
    } catch (Exception e) {
        LOG.info("parse exception: " + e.getMessage());
        return false;
    }
    record.removeAll(Fields.ATTACHMENT_BODY);
    try {
        record.put(Fields.MESSAGE, OBJECTMAPPER.writeValueAsString(attachmentBody));
    } catch (JsonProcessingException e) {
        LOG.info("parse exception: " + e.getMessage());
        return false;
    }
    return super.doProcess(record);
}

Any help is appreciated!

A: You need to compile the custom java class into a jar file. e.g. via 'mvn package' as shown here: https://github.com/kite-sdk/kite-examples/tree/master/kite-examples-morphlines
Then add the jar file to the java classpath, e.g. by copying the jar file into the lib/
 dir.