Q: resources for linux programming what are the best books or best websites to learn the linux programming for absolute beginners and for professional programmers? To be more specific topics like,
a) forking
b) Shared memory
c)exec commands
d)signals
e)scheduling algorithms (round robin,first come first serve,priority scheduling,short job first, multilevel queue scheduling, multilevel feedback queue scheduling)

A: A good book is Advanced Linux Programming, free available here
The network programming Holy Bible ;-) : UNIX network programming V1
The IPC programming: Unix network programming V2
the powerful man pages, and some books of Operative systems like either Tannenbaum's one or Stallings' one .
However Linux programming = C programming so if I were you also look a good C programming books if you are a beginner.

A: Although the focus is not programming, the Linux Documentation Project has been around for more than two decades (according to wikipedia, it was the first linux website online) and contains a lot of fundamental "how-to's" and books.  Some of the material dates back into the previous century and may have limited applicability today, but it is still a great resource.
As mentioned though, the focus is not programming, it's system administration.  You should have a look around for yourself in any case -- the material is eclectic.  The GNU C Library Manual (beware that this is not the same as the more basic GNU C Reference Manual) does discuss some of your topics in the context of the native library (fork and exec will be in chpt. 26, signals 24).  It doesn't cover threading or shared mem beyond BSD style mmap(), since those things aren't part of the base library.
The POSIX Specification is mostly a collection of man pages (usually, more informative ones than the linux system ones) that does cover shared mem and threading for POSIX compliant systems (which GNU/linux essentially is).  Man pages are probably the thing I consult most when programming.  They are not always the best introduction to a topic, but they are the definitive legalese if you need a specific answer to a specific question.  I find that if I don't understand something very well, stringing enough specific questions together  often makes things clearer than reading someone's rambling exposition on a general topic.


Q: Error: Can't set headers after they are sent Node.js and ExpressJS I am using Node.js and ExpressJS to save a mongoose model. I am getting the error of Error: Can't set headers after they are sent. I think it has to do with the line res.redirect("/dashboard/it/model"); conflicting with setRedirect({auth: '/login'}), from my route, the code in the setRedirect is below labeled. The setRedirect is from a middleware called middleware-responder that came as part of the template I am using to create Stripe user accounts. I can not remove it as far as I know. my GitHub repo I have committed all files that are not test files and are relevant (no unneeded views ect than what is already there)
Save Model
if(type=="aps"){
      var newAccessPoint = {
          name: name,
          manufacturer: manufacturer,
          model: model,
          range: range,
          bands: bands,
          channel: channel,
          poe: poe,
          notes: notes,
          signout: signout,
          author:author
        };
      // Create a new access point and save to DB
      AP.create(newAccessPoint, function(err, newlyCreated){
          if(err){
              console.log(err);
          } else {
              //redirect back to models page
              res.redirect("/dashboard/it/model");
          }
      });
    }

Route
app.post('/dashboard/it/model/new',
    setRender('dashboard/it/modelCreate'),
    setRedirect({auth: '/login'}),
    isAuthenticated,
    dashboard.getDefault,
   (req, res) => {

setRedirect code
exports.setRedirect = function(options){
  return function(req, res, next){
   if(req.redirect){
     req.redirect = _.merge(req.redirect, options);
   } else {
     req.redirect = options;
   }
   next();
 };
};

setRender code
exports.setRender = function(view){
  return function(req, res, next){
    req.render = view;

    next();
  };
};

A: That's happening because you are trying to send a response to the client when you already closed the connection.
Hard to tell by the way you are showing us your code but it seems like you are redirecting to options and then in the same request you are redirecting to dashboard/it/model

A: I pull your code from github.
I think the error message was clear. in your getDefault() middleware you are rendering a response so the server start sending data to your client and just after you try to redirect him to another url. Thats why when your comment out that middleware all work nicely.


Q: Sqlite3.Binary gives TypeError: buffer object expected I have a list which I extracted from a txt file as follows:
authors = re.match('#@(.*)', line)
if authors:
   authors_list = authors.group(1).split(",")

Now I need to insert these into my database, which should be done as follows:
for a in authors_list:
    c.execute("INSERT INTO authors(Name) VALUES (?)", (a))

But when I do that I get the following error:
ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 17 supplied.

So I did some research and found that I should change my variable a into a tuple (a, ) as such:
c.execute("INSERT INTO authors(Name) VALUES (?)", (a,))

And I also tried this:
c.execute("INSERT INTO authors(Name) VALUES (?)", ((a,)))

But got the following error:
ProgrammingError: You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings (like text_factory = str). It is highly recommended that you instead just switch your application to Unicode strings.

So I did more research and found that I should use sqlite3's Binary function. So I tried the following:
c.execute("INSERT INTO authors(Name) VALUES (?)", (sqlite3.Binary((a,))))

And got the following error:
TypeError: buffer object expected

I keep going back and forth between all three errors no mater what combination I try. Any help would be appreciated. I don't know what I'm doing wrong.

A: You are passing in a tuple, not a bytestring:
sqlite3.Binary((a,))

Create a tuple with the result of sqlite3.Binary(), having passed in just a:
(sqlite3.Binary(a),)

The whole statement is then run as:
c.execute("INSERT INTO authors(Name) VALUES (?)",
          (sqlite3.Binary(a),))

However, if this is supposed to be text, you'd normally decode the bytes to a string instead of trying to insert binary data:
c.execute("INSERT INTO authors(Name) VALUES (?)",
          (a.decode('utf8'),))

This does assume that your text is encoded using the UTF-8 codec; adjust the decoding as needed to match your data.


Q: react conditional component rendering I'm currently trying to create a React component to upload and crop an image using Croppie library.
I've found this code sample
import "croppie/croppie.css"
import { Button, Grid } from "@material-ui/core"
import * as React from "react"
import Croppie from "croppie"

export function CroppieExample() {
  const [image, setImage] = React.useState("")
  const [croppie, setCroppie] = React.useState<Croppie | null>(null)

  function handleImage(image: string) {
    setImage(image)
    const el = document.getElementById("image-helper")
    if (el) {
      const croppieInstance = new Croppie(el, {
        enableExif: true,
        viewport: {
          height: 250,
          width: 250,
        },
        boundary: {
          height: 280,
          width: 400,
       }
    });
    croppieInstance.bind({
      url: image,
    });
    setCroppie(croppieInstance)
    }
  }

  function handleSubmit(event: any) {
    event.preventDefault()
    if (croppie !== null) {
      croppie.result({type: 'base64',
      size: {
          width: 480,
          height: 480
      }}).then((blob) => {
        console.log(blob)
      }
      )
    }
  }

  return (
    <form onSubmit={handleSubmit}>
      <Grid container spacing={2}>
        {image === "" && (
            <Grid item xs={12}>
                {/* Your image upload functionality here */}
                <ImageUpload image={image} setImage={handleImage} />
            </Grid>
            )}
        {image !== "" && (
            <Grid item container justify="center" xs={12}>

            </Grid>
            )}
        <Grid container item xs={12} justify="flex-end">
          <Button color="primary" variant="contained" type="submit">
            Submit
          </Button>
        </Grid>
      </Grid>
    </form>
  )
}

I've a question regarding the conditional part of this piece of code:
In order to work, a Croppie instance must be attached to the div element "image-helper". The handleImage event is in charge of the croppieInstance creation. But by the time it is called, it seems that  is not rendered so no croppie instance can be created.
Is my assumption right?
If it's the case, what would be the React way to correct the code?
Thank you for your help

A: Yes your analysis is right. The code snippet is egregious. The correct way in React to initialize any code when DOM elements are finally available is via a callback ref.
const initImageHelper = useCallback(
  (element) => {
    if (element) {
      const croppieInstance = new Croppie(element, settings);
      croppieInstance.bind({ url: image });
      setCroppie(croppieInstance);
    }
  }, [image]
);

          {image !== "" && (
            <Grid item container justify="center" xs={12}>

            </Grid>
          )}


Q: Prove $(I-J_n)^{-1}=I-\frac{1}{n-1}J_n$ I have a question on matrices from a recent problem.

Let $J_n$ be the $n\times n$ matrix each of whose entries is $1$. Show that if $n\gt 1$, then
  $$(I-J_n)^{-1}=I-\frac{1}{n-1}J_n$$

Here's what I've tried so far:
$J_n$ is a matrix of $1$'s, so $I-J_n$ is the matrix whose diagonal entries are $0$ and $1$ elsewhere. But from here, I don't know how to take the inverse of this $n\times n$ matrix. One could use Gaussian-Jordan elimination but I don't think it helps here, it would get too complicated very quickly. Instead, I called the left-hand side of the equation $K$.
\begin{align}
(I-J_n)^{-1} & = K \\
(I-J_n)^{-1}K^{-1} & = KK^{-1} \\
(K(I-J_n))^{-1} & = I \\
(K-KJ_n)^{-1}&=I \\
I & = K-KJ_n
\end{align}
I still need to use the fact that $J_n$ contains only $1$'s but I'm not sure how to do that.
Any help in the right direction is appreciated.

A: $J_n^2=nJ_n$, so $(I-J_n)\left(I-\dfrac1{n-1}J_n\right)=I-\dfrac1{n-1}J_n-J_n+\dfrac1{n-1}J_n^2=I$

A: Simply test the multiplication $(I - J_n)\left(I - \frac{1}{n - 1}J_n\right)$:
\begin{align}
& (I - J_n)\left(I - \frac{1}{n - 1}J_n\right) \\
= & I - \frac{1}{n - 1}J_n - J_n + \frac{1}{n - 1}J_n^2 \\
= & I - \frac{n}{n - 1}J_n + \frac{n}{n - 1}J_n \\
= & I,
\end{align}
where we used $J_n^2 = nJ_n$, which can be easily verified.


Q: clean-webpack-plugin only accepts an options object I'm getting

Error: clean-webpack-plugin only accepts an options object. See:
    https://github.com/johnagan/clean-webpack-plugin#options-and-defaults-

My Webpack.config.js file looks like this:
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');

var plugins = [
    new CleanWebpackPlugin(['dist'], {}),
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.OccurenceOrderPlugin(),
    new CopyWebpackPlugin([{
        from: './src/images/',
        to: './images/'
    }]),
    new HtmlWebpackPlugin({
        inject: false,
        template: 'src/index.html'
    })
];

var config = {
    entry: [
        './src/js/main.js'
    ],

    output: {
        path: path.join(__dirname, 'dist'),
        publicPath: '/',
        filename: 'js/bundle.js',
    },

    plugins: plugins.concat([
        new ExtractTextPlugin('css/bundle.css'),
        //new webpack.optimize.UglifyJsPlugin(require('./uglifyjs.json'))
    ]),
    devServer: {
        inline: true,
        port: 8080
    },

    module: {
        loaders: [{
            test: /\.jsx?$/,
            exclude: /node_modules/,
            include: path.join(__dirname, 'src'),
            loader: 'babel',
            query: {
                presets: ['react', 'es2015']
            }},
            {
                test: /.s?css$/,
                include: path.join(__dirname, 'src'),
                loader: ExtractTextPlugin.extract('style', [
                    'css?sourceMap',
                    'postcss',
                    'sass?sourceMap'
                ])
            },
            {
                test: /\.css$/,
                include: path.join(__dirname, 'node_modules'),
                loader: 'style!css'
            }
        ]
    },
    postcss: function() {
        return [
            require('autoprefixer')({
                browsers: ['last 2 versions']
            })
        ];
    }
}
module.exports = config;

A: Like @AKX mentioned, newest version of clean-webpack-plugin doesn't accept array argument anymore.
The path which should be clearing is reading from webpack's output.path. In your example code it's here:
output: {
  path: path.join(__dirname, 'dist'),
  // rest of code
},

You should be very carefull, because someones still use pattern like this:
output: {
  path: __dirname,
  filename: './dist/bundle.js'
},

Above configuration will cause removing all files in your project!
If you need to clear only some files from webpack's output.path you should set cleanOnceBeforeBuildPatterns field in object passed into CleanWebpackPlugin constructor.

A: As you can see from the page the error message links, CleanWebpackPlugin does not accept two arguments as you're passing in:
new CleanWebpackPlugin(['dist'], {}),

Instead, just try
new CleanWebpackPlugin(),

if you don't need to pass in any options.
You may be seeing this problem if you're, say, following an older tutorial or such which uses a different version of the plugin, and the interface has changed meanwhile.


Q: Some more advanced recursion I've been looking around for awhile now, and I haven't found anything that helped me. I have to write a program that uses one method (the main method) to read in the size of/and elements of an array. Then I must write a recursive method titled "forwardsEqualBackwards" which returns true if the elements of the array can be read the same way regardless of whether the array is read forwards or backwards (it's a a test to see whether or not it's a palindrome) and false otherwise.

A: pseudocode:
bool forwardsEqualBackwards(array a, int length, int indexToLookAt=0)
{
  if (indexToLookAt >= length-indexToLookAt-1)
    return true; //reached end of recursion
  if (a[indexToLookAt] == a[length-indexToLookAt-1])
    return forwardsEqualBackwards(a,length, indexToLookAt+1); //normal recursion here
  else
    return false;
}

forwardsEqualBackwards("",0);  //returns true
forwardsEqualBackwards("a",1);  //returns true
forwardsEqualBackwards("otto",4);  //returns true
forwardsEqualBackwards("otsto",5);  //returns true
forwardsEqualBackwards("otstou",5);  //returns false

A: bool method(int start, int end)
{
     if(start<=end)
     {
           if(Array[start]!=array[end])
                 return false;
           return method(start+1, end-1)
     }
     return true;

}


Q: Simplify and summarize data table in R One of my data set is as follows
name  alias (list of alias)
x     c("R","V","Q")
y     "Z"
q     c("A", "R", "M")
w     c("C","A","R")

I would like to first simplify the table as follows
name alias
x  "R"
x  "V"
x  "Q"
y  "Z"
q  "A"
q  "R"
q  "M"
w  "C"
w  "A"
w  "R"

and later modify the data to get
alias name
"R"   c(x,q,w)
"V"   x
"Q"   x
"Z"   y
"A"  c(q,w)
"M"  q
"C"  w

How can I achieve this in R?
Here is the actual data set
> \dput(head(cases))
structure(list(caseid = c(7703415, 7758128, 7858259, 8802954,
8829620, 8847200), tcount = c(2L, 2L, 3L, 10L, 4L, 2L), helplinks = c("character(0",
"c(\"60107\", \"56085\", \"57587\", \"3000020\"", "character(0",
"character(0", "c(\"60107\", \"3000023\", \"3000020\", \"60107\", \"56085\", \"57587\"",
"character(0")), .Names = c("caseid", "tcount", "helplinks"), row.names = c(NA,
6L), class = "data.frame")

> head(cases)
   caseid tcount                                                  helplinks
1 7703415      2                                                character(0
2 7758128      2                     c("60107", "56085", "57587", "3000020"
3 7858259      3                                                character(0
4 8802954     10                                                character(0
5 8829620      4 c("60107", "3000023", "3000020", "60107", "56085", "57587"
6 8847200      2                                                character(0

A: New answer
Use cSplit from my "splistackshape" package:
cSplit(cases, "helplinks", ",", "long")[, helplinks := gsub(
  'character\\(0|c\\(|\\"', "", helplinks)][, list(
    caseid = list(caseid)), by = helplinks]
#    helplinks                          caseid
# 1:           7703415,7858259,8802954,8847200
# 2:     60107         7758128,8829620,8829620
# 3:     56085                 7758128,8829620
# 4:     57587                 7758128,8829620
# 5:   3000020                 7758128,8829620
# 6:   3000023                         8829620

Old answer
I'm assuming you're starting with something like this:
df <- data.frame(
  name = c("x", "y", "q", "w"),
  alias = I(list(c("R","V","Q"), "Z", c("A", "R", "M"), c("C","A","R")))
)
df
#   name   alias
# 1    x R, V, Q
# 2    y       Z
# 3    q A, R, M
# 4    w C, A, R

If that's the case, here's one approach using listCol_l from my "splitstackshape" package in conjunction with "data.table".
library(splitstackshape)
listCol_l(df, "alias")[, list(name = list(name)), by = alias_ul]
#    alias_ul  name
# 1:        R x,q,w
# 2:        V     x
# 3:        Q     x
# 4:        Z     y
# 5:        A   q,w
# 6:        M     q
# 7:        C     w

You don't really need "splitstackshape" for that, so if you want to remove the self-promotion part of my answer and just use "data.table", you could do:
library(data.table)
as.data.table(df)[, list(
  alias = unlist(alias)), by = name][, list(
  name = list(name)), by = alias]

A: First we clean up the "character(0"'s. Then we read in those character values that were once lists but now need to be scan-ned. Then we apply a function that makes a dataframe from every line:
good.case <- cases[ grepl("c\\(", cases$helplinks),]
 lapply( split(good.case, row.names(good.case) ), function(d){
   vec <- scan(text=gsub("c\\(|[, ]", "", d$helplinks) ,what="")
   do.call( data.frame, list(caseid=d$caseid, alias=vec) )
 }
 )
#-------
#Read 4 items
#Read 6 items
$`2`
   caseid   alias
1 7758128   60107
2 7758128   56085
3 7758128   57587
4 7758128 3000020

$`5`
   caseid   alias
1 8829620   60107
2 8829620 3000023
3 8829620 3000020
4 8829620   60107
5 8829620   56085
6 8829620   57587

 expanded <- lapply( split(good.case, row.names(good.case) ), function(d){
    vec <- scan(text=gsub("c\\(|[, ]", "", d$helplinks) ,what="")
    do.call( data.frame, list(caseid=rep(d$caseid, length(vec)), alias=vec) )
  }
  )
#Read 4 items
#Read 6 items

Now we bind the dataframes together:
 do.call(rbind, expanded)
#---------------
     caseid   alias
2.1 7758128   60107
2.2 7758128   56085
2.3 7758128   57587
2.4 7758128 3000020
5.1 8829620   60107
5.2 8829620 3000023
5.3 8829620 3000020
5.4 8829620   60107
5.5 8829620   56085
5.6 8829620   57587

But only half the way there I suppose. No point in pursuing further with Ananda's 5 caret answer sitting there.


Q: How to convert NSDictionary to custom object I have a json object:
@interface Order : NSObject

@property (nonatomic, retain) NSString *OrderId;
@property (nonatomic, retain) NSString *Title;
@property (nonatomic, retain) NSString *Weight;

- (NSMutableDictionary *)toNSDictionary;
...

- (NSMutableDictionary *)toNSDictionary
{

    NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
    [dictionary setValue:self.OrderId forKey:@"OrderId"];
    [dictionary setValue:self.Title forKey:@"Title"];
    [dictionary setValue:self.Weight forKey:@"Weight"];

    return dictionary;
}

In string this is:
{
  "Title" : "test",
  "Weight" : "32",
  "OrderId" : "55"
}

I get string JSON with code:
NSMutableDictionary* str = [o toNSDictionary];

    NSError *writeError = nil;

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:str options:NSJSONWritingPrettyPrinted error:&writeError];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

Now I need to create and map object from JSON string:
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *e;
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:nil error:&e];

This returns me filled NSDictionary.
What should I do to get object from this dictionary?

A: Assuming that your properties names and the dictionary keys are the same, you can use this function to convert any object
- (void) setObject:(id) object ValuesFromDictionary:(NSDictionary *) dictionary
{
    for (NSString *fieldName in dictionary) {
        [object setValue:[dictionary objectForKey:fieldName] forKey:fieldName];
    }
}

A: this will be more convenient for you :
 - (instancetype)initWithDictionary:(NSDictionary*)dictionary {
        if (self = [super init]) {
            [self setValuesForKeysWithDictionary:dictionary];}
        return self;
    }

A: Add a new initWithDictionary: method to Order:
- (instancetype)initWithDictionary:(NSDictionary*)dictionary {
    if (self = [super init]) {
        self.OrderId = dictionary[@"OrderId"];
        self.Title = dictionary[@"Title"];
        self.Weight = dictionary[@"Weight"];
    }
    return self;
}

Don't forget to add initWithDictionary's signature to Order.h file
In the method where you get JSON:
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *e;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:nil error:&e];
Order *order = [[Order alloc] initWithDictionary:dict];

A: If the property names on your object match the keys in the JSON string you can do the following:
To map the JSON string to your Object you need to convert the string into a NSDictionary first and then you can use a method on NSObject that uses Key-Value Coding to set each property.
NSError *error = nil;
NSData *jsonData = ...; // e.g. [myJSONString dataUsingEncoding:NSUTF8Encoding];
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingOptionsAllowFragments error:&error];

MyObject *object = [[MyObject alloc] init];
[object setValuesForKeysWithDictionary:jsonDictionary];

If the keys do not match you can override the instance method of NSObject -[NSObject valueForUndefinedKey:] in your object class.
To map you Object to JSON you can use the Objective-C runtime to do it automatically. The following works with any NSObject subclass:
#import <objc/runtime.h>

- (NSDictionary *)dictionaryValue
{
    NSMutableArray *propertyKeys = [NSMutableArray array];
    Class currentClass = self.class;

    while ([currentClass superclass]) { // avoid printing NSObject's attributes
        unsigned int outCount, i;
        objc_property_t *properties = class_copyPropertyList(currentClass, &outCount);
        for (i = 0; i < outCount; i++) {
            objc_property_t property = properties[i];
            const char *propName = property_getName(property);
            if (propName) {
                NSString *propertyName = [NSString stringWithUTF8String:propName];
                [propertyKeys addObject:propertyName];
            }
        }
        free(properties);
        currentClass = [currentClass superclass];
    }

    return [self dictionaryWithValuesForKeys:propertyKeys];
}

A: The perfect way to do this is by using a library for serialization/deserialization
many libraries are available but one i like is
JagPropertyConverter
https://github.com/jagill/JAGPropertyConverter
it can convert your Custom object into NSDictionary and vice versa
even it support to convert dictionary or array or any custom object within your object (i.e Composition)
JAGPropertyConverter *converter = [[JAGPropertyConverter alloc]init];
converter.classesToConvert = [NSSet setWithObjects:[Order class], nil];

@interface Order : NSObject

@property (nonatomic, retain) NSString *OrderId;
@property (nonatomic, retain) NSString *Title;
@property (nonatomic, retain) NSString *Weight;
@end

//For Dictionary to Object (AS IN YOUR CASE)

NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
[dictionary setValue:self.OrderId forKey:@"OrderId"];
[dictionary setValue:self.Title forKey:@"Title"];
[dictionary setValue:self.Weight forKey:@"Weight"];

Order *order = [[Order alloc]init];
[converter setPropertiesOf:order fromDictionary:dictionary];

 //For Object to Dictionary

Order *order = [[Order alloc]init];
order.OrderId = @"10";
order.Title   = @"Title;
order.Weight  = @"Weight";

NSDictionary *dictPerson = [converter convertToDictionary:person];

A: Define your custom class inherits from "AutoBindObject". Declare properties which has the same name with keys in NSDictionary. Then call method:
[customObject loadFromDictionary:dic];

Actually, we can customize class to map different property names to keys in dictionary. Beside that, we can bind nested objects.
Please have a look to this demo. The usage is easy:
https://github.com/caohuuloc/AutoBindObject


Q: Как убрать поле выберите файл? Подскажите пожалуйста, как убрать(спрятать) кнопку "Выберите файл"?

                              <input type="file" name="file">

A: .file-upload label input { display: none; }

или
.file-upload label input { opacity: 0; }

не забудьте обернуть в , если не будете вставлять в css файл

A: Есть несколько способов спрятать элемент

var elem = document.getElementsByClassName("deleted")[0];
elem.parentNode.removeChild(elem);
Как ничего не было

    <input type="file" name="file" style="display:none;">

Возможно взаимодействовать но невидим и занимает место

    <input type="file" name="file" style="opacity:0;">

Также возможно взаимодействовать но невидим и занимает место

    <input type="file" name="file" style="visibility:hidden;">

Элемент удален, полезно если не нужно лишнее GET или POST поле

    <input type="file" name="file" style="visibility:hidden;">

Невозможно взаимодействовать но невидим и занимает место

    <input type="file" name="file" style="visibility:hidden;" onclick="return false">


Q: How am I supposed to use the -audiodev option in QEMU? There is a thread Fwd: How am I supposed to use the -audiodev option?, but unfortunately it does not contain an answer. I use QEMU on Windows, and when I run my image in QEMU qemu-system-arm.exe , I get:
dsound: Could not initialize DirectSound
dsound: Reason: No sound driver is available for use, or the given GUID is not a valid DirectSound device ID
sdl: SDL_OpenAudioDevice for playback failed
sdl: Reason: WASAPI can't find requested audio endpoint: Element not found.
sdl: SDL_OpenAudioDevice for playback failed
sdl: Reason: WASAPI can't find requested audio endpoint: Element not found.
audio: Failed to create voice `lm4549.out'

So, I want to disable audio completely, and get rid of those messages.
So, I add this (found via https://unix.stackexchange.com/questions/564844/disable-sound-when-using-spice-with-kvm-libvirt) to my command line:
-audiodev id=none,driver=none

This then results with:
audio: Device lm4549: audiodev default parameter is deprecated, please specify audiodev=none

As recommended in that thread, I tried:
C:\bin\qemu\qemu-system-arm.exe -audio-help
Environment variable based configuration deprecated.
Please use the new -audiodev option.

Equivalent -audiodev to your current environment variables:
(Since you didn't specify QEMU_AUDIO_DRV, I'll list all possibilities)
-audiodev id=dsound,driver=dsound
-audiodev id=sdl,driver=sdl
-audiodev id=none,driver=none

Ok, I then try this instead of the above:
audiodev=none

... and I get:
qemu-system-arm.exe: audiodev=none: drive with bus=0, unit=0 (index=0) exists

Ok, I try this:
-audiodev=none

... and I get:
qemu-system-arm.exe: -audiodev=none: invalid option

So ... how do I set audio device to none in QEMU?


Q: Lagrange Interpolation With Expand Returning a Wrong Result in Maxima Recently I've been experimenting with polynomial interpolation to create a simple model of a battery discharge curve. My mathematics knowledge is a bit limited and this is part of my quest to find interesting things that my professors never mentioned.
I've found something very interesting while playing around with Maxima, if I use 10 points in the lagrange function I get the right result, but when I use the expand function I get the wrong result.
(%i1) load(interpol)$

(%i2) p:[[0.000000,9.429000],[10.000000,8.911000],[20.000000,8.707000],[30.000000,8.581000],[40.000000,8.502000],[50.000000,8.430000],[60.000000,8.356000],[70.000000,8.287000],[80.000000,8.228000],[90.000000,8.185000],[100.000000,8.144000],[110.000000,8.100000],[120.000000,8.038000],[130.000000,7.990000],[140.000000,7.960000],[150.000000,7.934000],[160.000000,7.905000],[170.000000,7.877000],[180.000000,7.844000],[190.000000,7.785000],[200.000000,7.728000],[210.000000,7.686000],[220.000000,7.653000],[230.000000,7.613000],[240.000000,7.580000],[250.000000,7.549000],[260.000000,7.524000],[270.000000,7.498000],[280.000000,7.469000],[290.000000,7.438000],[300.000000,7.381000],[310.000000,7.336000],[320.000000,7.279000],[330.000000,7.190000],[340.000000,7.113000],[350.000000,7.034000],[360.000000,6.906000],[370.000000,6.763000],[380.000000,0.011100]];
(%o2) [[0.0, 9.429], [10.0, 8.911], [20.0, 8.707], [30.0, 8.581],
[40.0, 8.502], [50.0, 8.43], [60.0, 8.356], [70.0, 8.287], [80.0, 8.228],
[90.0, 8.185], [100.0, 8.144], [110.0, 8.1], [120.0, 8.038], [130.0, 7.99],
[140.0, 7.96], [150.0, 7.934], [160.0, 7.905], [170.0, 7.877], [180.0, 7.844],
[190.0, 7.785], [200.0, 7.728], [210.0, 7.686], [220.0, 7.653],
[230.0, 7.613], [240.0, 7.58], [250.0, 7.549], [260.0, 7.524], [270.0, 7.498],
[280.0, 7.469], [290.0, 7.438], [300.0, 7.381], [310.0, 7.336],
[320.0, 7.279], [330.0, 7.19], [340.0, 7.113], [350.0, 7.034], [360.0, 6.906],
[370.0, 6.763], [380.0, 0.0111]]
(%i3) l:lagrange(p);
<< Expression too long to display! >>
(%i4) fl(x) := ev(l);
(%o4)                           fl(x) := ev(l)
(%i5) fl(110);
(%o5)                                 8.1
(%i6) e:expand(l);
<< Expression too long to display! >>
(%i7) fe(x) := ev(e);
(%o7)                           fe(x) := ev(e)
(%i8) fe(110);
(%o8)                          134287.8427835584

Why do I get this massive difference when I use the expand function? Is there a way to fix this?

A: Interpolating  $n$ equally spaced points with an $n-1$ degree polynomial will almost always result in a polynomial with HUGE oscillations$^*$. You would do better to use a low degree spline or to try to find the nature of the data you are trying to model and use that imformation to find a more appropriate function than a polynomial.
$^*$ Try plotting $x(x-1), x(x-1)(x-2), x(x-1)(x-2)(x-3), \dots$and see what kind of plots you get.


Q: Замена символов по краям каждого слова Новое Я не понимаю, почему звёздочки не меняются на em? Я же сказал найти слово, если оно начинается на * и заканчивается на *
echo preg_replace('#\b(?<=\*)(.+)(?=\*)\b#', '$1', 'This text has *two* *italic* bits');

Почему выводятся только последние буквы слова, не полностью слово?
echo preg_replace('#\*([a-z])+\*#', '$1', 'This *text* is *italic*');

A: В случае с \b(?<=\*)(.+)(?=\*)\b звездочки являются частью предварительных блоков просмотра, т.е. они не становятся частью заменяемой строки. Тут ещё можно добавить то, что (.+) — "жадный шаблон", т.е. найдёт все от первой звездочки до последней, (.+?) выглядит предпочтительнее, так как найдет текст от первой звездочки до ближайшей справа.
В #\*([a-z])+\*# у вас захватывающая подмаска захватывает только по одной букве, квантификатор должен быть внутри подмаски.
Используйте
preg_replace('#\*([a-z]+)\*#', '$1', 'This *text* is *italic*');

См. онлайн-демо.
Если необходимо добавить поддержку всех букв Юникода:
preg_replace('#\*(\p{L}+)\*#u', '$1', 'This *text* is *italic*');

где \p{L} находит любую букву Юникода.
Если стоит задача найти звездочку, после которой стоит буква, и далее любой текст, завершающийся буквой, после которой стоит звездочка, можно использовать
preg_replace('#\*(\p{L}(?:.*?\p{L})?)\*#u', '$1', 'This *text* is *italic*');

или
preg_replace('#\*(\p{L}(?:[^*]*\p{L})?)\*#u', '$1', 'This *text* is *italic*');

Тут \p{L}(?:[^*]*\p{L})? найдет букву, после которой опционально следует 0 и более любых символов, отличных от *, и вновь любая буква. Т.е. найдутся *Да, нет*,
 а * \\ * найдены не будут.


Q: How to replace a sentence with space on the basis of a pattern if it occurs in the middle of a sentence Suppose I have a line like this:
aaaa ---- bbbb

I want to erase the ----bbbb part, but I want to keep the aaaa part as it is in the file. How can I do it?

A: Using sed:
s='aaaa ---- bbbb'
echo "$s"|sed 's/--* bb*/foo/'
aaaa foo


Q: How to use API Key in Google Speech grpc Java library How do I use an API Key in Google Speech grpc Java or any other library. For HTTP request I am able to see that we can append key=API_KEY as mentioned in
https://cloud.google.com/docs/authentication/api-keys.
But for the given libraries (https://cloud.google.com/speech/docs/reference/libraries#client-libraries-install-java) all examples show how to use the Credential file.
Please help.

A: Use metadata with a key of X-Goog-Api-Key. See this other answer. If you have API restrictions, you may need additional headers. For example, an iOS example mentioned a bundle id restriction.


Q: Check size(variable) of all string in List using Java Stream I have a list of strings (given below), each string required to be in a specific size(Variable).
for e.g.
{"abc","xyz","def"}

this list elements has a fixed size of 3 and i would like to check if this size is not exceed to X=3 or 4.
Requirement is to return a boolean if that size exceed or lower the size. I refereed Java Stream docs couldn't find any relevant information.
Does Java Stream API is useful to solve this or should i solve it in classical way.

A: You can use the allMatch method like this:
int correctSize = 3;
List<String> myStrings = List.of("abc", "xyz", "def");
boolean allAreCorrectSize = myStrings.stream()
    .allMatch(s -> s.length() == correctSize);

A: Here both implementation, both can be used

*

*Using Stream API

public static boolean isValidUsingStreamAPI(List<String> list){
        int correctSize=3;
        return list.stream().allMatch(f->f.length()==correctSize);
}

*Classic Way

public static boolean isValidClassic(List<String> list){
        int correctSize=3;
        for(String s:list){
            if(s.length()!=correctSize)return false;
        }
        return true;
    }


Q: html2canvas is not working in Safari browser: Taking Screenshot I just want to take a screenshot of any HTML element ( "container" div in my case ).
it works fine in Chrome and Firefox browsers but not in Safari.
Following is how I am doing it:
<!doctype HTML>

Take screenshot of webpage with html2canvas

DIV 1

DIV 2

DIV 3

<input type='button' id='but_screenshot' value='Take screenshot' onclick='screenshot();'>

it shows the following error in the Safari browser:
and here is the specific part of code of html2canvas.js (it is by-default file I have just used).

A: we just have to enable the CORS in safari-mac browser. So, we'll do it by modifying our function screenshot() as follows:
function screenshot(){
    html2canvas(document.getElementById('id-screenshot'),{
        allowTaint: true,
        useCORS : true,
    }).then(function(canvas) {
        console.log("canvas: " + canvas);
        document.getElementById('test-s').appendChild(canvas);
    });
}


Q: how to make multiple tkinter buttons to press together while as user presses any one of them? how to make multiple tkinter buttons to press together while as user presses any one of them?
To be clear i want multiple tkinter buttons look like pressed at the same time user presses any one of them .
i tried this:
from tkinter import *
from tkinter import ttk

class one_for_all:
    def __init__(self):
        self.root = Tk()
        self.root.title("One For All, All For One")

        self.frame = ttk.Frame(self.root, padding="3 3 12 12")
        self.frame.grid(row=0, column=0)
        self.root.rowconfigure(0, weight=1)
        self.root.columnconfigure(0, weight=1)

        self.btn1 = ttk.Button(self.frame, text="btn1", command=lambda : self.push_all(1))
        self.btn2 = ttk.Button(self.frame, text="btn2", command=lambda : self.push_all(2))
        self.btn3 = ttk.Button(self.frame, text="btn3", command=lambda : self.push_all(3))
        self.btn4 = ttk.Button(self.frame, text="btn4", command=lambda : self.push_all(4))

        self.btn1.grid(row=0, column=0, sticky="nsew")
        self.btn2.grid(row=0, column=1, sticky="nsew")
        self.btn3.grid(row=1, column=0, sticky="nsew")
        self.btn4.grid(row=1, column=1, sticky="nsew")

        for child in self.frame.winfo_children():
            child.grid_configure(padx=5, pady=5)

    def push_all(self, caller):
        if caller != 1:
            self.btn1.configure(command=lambda : None)
            self.btn1.event_generate("<ButtonPress-1>")
            self.btn1.event_generate("<ButtonRelease-1>")
            self.btn1.configure(command=lambda: self.push_all(1))
        if caller != 2:
            self.btn2.configure(command=lambda : None)
            self.btn2.event_generate("<ButtonPress-1>")
            self.btn2.event_generate("<ButtonRelease-1>")
            self.btn2.configure(command=lambda: self.push_all(2))
        if caller != 3:
            self.btn3.configure(command=lambda : None)
            self.btn3.event_generate("<ButtonPress-1>")
            self.btn3.event_generate("<ButtonRelease-1>")
            self.btn3.configure(command=lambda: self.push_all(3))
        if caller != 4:
            self.btn4.configure(command=lambda : None)
            self.btn4.event_generate("<ButtonPress-1>")
            self.btn4.event_generate("<ButtonRelease-1>")
            self.btn4.configure(command=lambda: self.push_all(4))

    def mainloop(self):
        self.root.mainloop()

if __name__ == "__main__":
    one_for_all().mainloop()

but it looks like only button 4 is stimulated by other buttons not all 4 :(
Note: i just started the tkinter without any prior experience of GUI
Thanks in Advance.

A: You can do something like this:
from tkinter import Tk, Button

class MainWindow(Tk):
    def __init__(self):
        super().__init__()

        self.buttons = list()
        for i in range(4):
            button = Button(self, text=f'Button {i}')
            button.bind('<ButtonPress-1>', self.press)
            button.bind('<ButtonRelease-1>', self.release)
            button.pack(fill='both')
            self.buttons.append(button)

    def press(self, event=None):
        for btn in self.buttons:
            btn.config(relief='sunken')

    def release(self, event=None):
        for btn in self.buttons:
            btn.config(relief='raised')

if __name__ == '__main__':
    MainWindow().mainloop()

It will visually make them appear to be clicked at once.
You can simply inherit from Tk and it will reduce the code written a bit since instead of self.root it would simply be just self and the features would be inherited and other stuff, for example, don't need to define mainloop as it is already inherited.
Also:
I strongly suggest following PEP 8 - Style Guide for Python Code. Function and variable names should be in snake_case, class names in CapitalCase. Have two blank lines around function and class declarations.
I strongly advise against using wildcard (*) when importing something, You should either import what You need, e.g. from module import Class1, func_1, var_2 and so on or import the whole module: import module then You can also use an alias: import module as md or sth like that, the point is that don't import everything unless You actually know what You are doing; name clashes are the issue.


Q: Multi Tenant Identity Is there any way to declare identity partitioned by tenant id?
For example I want to have this structure:
tenant_id | record_id (auto increment)
---------------------
      1   |   1
      1   |   2
      1   |   3
      1   |   4
      2   |   1
      2   |   2

A: No, there is no means of partitioning either an IDENTITY or SEQUENCE. In order to do this you would have to create a table to manage TenantID and RecordID for this table. Then you would need a function that accepts TenantID and will return RecordID. This means that you need to insert via a stored procedure that can grab that value and then do the INSERT, or maybe you can get away with an INSTEAD OF trigger, but I am not sure about that given that both TenantID and RecordID need to be part of the PK.
And if you want this pattern to apply to all tables then you would need to duplicate that custom sequence per each table. This is ok for maybe a few tables, but not more than that.
There are rare occasions when this type of behavior is desirable, but the current reason for requesting this seems a bit suspect (noted in a comment on the question):

for capacity...1 mil record with id partitioned by 50 tenants will have highest id around 20k, while not partitioned will have highest id of 1 mil.

This is not (or at least should not be) a valid concern. The INT datatype has a capacity of just under 4.3 billion values. If you start the IDENTITY (i.e. the "seed") at 1, then you get half that range since this is a signed INT and not an unsigned INT. If you want all 4,294,967,296 values, then use IDENTITY(-2147483648, 1).


Q: Receiving "error: conflicting types for 'function'" I am creating a program to convert from binary, decimal, hex, and oct to any one of those options.  For hex, I need a way to format values greater than 9 into one of A, B, C, D, E, F.  Since this will be repeated in several functions, I decided to make the following function:
char hexRepresentation(double n){
    if(n > 9){
        if(n==10) return 'A';
        if(n==11) return 'B';
        if(n==12) return 'C';
        if(n==13) return 'D';
        if(n==14) return 'E';
        if(n==15) return 'F';
    }

    return (char)n;
}

However, when I try to compile, I receive the error

conflicting types for 'hexRepresentation'

I'm utterly new at C, coming from Java, and am banging my head against a wall over what should be the simplest things to implement.  Any help would be greatly appreciated!

A: You don't get a declaration kind-of error because in C, when you do not forward declare a function most compilers assume an extern function that returns an int type. Actually the compiler should warn you about this (most do). Then later on when the compiler actually reaches the function implementation it finds a different return type, in this case a char, and then throws the "conflicting type" error. Just forward declare all the functions to avoid this kind of errors.
About what would be the best way somthing like following code woudl yield a similar result:
if (n > 9)
{
   return('A' + (n - 10));
}

A: Whatever you are doing in the code posted, you are not using double datatype at all, within the function. And from the function return type, it appears you will never see the return value >127.
This code highlights some issues:(This is just illustrative)
char hexRepresentation(double n){
    if(n > 9){//comparing (double>int). Bad.
        if(n==10) return 'A';
        if(n==11) return 'B';
        if(n==12) return 'C';//You wrote if(double == int). Bad.
        if(n==13) return 'D';
        if(n==14) return 'E';
        if(n==15) return 'F';
    }

    return (char)n; //again unsafe downgrade from 8 bytes double to 1 byte char.
}

Even if you fix your compiler error, you may not get the desired results always, due to such dangerous usage of datatype in the function.
To know why its bad, look here:
http://www.cygnus-software.com/papers/comparingfloats/Comparing%20floating%20point%20numbers.htm
I would use fabs(n) instead of n everywhere in that function body.
And the error "conflicting types for 'hexRepresentation'" will be shown when there exists a prior declaration or definition of the same named function hexRepresentation before this function definition. Also, if you do not declare a function and it only appears after being called, it is automatically assumed to be int by the compiler.
So, declare and define your function before main()
or declare before main() and define the function anywhere else in the file, but, with the same function prototype.
Do:
 char hexRepresentation(double); //Declaration before main
 main()
 {
   ...
 }
 char hexRepresentation(double n){//Definition after main
 ...
 }

Or
 char hexRepresentation(double n){ //Declaration and definition before main
  ...
 }

 main()
 {
    ...
 }

A: Just create one stack ( for char) which has push and pop functions. I am not returning the value just printing it there in the same function. (have implemented for integral values only)
#define max 100
char a[max];

void hex(int n)
{
 while(n>0)
 {
 int rem = n%16;
 if (rem<10)
   push(rem+'0');
 elsif(rem >=10 && rem <16)
   {
     switch(rem)
     {
       case 10:
         push('A');break;
         case 11:
         push('B');break;
         case 12:
         push('C');break;
         case 13:
         push('D');break;
         case 14:
         push('E');break;
         case 15:
         push('F');break;
     }
    else
       n=n/16;
   }
   }
   i=0;
   while(top>-1)
     a[i++]=pop();
   i=0;
   while(a[i]!='\0')
     printf("%c",a[i++]);
}

Is it helpful ?


Q: 11 LEFT JOIN s make query very slow I have  this  big  query it  contain  11 LEFT  JOINS  .  when  i run  it.  it get  12s  to  return  result  .  is  some  one  can assist me to  make  speed this  query  that big  help.  um  new  to  sql  code.  i  attache  image   of EXPLAIN   result
SELECT `idclients`, `clientsNameFirst`, `clientsNameLast`, `clientsEmail`, `clientsTelNoPersonalMobile`
FROM `clients`
LEFT JOIN `experienced` ON `experienced`.`clients_idclients` = `clients`.`idclients`
LEFT JOIN `designation` ON `designation`.`iddesignation` = `experienced`.`designation_iddesignation`
LEFT JOIN `industry` ON `industry`.`idindustry` = `experienced`.`industry_idindustry`
LEFT JOIN `company` ON `company`.`idcompany` = `experienced`.`company_idcompany`
LEFT JOIN `job_category` ON `job_category`.`idjobCategory`=`experienced`.`job_category_idjobCategory`
LEFT JOIN `academic_qualifications` ON `academic_qualifications`.`clients_idclients` = `clients`.`idclients`
LEFT JOIN `qulification` ON `qulification`.`idqulification` = `academic_qualifications`.`qulification_idqulification`
LEFT JOIN `institute` ON `institute`.`idinstitute` = `academic_qualifications`.`institute_idinstitute`
LEFT JOIN `client_tag` ON `client_tag`.`clients_idclients` = `clients`.`idclients`
LEFT JOIN `tag` ON `tag`.`idtag` = `client_tag`.`tag_idtag`
LEFT JOIN `cv` ON `cv`.`clients_idclients` = `clients`.`idclients`
WHERE (   `clients`.`fullName` LIKE '%Anti money laundering executive%'
       OR `clients`.`clientsEmail` LIKE '%Anti money laundering executive%'
       OR `clients`.`clientsTelNoPersonalMobile` LIKE '%Anti money laundering executive%'
       OR `designation`.`designationName` LIKE '%Anti money laundering executive%'
       OR `cv`.`cvName` LIKE '%Anti money laundering executive%'
       OR `industry`.`industryName` LIKE '%Anti money laundering executive%'
       OR `company`.`companyName` LIKE '%Anti money laundering executive%'
       OR `qulification`.`qulificationName` LIKE '%Anti money laundering executive%'
       OR `institute`.`instituteName` LIKE '%Anti money laundering executive%'
       OR `job_category`.`jobCategoryName` LIKE '%Anti money laundering executive%'
       OR `tag`.`tagName` LIKE '%Anti money laundering executive%' )
AND `clients`.`status_idstatus` != '10'
AND `clients`.`clientsAge` >= '0'
AND `clients`.`clientsAge` <= '100'
AND `clients`.`clientsOtherQualifications` = '1'
GROUP BY `clients`.`idclients`
ORDER BY `clients`.`idclients` DESC
 LIMIT 30

after  run  this  code  with   EXPLAIN   i got  this  result.

AND  this  is  my  db

This  is  my client  table stretcher

A: 1. Solution part one:
First of all, do not write numeric values as strings (avoid conversion). This is what these three lines should be:
AND `clients`.`status_idstatus` != 10
AND `clients`.`clientsAge` >= 0
AND `clients`.`clientsAge` <= 100
AND `clients`.`clientsOtherQualifications` = 1

2. Solution part two:
Second, try to make your query SARGable, so that it can use indexes and be faster.
(read more here: What makes a SQL statement sargable? )
Instead of using a non-SARGable argument, try to search like this:
WHERE (   `clients`.`fullName` LIKE 'Anti money laundering executive%'
   OR `clients`.`clientsEmail` LIKE 'Anti money laundering executive%'
   OR `clients`.`clientsTelNoPersonalMobile` LIKE 'Anti money laundering executive%'
   OR `designation`.`designationName` LIKE 'Anti money laundering executive%'
   OR `cv`.`cvName` LIKE 'Anti money laundering executive%'
   OR `industry`.`industryName` LIKE 'Anti money laundering executive%'
   OR `company`.`companyName` LIKE 'Anti money laundering executive%'
   OR `qulification`.`qulificationName` LIKE 'Anti money laundering executive%'
   OR `institute`.`instituteName` LIKE 'Anti money laundering executive%'
   OR `job_category`.`jobCategoryName` LIKE 'Anti money laundering executive%'
   OR `tag`.`tagName` LIKE 'Anti money laundering executive%' )

A: Start over.
Build a table of all the strings in a single TEXT column.  Use a FULLTEXT index on it.  Let that be the search table.  After finding id from that table, then do look up just those ids and do the JOINs without the LIKEs.
CREATE TABLE Search (
    idclient INT NOT NULL,      -- for JOINing to clients.idclient
    stuff MEDIUMTEXT NOT NULL,  -- all the strings collected together
    PRIMARY KEY(idclient),
    FULLTEXT(stuff)
) ENGINE=InnoDB;

SELECT ...
    FROM Search AS s
    JOIN client AS c USING(idclient)
    LEFT JOIN ... -- without the LIKE
    WHERE MATCH(s.stuff) AGAINST('+Anti +money +laundering +executive' IN BOOLEAN MODE)
      AND c.status_idstatus...
      AND ...

The MATCH will take charge and whittle down the rows to very few, thereby making the rest of the query run fast.
There are 3 things conspiring to make you query slow:

*

*OR -- makes indexing useless

*Leading wildcards in LIKE -- making indexing useless

*Scattering all the strings across multiple tables -- requiring going off to all of them without knowing if there is anything useful there.

That is, the LEFT JOIN (contrary to what the titles suggests) is not the primary villain.
It might also be better to remove the Age test (etc) when they are not applicable.


Q: Using sed inside php script is causing unexpected T_STRING error I'm adding a line to my php script:
exec('sed -i 1i'MAILTO=""' /var/spool/cron/' '.$clientName.');

But it shows me an error:
PHP Parse error:  syntax error, unexpected T_STRING in /home/admin/myproject.pl/newclient/main.php on line 368

Parse error: syntax error, unexpected T_STRING in /home/admin/myproject.pl/newclient/main.php on line 368

A: I think the error says it quite well. You have a syntax error.
Perhaps this is what you wanted?
exec('sed -i \'1i MAILTO=""\'  /var/spool/cron/'.$clientName);


Q: Proving connectedness Suppose $S$ is a set, any pair of points of $S$ ($P,Q$ assume) can be contained in a connected subset of $S$.  Show $S$ is also connected.
I tried to use the polygonal chain theorem(Every open set can be connected by a polygonal chain.) but we don't know if $S$ is an open set.
Using the original definition of connectedness seems really abstract...
any help?

A: Picture: If $S$ had two separate pieces, pick a point in each piece. Put these two points in a connected subset (using the assumption), and conclude they really weren't in separate pieces.
Formalization: Suppose that $S = U \cup V$ with $U$ and $V$ open, disjoint, non-empty subsets of $S$. Choose $p \in U$, $q \in V$ and $A \subseteq S$ containing $p, q$ with $A$ connected. Consider the sets $A \cap U$ and $A \cap V$, and try to derive a contradiction.

A: I will use the fact that if $X$ is a space, $x$ a point, and $A$ and $B$ two connected subspaces of $X$ both containing $x$, then $A\cup B$ is connected. (This holds more generally for any arbitrary union.)
Fix some point $x$ in $S$, and for each element $y$ of $S$, let $S_y$ denote a connected subspace of $S$ containing $x$ and $y$.  Then $S=\bigcup_{y\in S}{S_y}$ is connected as it is a union of connected subspaces all containing a common point ($x$).

A: Suppose S is a set, any pair of points of S (P,Q assume) can be contained in a connected subset of S.
I think you can still use the polygonal chain theorem, but I think you've slightly misquoted it:
Polygonal Chain Theorem: Let G be an open set.  Then G is connected if and only if every pair of points of G can be connected by a polygonal chain in G. (courtesy of Michael Henle's Combinatorial Introduction to Topology)
If each for each arbitrary pair $P_1$, $P_2$  in S is contained in a connected subset $G$ of S, then (by the Polygonal Chain Theorem) every pair of points in $G$ can be connected by a polygonal chain in $G$.  Then there exists a polygonal chain connecting $P_1$ and $P_2$, and hence a polygonal chain exists connecting any pair of points in S.  Hence, by the Polygonal Chain Theorem, S is connected.


Q: Is it possible to center align a number in a diamond? I'm trying to center align this 1 in the diamond, but I can't figure out how to. Is this even possible? Please help...

.num {
  width: 0;
  height: 0;
  border: 15px solid transparent;
  border-bottom-color: pink;
  position: relative;
  top: -15px;
  text-align: center;
  color: white;
  font-weight: bold;
  vertical-align: center;
}

.num:after {
  text-align: center;
  content: '';
  position: absolute;
  left: -15px;
  top: 15px;
  width: 0;
  height: 0;
  border: 15px solid transparent;
  border-top-color: pink;
}

1

A: Use clip-path

.num {
  background:pink;
  display:inline-flex;
  font-size:20px;
  width:80px;
  height:80px;
  align-items:center;
  justify-content:center;
  clip-path:polygon(50% 0,100% 50%,50% 100%,0 50%);
}

1

A: Or if you don't want to play with clips than you can use the following:

1

CSS
.num {
  width: 0;
  height: 0;
  border: 15px solid transparent;
  border-bottom-color: pink;
  position: relative;
  top: -15px;
  text-align: center;
  color: white;
  font-weight: bold;
  vertical-align: center;
}

.num span {
  width: 20px !important;
  height: 40px !important;
  position: absolute;
  margin-left: -10px;
  vertical-align: center;
  margin-top: 5px;
  z-index: 1
}

.num:after {
  text-align: center;
  content: '';
  position: absolute;
  left: -15px;
  top: 15px;
  width: 0;
  height: 0;
  border: 15px solid transparent;
  border-top-color: pink;
}

But be aware: this only works if you have fix sizes. If you use percentage, than you have to always calculate the margins/paddings.


Q: Am I able to complement a virtual function of subclasses? i have a question. Lets say i have this virtual function in main class:
virtual void h_w() { cout << "Hello, wolrd!" << endl; }

And Im doing with the same function that:
void h_w() { cout << "Today is: " << math.rand(); << endl; }

Am I allowed to do that? I mean, can i change body of main function like I want in subclasses? Thanks.

A: Assuming you mean you want something like this:
class base {
public:
    virtual void h_w() { std::cout << "Hello world!\n"; }
};

class derived : public base {
public:
    void h_w() { std::cout << "Today is: " << rand() << "\n"; }
};

int main() {
    std::unique_ptr<base> b = std::make_unique<derived>();

    b->h_w();
}

...then yes, C++ supports that. In fact, this is pretty much a canonical demonstration of virtual functions, at least if you change names to (for example) "animal" as the base class and "duck" as the derived class, and have them print out something like "generic animal" and "duck" respectively. For the record, it's probably worth noting that most example based on animals are more or less broken in various ways, such as animals simply not following simple sets of rules like we expect code to.
A better example, would be something like a base class defining a generic interface to a database that allows things like reading a record, writing a record, and finding a set of records that satisfy some criteria. The derived class could then (for example) provide an implementation to carry out those "commands" in terms of some specific type of database--perhaps SQL, or perhaps some simple key/value storage engine, but the client doesn't know or care, beyond minor details like performance.
As to why this is better: first of all, because it corresponds much more closely to things you're likely to really do with a computer. Second, because we can define databases to really follow our rules and fulfill the obligations we set. With animals, we're stuck with all sorts of exceptions to any meaningful rule we might try to make, as well as the simple fact that (of course) being able to make a Duck say "quack" and a dog say "bow wow" isn't really very useful (and in the rare case that it is useful, we probably just want to save/retrieve its sound as some sort of blob, not define an entire new type to encode something better stored as data).


Q: What is special in /Applications/ folder? What happens when an .app bundle going copy to the /Applications/ folder? Are there any processes starting, any preferences copied to /Library/ ? Is a copy to /Applications/ folder a special trigger/event for the OS X?
I found that if I just copy Xcode then com.apple.dt.Xcode.plist appears in user's Preferences folder.

A: With the exception of installing app with package manager, there is no special events if you only copy application to any folders. The preferences stored in Library or Application Support are created when you run the application for the first time.


Q: Is there a way to work with arrays and use Protege I am trying to perform the functions on arrays such as inverse of and transpose on matrices and use it along with Protege so as to calculate the forces and deflections using reasoner. We can perform the calculations using SWRL rules in ontology but it does not support array as data type. But we have Postgres and MongoDB which supports arrays. Is there any way to work with arrays and use inverse operation in ontology? Suppose inverse operation is done by database such as Postgres then how to display the array elements in ontology? Can MongoDB be used here? If yes how do we connect to Protege 5.2. I understand WebProtege can be used along MongoDB but the current version of WebProtege does not support reasoning part. Also Ontop plugin does not support connectivity with MongoDB. Kindly clarify if I am missing some thing in meeting the objective of working with arrays in ontology.


Q: Associating ViewPager with navigation tabs Is there any way to associate each fragment in the ViewPager with a certain navigation tab? So when we flip right/left ,the right tab will be highlighted.
Thank you.

A: Use TabLayout from the Material Design support library.
See the "Tabs" paragraph in the blog post that introduces the library:

However, if you are using a ViewPager for horizontal paging between
  tabs, you can create tabs directly from your PagerAdapter’s
  getPageTitle() and then connect the two together using
  setupWithViewPager(). This ensures that tab selection events update
  the ViewPager and page changes update the selected tab.


Q: Keep XML namespaces after split or grep I have a huge xml-file (several GB) which I can split with xml_split or I can extract the relevant subbnode with xml_grep. I run out of RAM if I try to read the whole XML.
But when I try to parse one of the splitted files, or the grep:ed file, I get the error "Namespace prefix xx on yy is not defined" thousands of times.
Is there a way to copy the namespace-definition from the original file to the splitted or grep:ed files? Or have I misunderstood the errors?
I'm very new to XML and I find XML::TWIG useful. Here is the grep-command I use:
xml_grep --root 'SubInformation' --cond 'SubInformationName[string()="Blah"]' Infile.xml > Outfile.xml

A: Which tool are you using to parse the result of the split (or the grep)? xmllint (from libxml2) complains, but xmlwf (from expat) doesn't. So I think any expat-based tool would be ok with the XML, but not libxml2-based ones.
It looks like xml_split and xml_grep could declare the namespaces though. At least it should be an option. I'll have a look at it.
In the meantime, here is a quick'n dirty way to post-process the result you get with xml_grep:
xml_grep --root 'SubInformation' --cond 'SubInformationName[string()="Blah"]' Infile.xml | perl -MXML::Twig -e'XML::Twig->new( start_tag_handlers => { xml_grep => sub { $_->set_att( "xmlns:m" => "http://m.org") }, SubInformation => sub { $_->flush } })->parse( \*STDIN)' > Outfile.xml

replace xmlns:m and "http://m.org" with the appropriate values.
Let me think of a way to do this in a generic way for the result of xml_split. Can I assume that the namespace declarations are not too tricky (ie that the prefix(es) are declared just once)?
Edit: Here is a way to add the namespace declarations to the files resulting from xml_split, call it as add_ns Infile after you have run xml_split on Infile.xml:
#!/usr/bin/perl

use strict;
use warnings;

use XML::Twig;

my $root= shift @ARGV;

my( $base, @files)= sort glob( "$root-*.xml");

my %ns= ns_for_file( $base);

foreach my $file (@files)
  { add_ns( $file, %ns); }

sub ns_for_file
  { my( $base)= @_;
    my %ns;
    XML::Twig->new( start_tag_handlers
      # get namespace declarations from the root and bail
      => { 'level(0)' => sub { %ns= ns_for_tag( $_);
                               $_[0]->finish_now();
                             }
         },
                  )
             ->parsefile( $base);
    return %ns;
  }

# get all namespace declarations from the root element
sub ns_for_tag
  { my( $e)= @_;
    return map { $_ => $e->att( $_) if m{^xmlns:} } $e->att_names;
  }

sub add_ns
  { my( $file, %ns)= @_;
     XML::Twig->new( start_tag_handlers => { 'level(0)' => sub { $_->set_att( %ns); } },
                     twig_handlers => { _all_ => sub { $_->flush; } },
                     keep_spaces => 1,
                   )
              ->parsefile_inplace( $file);

}

A: To process large XML files, you can also use a pull parser. See XML::LibXML::Reader.


Q: Monitorar as requisições HTTP externas dentro da página Bom dia senhores.
É possível monitorar as requisições de uma página?
Digo: Todos os arquivos que la forem chamados, exemplo: Css, Js, img, video, mp3, iframe...
Qualquer requisição HTTP.


Q: Can I remove the JSON-LD schema that Yoast adds to my WordPress site? I would like to remove the JSON-LD schema that Yoast applies to my WordPress site so that I can add my own.  I have already added my own, and Google Structured Data Testing says that it is OK, but basically I have 3 separate JSON-LD schemas instead of two because of Yoast.
You can see what I mean here: https://search.google.com/structured-data/testing-tool/u/0/#url=http%3A%2F%2Fwww.yogabearpc.com
Yoast has added the WebSite schema and it seems unnecessary or even damaging?

A: I wanted to disable this because of the sitelinks searchbox and the fact that I don't have a search function that works globally, just on the blog. Having the search box enabled for me would have undesirable effects.
The easier option may just be to prevent Google using the sitelinks searchbox without having to touch the functions files. You can prevent Google using sitelinks searchbox on your site by using the following meta:
<meta name="google" content="nositelinkssearchbox" />

If you want to disable Yoast's JSON-LD all together then here's a snippet from my blog and the code I use on my site:

SOURCE
How to disable Yoast SEO Schema JSON-LD completely
function bybe_remove_yoast_json($data){
  $data = array();
  return $data;
}
add_filter('wpseo_json_ld_output', 'bybe_remove_yoast_json', 10, 1);

Login to your WordPress dashboard and head over to the editor
  within the tab menu appearance, find your functions file (normally
  named functions.php) and add the code below just before the PHP tag is
  closed at the bottom.

A: Simplest way to completely disable the Yoast SEO schema JSON-LD
Add this line to functions.php file:
add_filter( 'wpseo_json_ld_output', '__return_empty_array' );
Source

A: If you want to disable just Organization or just Website, add this to your theme's functions.php file:
function bybe_remove_yoast_json($data){
    if ( (isset($data['@type'])) && ($data['@type'] == 'Organization') ) {
        $data = array();
    }
    return $data;
}
add_filter('wpseo_json_ld_output', 'bybe_remove_yoast_json', 10, 1);

A: Unless the data Yoast produces is wrong, there is no harm in having it. Quite the contrary, having more structured data is better than having less.
If having it is "unnecessary" depends on your definition of what is necessary. Some consumers might be interested in it, others not.
My guess is that Yoast adds a WebSite entity because of Google’s sitelinks searchbox rich snippet result, which allows Google users to search your site directly from the Google search result.


Q: JQuery not rendering HTML I am using $.get() in my ASP.NET MVC 3 application to get a response from database asynchronously. I get the response returning correctly and based on the response I generate my HTML in a string variable and finally append it to a div already on my markup page. In debug mode it shows me the complete HTML created but it doesn't get rendered in browser.
Here is my sample code
$.get("/Modules/FetchModuleActionsByModuleID", { ModuleID: ModuleID }, function (response)
{
    if (response.replace(/"/g, '') != '{d:[]}' && response.replace(/"/g, '') != '{d:null}' && response.replace(/"/g, '') != '' && response != '')
    {
        var actions = eval('(' + response + ')');
        var moduleHtml="";
        if (actions.length > 0)
        {
            for (i = 0; i < actions.length; i++)
            {

                moduleHtml += "
";
                moduleHtml += "<input type='checkbox' name='" + ModuleName + "_Actions' value='" + actions[i].ActionID + "' />";
                moduleHtml += "" + actions[i].ActionName + "";
                moduleHtml += "

";
                moduleHtml += "
";
            }

            moduleHtml += "
";
            moduleHtml += "<input type='button' class='inpuButtonAdd' value='Save' /> ";
            moduleHtml += "<input type='button' class='inpuButtonAdd' value='Cancel' /> ";
            moduleHtml += ""
            moduleHtml += "
";

            moduleHtml += "
";

            moduleHtml += "

";
            moduleHtml += "
";
            moduleHtml += "
";
            moduleHtml += "

";

            $("#divModuleDetails").append(moduleHtml); //appending to div
        }
    }
});

What could be causing this?

A: look at this line:
moduleHtml += ""

i think the problem is script still printing only a span but maybe nothing :)
anyway checkout below script optimization i think it should work ;)
    $.get("/Modules/FetchModuleActionsByModuleID", { ModuleID: ModuleID }, function (response)
{
    if (response.replace(/"/g, '') != '{d:[]}' && response.replace(/"/g, '') != '{d:null}' && response.replace(/"/g, '') != '' && response != '')
    {
        var actions = eval('(' + response + ')');
        var moduleHtml;
        if (actions.length > 0)
        {
            for (i = 0; i < actions.length; i++)
            {

                moduleHtml += "
"
                + "<input type='checkbox' name='"
                + ModuleName
                + "_Actions' value='"
                + actions[i].ActionID
                + "' />"
                + ""
                + actions[i].ActionName
                + ""
                + "

"
                + "
";
            }

           moduleHtml += "
"
            +"<input type='button' class='inpuButtonAdd' value='Save' /> "
            + "<input type='button' class='inpuButtonAdd' value='Cancel' /> "
            +""
            + "
"
            + "
"
            + "

"
            + "
"
            + "
"
            + "

";

            $("#divModuleDetails").append(moduleHtml); //appending to div
        }
    }
});


Q: The Intercept of a categorical multiple regression R is not the mean value? Let's say I have 2 (categorical) variables and one continuous:
library(tidyverse)
set.seed(123)
ds <- data.frame(
  depression=rnorm(90,10,2),
  schooling_dummy=c(0,1,2),
  sex_dummy=c(0,1)
)

When I regress depression on sex (0 or 1), the intercept is 10.0436, what is the mean of sex = 0. Ok!
ds %>% group_by(sex_dummy) %>%
+   summarise(formatC(mean(depression),format="f", digits=4))
# A tibble: 2 x 2
  sex_dummy `formatC(mean(depression), format = "f", digits = 4)`
      <dbl> <chr>
1      0    10.0436
2      1.00 10.1640

The same thing happens when I regress depression on schooling. The intercept value is 10.4398. The mean of schooling = 0 is the same.
ds %>% group_by(schooling_dummy) %>%
+   summarise(formatC(mean(depression),format="f", digits=4))
# A tibble: 3 x 2
  schooling_dummy `formatC(mean(depression), format = "f", digits = 4)`
            <dbl> <chr>
1            0    10.4398
2            1.00 9.7122
3            2.00 10.1593

Now, when I compute a model with both variables, why the intercept is not the mean when both groups = 0? The regression **intercept is 10.3796, but the mean when sex = 0, and schooling is = 0 is 10.32548:
ds %>% group_by(schooling_dummy,sex_dummy) %>%
+   summarise(formatC(mean(depression),format="f", digits=5))
# A tibble: 6 x 3
# Groups: schooling_dummy [?]
  schooling_dummy sex_dummy `formatC(mean(depression), format = "f", digits = 5)`
            <dbl>     <dbl> <chr>
1            0         0    10.32548
2            0         1.00 10.55404
3            1.00      0    9.59305
4            1.00      1.00 9.83139
5            2.00      0    10.21218
6            2.00      1.00 10.10648

When I predict the model when both are 0:
predict(mod3, data.frame(sex_dummy=0, schooling_dummy=0))
       1
10.37956

This result is related to depression (of course...) but still not What I was expecting, since:

(Reference: https://www.theanalysisfactor.com/interpret-the-intercept/)
What is the same for this previous forum post
I aware of my variables are categorical and I'm adjusting my script, as you can reproduce using this code below:
Thanks
library(tidyverse)
set.seed(123)
ds <- data.frame(
  depression=rnorm(90,10,2),
  schooling_dummy=c(0,1,2),
  sex_dummy=c(0,1)
)
mod <- lm(data=ds, depression ~ relevel(factor(sex_dummy), ref = "0"))
summary(mod)
ds %>% group_by(sex_dummy) %>%
  summarise(formatC(mean(depression),format="f", digits=4))

mod2 <- lm(data=ds, depression ~ relevel(factor(schooling_dummy), ref = "0"))
summary(mod2)
ds %>% group_by(schooling_dummy) %>%
  summarise(formatC(mean(depression),format="f", digits=4))

mod3 <- lm(data=ds, depression ~ relevel(factor(sex_dummy), ref = "0") +
             relevel(factor(schooling_dummy), ref = "0"))
summary(mod3)
ds %>% group_by(schooling_dummy,sex_dummy) %>%
  summarise(formatC(mean(depression),format="f", digits=5))

predict(mod3, data.frame(sex_dummy=0, schooling_dummy=0))

A: Two errors in your thinking (although your R code works so it's not a programming error.
First and foremost you violated your own statement you have not dummy coded schooling it does not have only zeroes and ones it has 0,1 & 2.
Second you forgot the interaction effect in your lm modeling...
Try this...
library(tidyverse)
set.seed(123)
ds <- data.frame(
  depression=rnorm(90,10,2),
  schooling_dummy=c(0,1,2),
  sex_dummy=c(0,1)
)
# if you explicitly make these variables factors not integers R will do the right thing with them
ds$schooling_dummy<-factor(ds$schooling_dummy)
ds$sex_dummy<-factor(ds$sex_dummy)
ds %>% group_by(schooling_dummy,sex_dummy) %>%
    summarise(formatC(mean(depression),format="f", digits=5))
# you need an asterisk in your lm model to include the interaction term
lm(depression ~ schooling_dummy * sex_dummy, data = ds)

The results give you the mean(s) you were expecting...
Call:
lm(formula = depression ~ schooling_dummy * sex_dummy, data = ds)

Coefficients:
                (Intercept)             schooling_dummy1             schooling_dummy2
                  10.325482                    -0.732433                    -0.113305
                 sex_dummy1  schooling_dummy1:sex_dummy1  schooling_dummy2:sex_dummy1
                   0.228561                     0.009778                    -0.334254

and FWIW you can avoid this sort of accidental misuse of categorical variables if your data is coded as characters to begin with... so if your data is coded this way:
ds <- data.frame(
  depression=rnorm(90,10,2),
  schooling=c("A","B","C"),
  sex=c("Male","Female")
)

You're less likely to make the same mistake plus the results are easier to read...


Q: How I count the words and expressions in a text? I want to count how much times some given words or phrases appears in a text, but I want use some string similarity algorithms.
Every word or expression has an value, so I will set the relevancy of the text according to the number of words found, etc.
I guess that the String class from Java cannot offer this. I will need to iterate all the text for each word or expression I want to find?
Is there a library for text handling?
Example: find texts that has "videogame", "i have a videogame" and something like this, evaluating similar expressions. I guess if I iterate for each word or expression I need to evaluate, I cannot find the similar words and it will be more slower.

A:
but I want use some String similarity algorithms.

Take a look at Lucene. Allows you to index some text and look for works using a similarity algorithm. I would think you want to split each words and index them using lucene. Then for all the words you are interested for you can search the index. You can do things like Automobile~ which will do a fuzzy search. Here is a rough algo:
for each word in STRING.split(' ')
  index word

for each word in your list
  search for word and look for number of occurrences

A: The inverted index that Denniss said is what you are looking for. You'll need to define your Document very well if you want a powerfull engine.
For phrase matches, your Document should have the position of the word (the key of the Map) in this Document. Once you got all the words you were looking for, you can know if this words were together in the original document.
For example:
doc1: "Hello World"
doc2: "Hello Beautiful World"

inverted index {
  "Beautifull": [(doc2, 2)],
  "Hello": [(doc1, 1)(doc2, 1)],
  "World": [(doc1, 2)(doc2, 3)],
}

query: "Hello World"

Both documents have the words "Hello" and "World", but doc1 has them together (position 1 and 2) and doc2 doesn't (position 1 and 3).
If you want to find similar words, you'll need a new structure. First, you need to define what is similar. Levenshtein distance is what you need for that.
To implement it, you'll need a whole new struture like an automata: Levenshtein automaton.
Full-text search is a huge area. Implementing a search engine is hard and many libraries and applications already do it.
(I work for Indextank.com a realtime full-text search engine. If you need a search engine running in a couple of minutes, try us out)

A: What you are looking for is porbably an Inverted File data structure. I learned this in database class and here is a link to the lecture.
http://dl.dropbox.com/u/8950924/16Sp11-Search.pdf
Basically the idea is to have a Map data structure
Map<String, List<Document>> invertedIndex;

where string is the word and List<Document> is the documents containing that word.
If you read more into that pdf, you can even find a way to rank the document.


Q: Problem connecting to L2TP VPN I installed l2tp-ipsec-vpn from ppa:werner-jaeger/ppa-werner-vpn.
Yesterday I was able to connect to my L2TP vpn account successfully.
But after restart i'm getting this on syslog:
Mar 07 21:16:44.834 xl2tpd[7179]: death_handler: Fatal signal 15 received
Mar 07 21:16:44.835 Stopping xl2tpd: xl2tpd.
Mar 07 21:16:44.866 recvref[22]: Protocol not available
Mar 07 21:16:44.867 xl2tpd[7225]: This binary does not support kernel L2TP.
Mar 07 21:16:44.867 Starting xl2tpd: xl2tpd.
Mar 07 21:16:44.868 xl2tpd[7226]: xl2tpd version xl2tpd-1.2.8 started on my-laptop PID:7226
Mar 07 21:16:44.868 xl2tpd[7226]: Written by Mark Spencer, Copyright (C) 1998, Adtran, Inc.
Mar 07 21:16:44.868 xl2tpd[7226]: Forked by Scott Balmos and David Stipp, (C) 2001
Mar 07 21:16:44.868 xl2tpd[7226]: Inherited by Jeff McAdams, (C) 2002
Mar 07 21:16:44.868 xl2tpd[7226]: Forked again by Xelerance (www.xelerance.com) (C) 2006
Mar 07 21:16:44.869 xl2tpd[7226]: Listening on IP address 0.0.0.0, port 1701
Mar 07 21:16:45.898 xl2tpd[7226]: Connecting to host vp3.nasaserver.org, port 1701
Mar 07 21:16:50.903 xl2tpd[7226]: Maximum retries exceeded for tunnel 39372.  Closing.

I'm using Ubuntu Lucid Lynx.
What is the problem?


Q: Not able to serve media files in django I am trying to create an online music player. I was trying to play a song in django. But it was not able to play since it was not able to detect the audio file. I have set up the media in django as I read on the internet but it's not working.
Here is the screenshot of my project directory:

detect and music are two apps. I am currently working with music app.
Settings.py(included this at last of file).
STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static")
]
MEDIA_ROOT = os.path.join(BASE_DIR,"media")
MEDIA_URL = '/media/'

urls.py:
from django.conf.urls import *
from django.contrib import admin
from detect import views
from music import views
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^music/$',views.play,name = 'play')

]

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

views.py:
from django.shortcuts import render
from django.http import HttpResponse
def play(request):
    return render(request,'music/song.html',{})

song.html:
<html>
<audio id="Player" autoplay>
     <source src="{{MEDIA_URL}}/audio/test.mp3"/>
</audio>
</html>

A: Pass MEDIA_URL like to render like this
render(request,'music/song.html',{'MEDIA_URL': settings.MEDIA_URL}) and make sure to include from django.conf import settings in your views.py.


Q: Joomla ZOO item counter I'm using joomla 3, zoo component.
In the backend of the system i have this code to display numbers of items in the every zoo application installed:
<?php echo $application->getItemCount(); ?>

What i need is to edit this code to display only numbers of items that are "published".
I'm not sure how to do this as i'm not a php coder.
Any suggestions, please?

A: You could try fetching the data from the database. Check out the doc here. Here is some sample code witch should help
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('COUNT(*)');
$query->from($db->quoteName('#__tablename'));
$query->where($db->quoteName('published') . ' = 1');
$row = $db->loadRow();
print_r($row);

You will need to find the table where the data is stored and replace __tablename accordingly (and maybe change the column name "published" if needed)


Q: Again boxes with marbles and strategy
Let’s consider 3 identical jewelry boxes, one with 2 green marbles, one with 2 blue marbles and last one with one green and one blue.
  Before opening any box we set a target, either to pick two marbles of the same color or different.
We then randomly choose a box and then a marble (without seeing its color before choosing it). We then see the color of the marble and put it back to its box. We repeat the process by picking a box (same with the previous or different) and a marble from it (again randomly).
Find the probability that we succeed (i.e. if we had chosen to go for “two of the same color”, we indeed got two marbles of the same color, or, if we chose to go for two marbles of different colors, we got two different. We assume that our moves are of absolute logic.

Let's assume that we choose to find two marbles of the same color.
We pick one box (probability $\frac{1}{3}$), say we get a green marble (is the (conditional) probability $\frac{1}{2}$??), then we must select either the same box again (hoping we will get a marble of the same color - blue probability $\frac{1}{2}$) or another box, probability $\frac{1}{2}$ for the box and probability 0 if we pick the box with the two blue marbles, 1/2 if we pick the box with 1+1 and 1 if we pick the box with the 2 green (assuming the one we chose the first time was the 1+1).
By intuition only, I think that I must set the target to pick 2 marbles of the same color, as the chances for this are 2/3 overall.
I don't know how to continue :(

A: The probability the first box you choose has two marbles of the same colour is $\frac23$

*

*So if you pick the same box again, the probability that your second marble is the same colour as your first marble is $\frac23 \times 1 + \frac13 \times \frac12 = \frac56$, and the probability that it is different is $\frac23 \times 0 + \frac13 \times \frac12 = \frac16$

*While if you pick a different second box, the probability that your second marble is the same colour as your first marble is $\frac23 \times \frac14 + \frac13 \times \frac12 = \frac13$, and the probability that it is different is $\frac23 \times \frac34 + \frac13 \times \frac12 = \frac23$

*If you pick the second box at random, the probability that your second marble is the same colour as your first marble is then $\frac13 \times \frac56 + \frac23 \times \frac13 = \frac12$, and the probability that it is different is $\frac13 \times \frac16 + \frac23 \times \frac23 = \frac12$, as you would expect
So the best strategy would be, as I think you have said, to set a target of picking the same colour twice, and then to choose the second marble from the same box as the first.  The probability of achieving the target would be $\frac56$


Q: What extension for underlining html  in visual studio code editor? I need something like this (i have in bracket editor) but I don't know its come from which extension.

A: There is a extension for that.
Simply search for "highlight-matching-tag" in the extension tab
or download it here: https://marketplace.visualstudio.com/items?itemName=vincaslt.highlight-matching-tag
I recommend to set a custom setting like this:
    "highlight-matching-tag.style": {
    "borderWidth": "1px",
    "borderColor": "orange",
    "borderStyle": "solid"
}


Q: How to create a new metastore? I want to configure Unity Catalog and one step is creating a metastore in the region where I create databricks workspace (I am on Azure).
I created a workspace with a premium pricing tier and I am the admin.
Following the documentation, I should go to the Data tab to create metastore.
However, when I open the Data tab, I don't see "Create Metastore" button.

The same in SQL persona:

Could you guide me how to make a new metastore?
If a metastore is already created in the region, how can I find it?

A: In order to do this sort of management, you should access the Databricks account portal at the tenant level:
Databricks Account

From there, you can create and manage the metastores, as well as assign a metastore with a Databricks Workspace, which is what you have created.
Take into account that for most of what you have described, you must be an account admin for the Databricks Account.
As per the official docs (source):

The first Azure Databricks account admin must be an Azure Active Directory Global Administrator at the time that they first log in to the Azure Databricks account console. Upon first login, that user becomes an Azure Databricks account admin and no longer needs the Azure Active Directory Global Administrator role to access the Azure Databricks account. The first account admin can assign users in the Azure Active Directory tenant as additional account admins (who can themselves assign more account admins). Additional account admins do not require specific roles in Azure Active Directory.

A:
You must be an Azure Databricks account admin to getting started using Unity Catalog this can be done for first time using Azure Active Directory Global Administrator of your subscription.

As per official documentation:
The first Azure Databricks account admin must be an Azure Active
Directory Global Administrator at the time that they first log in to
the Azure Databricks account console. Upon first login, that user
becomes an Azure Databricks account admin and no longer needs the
Azure Active Directory Global Administrator role to access the Azure
Databricks account. The first account admin can assign users in the
Azure Active Directory tenant as additional account admins (who can
themselves assign more account admins). Additional account admins do
not require specific roles in Azure Active Directory.

How to identify your Microsoft Azure global administrators for your subscriptions?

The global administrator has access to all administrative features. By default, the person who signs up for an Azure subscription is assigned the global administrator role for the directory. Only global administrators can assign other administrator roles.

Login into the Azure Databricks account console via Global admin and then account admin can assign users in the Azure Active Directory tenant.

For more details, refer to Azure Databricks - Get started using Unity Catalog and also refer to MS Q&A thread - How to access Azure Databricks account admin? addressing similar issue.

A: Configure  your Unity Catalog Metastore

Go to + New add click on new notebook and open.
If you already have  catalogs with data .then use below command to check,
# Show all catalogs in the metastore.

display(spark.sql("SHOW CATALOGS"))

If you don't have catalog . create utility catalog :
# Create a catalog.

spark.sql("CREATE CATALOG IF NOT EXISTS catalog_name")

# Set the current catalog.

spark.sql("USE CATALOG catalog_name")

for more information refer this offical_document and Notebook.


Q: ProductName hides System.Windows.Forms.Control.ProductName I have a property ProductName in my Form. I am getting warning while compiling the code.
FormInventory.ProductName hides inherited member 'System.Windows.Forms.Control.ProductName'. Use the new keyword if hiding was intended.
below is my code
public partial class FormInventory : Form, IInventoryView
{
   public FormInventory()
   {
   }

   public string ProductName
   {
      get { return this.textProductName.text; }
      set { this.textProductName.text = value; }
   }
}

textProductName is a textbox.
I know that ProductName hides the base class's property Forms.Control.ProductName. My question is

*

*Is it possible to suppress the warning without Renaming my FormInventory.ProductName property

*I am currently in the beginning of the development, if i hide this property with the new modifier will there be any problem at the time of releasing the product, because base property Forms.Control.ProductName returns the product name of the assembly containing the control. Where as my FormInventory.ProductName  returns a user entered value.

*Where will we be using this Forms.Control.ProductName, because i have never used it before.
I have searched and found Similar questions

*

*Entity Framework hides inherited member Warning

*Use new keyword if hiding was intended
these questions doesn't solve my problem but helped me in understanding the cause for the warning.

A: If ProductName is a form field that you intend displaying on the form, why not instead abstract all the fields of property into a separate Product entity. This should ease the maintenance of your app (and bring it more in line with patterns like MVC / MVVM), e.g.
public class Product
{
     public string ProductName{ get; set; }
     public int ProductSize{ get; set; }
     // etc
}

public partial class FormInventory : Form
{
   public FormInventory()
   {
   }

   public Product Product
   {
      get;
      set;
   }
}

Edit :
IMO, the architecture presented by Rod Cerata's blog looks OK, but I believe it would be improved via encapsulation of a "ViewModel" for your Employee.
Have a look at EmployeePresenter.cs - you get lots of repetitive scraping code like this:
        _model.EmployeeID = _view.EmployeeID;
        _model.Lastname = _view.Lastname;
        _model.Firstname = _view.Firstname;
        _model.EmployeeType = _view.EmployeeType;
        _model.Salary = _view.Salary;
        _model.TAX = _view.TAX;

IMO would be improved by creating a new EmployeeViewModel class (which would be more or less the same as EmployeeModel, plus any 'screen' specific fields e.g. Title, "mode" (Edit, New, Read Only etc), and then using a tool like AutoMapper, which would reduce the code above.

A: 1. Yes, simply use the new keyword, like public new string ProductName { get; set; }
2. No, it simply returns the name of the assembly.
3. Its used for debugging and some "reflection". I say "reflection" because it's more like a human-made reflection.
So, it's safe to go forward this way. But why don't you simply change it to MyCompanyProductName?
Regards

A: Using the 'new' keyword will suppress the warning.  When you do this, the result of calling the ProductName property depends on Type of the variable that is used to referenced the form... for example, if you're calling the property from another class:
// Notice that we're only creating one object and
// assigning it to two different variables.
FormInventory explicitlyNameForm = new FormInventory();
Form referenceToBaseForm = explicitlyNameForm;

// Acting on the child reference (FormInventory) will
// operate on YOUR implementation of ProductName
explicitlyNameForm.ProductName = "Some Value";

// But acting on the parent reference (Form) will
// operate on the .NET implementation of ProductName
referenceToBaseForm.ProductName = "Some Other Value";

The end result will probably be what you want... the compiler knows which implementation to use based on how you've declared your variable.  And since all references within the .NET framework reference the Form class, not your new class, there is no risk of affecting anything that happens within the .NET framework with respect to this property.
However, as the others have suggested, it may cause less confusion if you're able to rename the property.


Q: vector in C++ can only read the last element I add several element to the vector, but when I visit them, they are all the one which is added at last. I can't understand.
here is my code:
while(true){
    cin>>shape;
    if(shape=='X') break;
    if(shape=='C'){
        cin>>x>>y>>r;
        Circle c(x,y,r);
        shapes[sum] = &c;
        //cout<<shapes[sum]->getArea()<<endl;
        sum++;
    }else if(shape=='R'){
        cin>>x1>>y1>>x2>>y2;
        Rectangle rec(x1,y1,x2,y2);
        shapes[sum] = &rec;
        //cout<<shapes[sum]->getArea()<<endl;
        sum++;
    } else if(shape=='T'){
        cin>>x1>>y1>>x2>>y2>>x3>>y3;
        Triangle tr(x1,y1,x2,y2,x3,y3);
        shapes[sum] = &tr;
        //cout<<shapes[sum]->getArea()<<endl;
        sum++;
    }
}
for(int j=0; j<sum; j++){
    showArea(shapes[j]);
}

I found that at last, all the element in the vector is same, they are the element which is added at last.

A: Your vector stores pointer. And you store inside it pointer of local variables:
} else if(shape=='T'){
    cin>>x1>>y1>>x2>>y2>>x3>>y3;
    Triangle tr(x1,y1,x2,y2,x3,y3); // <= Create local variable, automatic allocation
    shapes[sum] = &tr; // <= store its address
    //cout<<shapes[sum]->getArea()<<endl;
    sum++;
} // <= automatic dealocation of tr, ie tr doesn't exist anymore
  // shapes[sum - 1] stores address of no more existing variable => Undefined behavior

you should do:
} else if(shape=='T'){
    cin>>x1>>y1>>x2>>y2>>x3>>y3;
    Triangle *tr = new Triangle(x1,y1,x2,y2,x3,y3); // manual allocation
    shapes.push_back(tr);
    //cout<<shapes[sum]->getArea()<<endl;
    sum++;
}

BUT you have to deallocate with delete when you don't need anymore objects in vector

sum isn't necessary: you have to use push_back to avoid Undefined Behavior, and after, you can use shapes.size() to retrieve size of vector.
Indeed, accessing to an element of vector which is out of bound (ie when you do vector[n], n is equal or greater than vector.size()) is undefined behavior.

Modern way of doing this: use of shared_ptr or unique_ptr


Q: existence of an automorphism F(A)=A Let G be a bounded domain in $\mathbb{C}$ and let $A\subset G$ be finite.I got to show that for every $f\in Aut(G\backslash A)$ there is a unique $F \in Aut (G)$ with $F\vert_{G\backslash A}=F$ and that $F(A)=A$. $Aut$ is the group of all automorphism. I got no idea how to show this. Can I use here the Maximums-theorem?

A: Same argument as for several of your recent questions. If $a\in A$ then $f$ has a removable singularity at $a$ since $G$ is bounded. So $f$ extends to a map $F:G\to\overline G$. Open Mapping Thorem shows that $F:G\to G$.
If $a\in A$ and $F(a)\in G$ then the Open Mapping Theorem shows that $f$ is not injective. So $F$ maps $A$ into $A$. And if $a,a'\in A$, $a\ne a'$ and $F(a)=F(a')$ then the Open Mapping Theorem shows that $f$ is not injective. So $F$ is injective on $A$; since $A$ is finite it follows that $F$ is bijective.
For details see my answer to your other question Automorphism of unit disk without zero


Q: Is ~~ a short-circuit operator? From the Smart matching in detail section in perlsyn:

The smart match operator
  short-circuits whenever possible.

Does ~~ have anything in common with short circuit operators (&&, ||, etc.) ?

A: The meaning of short-circuiting here is that evaluation will stop as soon as the boolean outcome is established.
perl -E "@x=qw/a b c d/; for (qw/b w/) { say qq($_ - ), $_ ~~ @x ? q(ja) : q(nein) }"

For the input b, Perl won't look at the elements following b in @x. The grep built-in, on the other hand, to which the document you quote makes reference, will process the entire list even though all that's needed might be a boolean.
perl -E "@x=qw/a b c/; for (qw/b d/) { say qq($_ - ), scalar grep $_, @x ? q(ja) : q(nein) }"

A: Yes, in the sense that when one of the arguments is an Array or a Hash, ~~ will only check elements until it can be sure of the result.
For instance, in sub x { ... }; my %h; ...; %h ~~ \&x, the smart match returns true only if x returns true for all the keys of %h; if one call returns false, the match can return false at once without checking the rest of the keys. This is similar to the && operator.
On the other hand, in /foo/ ~~ %h, the smart match can return true if it finds just one key that matches the regular expression; this is similar to ||.


Q: How do i trigger a form submit after validating with ? I have a form that i need to validate 1 field by the controller,
what is the right way to to preform validation with the controller and by the answer to preform form submission??
Heres the VFP code:
<apex:outPutPanel id="script_block">
    <script>
        var submitDisabled = '{!submitDisabled}';
        function performValidation(){
            // 1. check with controller preSubmitCase method
            // 2. if "submitDisabled" callback is true then submit the form, if not then raise an error to the user
        }
    </script>
</apex:outPutPanel>

<apex:form id="myform" >

    <apex:input   id="acctReporting_on" value="{!acctReporting_on}"/> //Required field
    <input type="button"  onclick="performValidation();" value="Submit" />
    <apex:actionFunction name="preSubmitCase" action="{!preSubmitCase}" reRender="form" />
    <apex:commandButton value="Submit Case"   action="{!submitCase}"/>

</apex:form>

And here's the controller code:
public class SubmitCaseController {

    public Boolean submitDisabled {get; set;}
    public String acctReporting_on { get; set; }

     public PageReference preSubmitCase() {

        submitDisabled = false;
        List<Account> accts = [SELECT Id FROM Account WHERE Name = :acctReporting_on];
        if(accts.size() == 1) {
            submitDisabled = true;
        }
        return null;
     }

    public PageReference submitCase() {
        //form submition function
    }
}

A: You can modify your code as follows, added rerender to your form and disabled to command button:
Page:
<apex:form id="myform" >
    <apex:input id="acctReporting_on"
        value="{!acctReporting_on}"/>

    <!-- call action function directly from onclick -->
    <input type="button"
        value="Submit"
        onclick="performValidation();"/>

    <!-- call controller method for validation -->
    <apex:actionFunction name="performValidation"
            action="{!preSubmitCase}"
            reRender="myform"/>

    <!-- added disabled tag to conditionally -->
    <apex:commandButton value="Submit Case"
        action="{!submitCase}"
        disabled="{!submitDisabled}"/>
</apex:form>

Class:
public class SubmitCaseController {

    public Boolean submitDisabled { get; set; }
    public String acctReporting_on { get; set; }

    public SubmitCaseController() {
        // on load disable submit
        submitDisabled = false;
    }

     public void preSubmitCase() {
        List<Account> accts = [SELECT Id FROM Account
            WHERE Name = :acctReporting_on];
        // if there are records, this would be true
        submitDisabled = accts.size() == 1;
     }

    public PageReference submitCase() {
        //form submition function
    }
}


Q: Site doesn't scroll smoothly (HTML + CSS) I'm creating a site using HTML and CSS for a school project (there's no JS involved).
I use a Smooth Scrolling addon on Google Chrome, but the page doesn't scroll smoothly like every other page on the Internet does. Instead, it scrolls in blocky chunks down the page.
JSFiddle: Here

(the first few lines of code just for the JSFiddle link)
Interestingly, the preview in JSFiddle scrolls smoothly :/
Thanks in advance :)

A: Tested on Chrome, and it scrolls just fine.
Scrolling is controlled by your mouse settings, so maybe something changed with your scroll wheel?