text:
Q: Separate config for DEV and PROD of wepack5 not working I removed my webpack.config.js to create 3 different webpack config files, namely webpack.common.js, webpack.prod.js, webpack.dev.js. While with webpack.config.js, the project was running fine after npm run start. But after separating config to 3 different files, the build fails with this error
$ npm run start

> resume@1.0.0 start C:\Users\Ankit Rawat\projects\resume
> webpack serve --open --config webpack.dev.js

[webpack-cli] The specified config file doesn't exist in 'C:\Users\Ankit Rawat\projects\resume\webpack.dev.js'
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! resume@1.0.0 start: `webpack serve --open --config webpack.dev.js`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the resume@1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Ankit Rawat\AppData\Roaming\npm-cache\_logs\2021-01-14T06_54_14_483Z-debug.log

npm run build also fails with the same error.
webpack.common.js
const path = require('path');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
    entry: {
        app: './src/index.js',
    },
    module: {
        rules: [
            // JavaScript
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: ['babel-loader'],
            },
            // Images
            {
                test: /\.(?:ico|gif|png|jpg|jpeg)$/i,
                type: 'asset/resource',
            },
        ],
    },
    plugins: [
        // new CleanWebpackPlugin(['dist/*']) for < v2 versions of CleanWebpackPlugin
        new CleanWebpackPlugin(),
        new HtmlWebpackPlugin({
            title: 'HEY !!',
            template: path.resolve(__dirname, './index.html'),
            filename: 'index.html', // output file
        }),
        new webpack.ProvidePlugin({ // no need to import React and ReactDOM  in every component created, after using this
            'React': 'react',
            'ReactDOM': 'react-dom',
        })
    ],
    output: {
        filename: '[name].bundle.js',
        path: path.resolve(__dirname, 'dist'),
    },
};

webpack.dev.js
const { merge } = require('webpack-merge');
const common = require('./webpack.common.js');

module.exports = merge(common, {
    mode: 'development',
    devtool: 'inline-source-map',
    devServer: {
        historyApiFallback: true,
        contentBase: path.resolve(__dirname, './dist'),
        open: true,
        compress: true,
        hot: true,
        port: 8080,
    },
    plugins: [
        new webpack.HotModuleReplacementPlugin()
    ],
    module: {
        rules: [
            // CSS and Sass
            {
                test: /\.(scss|css)$/,
                use: ['style-loader', 'css-loader', 'sass-loader'],
            }
        ],
    },
});

webpack.prod.js
const { merge } = require('webpack-merge');
const common = require('./webpack.common.js');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');

module.exports = merge(common, {
    mode: 'production',
    devtool: 'source-map',
    module: {
        rules: [
            {
                test: /\.css$/i,
                use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'],
            },
        ],
    },
    optimization: {
        minimizer: [
            new CssMinimizerPlugin(),
        ],
    },
});

package.json
{
  "name": "resume",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "webpack serve --open --config webpack.dev.js",
    "build": "webpack --config webpack.prod.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@babel/preset-react": "^7.12.10",
    "css-minimizer-webpack-plugin": "^1.2.0",
    "react": "^17.0.1",
    "react-dom": "^17.0.1"
  },
  "devDependencies": {
    "@babel/core": "^7.12.10",
    "@babel/plugin-proposal-class-properties": "^7.12.1",
    "@babel/preset-env": "^7.12.11",
    "babel-loader": "^8.2.2",
    "clean-webpack-plugin": "^3.0.0",
    "css-loader": "^5.0.1",
    "html-webpack-plugin": "^4.5.1",
    "mini-css-extract-plugin": "^1.3.3",
    "node-sass": "^5.0.0",
    "react-hot-loader": "^4.13.0",
    "sass-loader": "^10.1.1",
    "style-loader": "^2.0.0",
    "webpack": "^5.12.2",
    "webpack-cli": "^4.3.1",
    "webpack-dev-server": "^3.11.1",
    "webpack-merge": "^5.7.3"
  }
}

This was my webpack.config.js which is now deleted
const path = require('path')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const { web } = require('webpack')

module.exports = {
    mode: 'development',
    devServer: {
        historyApiFallback: true,
        contentBase: path.resolve(__dirname, './dist'),
        open: true,
        compress: true,
        hot: true,
        port: 8080,
    },
    // entry: {
    //     main: path.resolve(__dirname, './src/index.js'),
    // },
    // output: {
    //     path: path.resolve(__dirname, './dist'),
    //     filename: '[name].bundle.js',
    // },
    module: {
        rules: [
            // JavaScript
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: ['babel-loader'],
            },
            // CSS and Sass
            {
                test: /\.(scss|css)$/,
                use: ['style-loader', 'css-loader', 'sass-loader'],
            },
            // Images
            {
                test: /\.(?:ico|gif|png|jpg|jpeg)$/i,
                type: 'asset/resource',
            },
        ],
    },
    plugins: [
        new HtmlWebpackPlugin({
            title: 'HEY !!',
            template: path.resolve(__dirname, './index.html'),
            filename: 'index.html', // output file
        }),
        new CleanWebpackPlugin(),
        new webpack.HotModuleReplacementPlugin(),       // ONLY FOR DEVELOPMENT
        new webpack.ProvidePlugin({                     // no need to import React and ReactDOM  in every component created, after using this
            'React': 'react',
            'ReactDOM': 'react-dom',
        })
    ],
}

I'am not being able to get the problem here. Please Help.

A: As specified by @tmhao2005, the webpack files were not placed in the right place.
Rectified that and that error disappeared only to be replaced by
[webpack-cli] Failed to load 'C:\Users\Ankit Rawat\projects\resume\webpack.dev.js'
[webpack-cli] ReferenceError: webpack is not defined
    at Object.<anonymous> (C:\Users\Ankit Rawat\projects\resume\webpack.dev.js:17:13)
    at Module._compile (C:\Users\Ankit Rawat\projects\resume\node_modules\v8-compile-cache\v8-compile-cache.js:192:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Module.require (internal/modules/cjs/loader.js:690:17)
    at require (C:\Users\Ankit Rawat\projects\resume\node_modules\v8-compile-cache\v8-compile-cache.js:159:20)
    at loadConfig (C:\Users\Ankit Rawat\projects\resume\node_modules\webpack-cli\lib\webpack-cli.js:753:31)
    at Promise.all.options.config.map (C:\Users\Ankit Rawat\projects\resume\node_modules\webpack-cli\lib\webpack-cli.js:823:48)
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! resume@1.0.0 start: `webpack serve --open --config webpack.dev.js`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the resume@1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Ankit Rawat\AppData\Roaming\npm-cache\_logs\2021-01-14T08_03_02_168Z-debug.log

This was solved by adding const webpack = require('webpack'); in the required pages.


text:
Q: Citrix VDA Uninstall I have to upgrade Citrix 7.15 to Citrix vda 1912 and there over 600 machines I have to upgrade.
When I push the uninstaller to a bunch of machine in desktop central it will uninstall again when I sign in as my admin account.
SO if I push the uninstaller -> then push the installer it will work however my main issue is that when I sign in that pc as my admin account the uninstaller will run again.
is there a way to fully uninstall via without signing in multiple times? and if not is there a bat script or power shell script that can sign me in another machine?
we use window 10
SO if I push the uninstaller -> then push the installer it will work however my main issue is that when I sign in that pc as my admin account the uninstaller will run again.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Problem with running the first test on the Robolectric Strange behavior. I'm just setting up the Robolectric now.
Here are my settings:
build.app
dependencies {
    testImplementation 'org.robolectric:robolectric:4.0-alpha-3-SNAPSHOT'
}

and
testOptions {
        unitTests {
            includeAndroidResources = true
        }
    }

build.project
repositories {
     maven { url "https://oss.sonatype.org/content/repositories/snapshots" }
}

So that is my activity
@RunWith(RobolectricTestRunner.class)

public class RootActivityTest {
private RootActivity activity;

@Before
public void setup()  {
    activity = Robolectric.buildActivity(RootActivity.class)
            .create()
            .resume()
            .get();
}

@Test
public void checkActivityNotNull() throws Exception {
    assertNotNull(activity);
}
}

And now when I run a test with this configuration, I get the following error:

java.lang.RuntimeException: MultiDex installation failed (/tmp/robolectric-Method_checkActivityNotNull6294215780013113020/com.mandarine.android-sourceDir (Is a directory)).

Tried to implement one of this library:
testImplementation "org.robolectric:multidex:3.4.2"

or
testCompile "org.robolectric:shadows-multidex:3.0"

But doesn't help.

A: Perhaps someone will be useful. Also u can start from this link
My experience how to run tests with Robolectric:
build.grade:
testImplementation 'org.robolectric:robolectric:3.8'

testOptions {
    unitTests {
        includeAndroidResources = true
    }
}

Here is my MainActivity:
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21)

public class MainActivityTest {

@Test
public void shouldNotBeNull() throws Exception {
    MainActivity activity = Robolectric.setupActivity(MainActivity.class);
    assertNotNull(activity);
}
}

And last trick, add in gradle.properties:
android.enableAapt2=false


text:
Q: Inverse Laplace transform of functions with jump discontinuities Given a function $F(s)$, suppose we define its inverse Laplace transform as:
\begin{equation}
f(t) = \lim_{k \to \infty} \frac{(-1)^{k}}{k!}\left(\frac{k}{t}\right)^{k+1}F^{(k)}\left( \frac{k}{t} \right)
\end{equation}
for $t > 0$.
Now suppose we take the ordinary Laplace transform of a function with a jump discontinuity. In this case, what would the above formula recover when applied to the Laplace transform of the function at the jump discontinuity? Would it be $\frac{1}{2}(f(x^+) + f(x^-))$?


text:
Q: Is it possible to make the hyphenation char gray? In math articles, sometimes there might be a lot of composed phrases like $R$-module, $r$-$K$-linear, etc., and in some cases it could be confusing whether a - is for hyphenation or is it just a normal - in the phrases.
It would seem inappropriate to completely suppress word break in these phrases (with \mbox, for example) since some of them might be quite long. For now I use the NON-BREAKING HYPHEN (U+02011) though to ensure that the breaking point is not at those - which are part of the phrases, so there is no risk that one shall misread them as a hyphen char. However, it is still strange to see something like $r$-$k$-li- at the end of a line.
In these cases, is it possible to make the hyphen char - in gray (for example as \textcolor{gray}{-}) or some other style, globally, so as to differ from the normal -?

At first this seems to me an easy question, but after searching around on this site it turns out that one seems to have very little control over the hyphen chars (pre-break, post-break and no-break, according to the question given below). Shouldn't we have full access to them and can change them to whatever we want?
I've checked in particular this question, but the solution seems to aim at changing the hyphen char only locally (not sure if I understood the usage of \discretionary correctly). Also, it seems that the treatment for hyphen char differs under different engines, thus if it is too much to ask for a universal way to achieve this, I hope that the solution (if exists) can at least work for LuaLaTeX.


text:
Q: ClassNotFoundException when trying to start topology This is a strange problem that I'm hoping someone's encountered and overcome.
I have a relatively simple topology:
Spout -> BoltA -> BoltB
      -> BoltC

If I use bolts A and B, it works. A and C works too. Enabling all three though gives me this:
16:05:20.627 [main] WARN  backtype.storm.daemon.nimbus - Topology submission exception. (topology name='traffic') #<RuntimeException java.lang.RuntimeException: java.lang.ClassNotFoundException: backtype.storm.daemon.nimbus$normalize_conf$get_merged_conf_val__3916$fn__3917>
16:05:20.634 [main] ERROR o.a.zookeeper.server.NIOServerCnxn - Thread Thread[main,5,main] died
java.lang.RuntimeException: java.lang.ClassNotFoundException: backtype.storm.daemon.nimbus$normalize_conf$get_merged_conf_val__3916$fn__3917
at backtype.storm.utils.Utils.deserialize(Utils.java:88) ~[storm-core-0.9.1-incubating.jar:0.9.1-incubating]
at backtype.storm.daemon.nimbus$read_storm_conf.invoke(nimbus.clj:89) ~[storm-core-0.9.1-incubating.jar:0.9.1-incubating]
at backtype.storm.daemon.nimbus$start_storm.invoke(nimbus.clj:724) ~[storm-core-0.9.1-incubating.jar:0.9.1-incubating]
at backtype.storm.daemon.nimbus$eval3974$exec_fn__1459__auto__$reify__3987.submitTopologyWithOpts(nimbus.clj:962) ~[na:na]
at backtype.storm.daemon.nimbus$eval3974$exec_fn__1459__auto__$reify__3987.submitTopology(nimbus.clj:971) ~[na:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.7.0_55]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[na:1.7.0_55]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.7.0_55]

I'm running it locally using the code below:
LocalCluster cluster = new LocalCluster();
cluster.submitTopology(topoName, conf, buildTopology(source, service));
try {
  Thread.sleep(10000);
} catch (InterruptedException e) {
  throw new RuntimeException(e);
}
cluster.killTopology(topoName);
cluster.shutdown();

I'm running against storm-core-0.9.1-incubating.jar
All I could find was this discussion about it "being a classpath issue". The fact that it only happens after adding a third bolt, but it doesn't matter which bolt, really confuses me. Is there something that Storm does once it has a "sufficiently complex topology" that kicks in at 3 bolts or 4 components?
EDIT
Well, it gets weirder. After finding someone with the same problem I tried their solution and added to my logback.xml:
<logger name="backtype.storm.daemon.nimbus" level="INFO" />

which fixed the problem. Anything higher (WARN, ERROR) brings it back. Lower (DEBUG) is fine. Removing this line and setting the root logger to DEBUG brings the problem back, so I'm really confused. If something in the code path depends on logger.isInfoEnabled() shouldn't it act the same for rootLogger=INFO and backtype.storm.daemon.nimbus=INFO?


text:
Q: Debian virt/res/shr and cpu time limiting Servers have multiple users running multiple programs, some of which don't seem to behave and will eat up RAM like there is no tomorrow, for example:
  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
30091 xxxx 20   0 2194m 1.4g 1.4g S   21  9.0   0:56.03 aaaaa
30212 xxxx 20   0 1460m 1.1g 1.1g D    5  6.9   0:44.12 aaaaa

We have filesystem quota setup, otherwise nothing else that I know of. I'd like to be able to limit VIRT RES SHR (perhaps just limiting 1 will limit the other 2?). Is this possible?
As well I would like to limit cputime before command is terminated (actually the command is called by another script, I assume the father script won't be terminated?).
I've had a look at limits.conf and PAM stuff, but not sure what is the best way, and how to test.

A: You want setrlimit(RLIMIT_AS, ...).  From the manpage (setrlimit(2)):

RLIMIT_AS
The maximum size of the process's virtual memory (address space) in bytes.  This limit affects calls to brk(2), mmap(2) and mremap(2),  which fail with the error ENOMEM upon exceeding this limit.  Also automatic stack expansion will fail (and generate a SIGSEGV that kills the process if no alternate stack has been made available via sigaltstack(2)).  Since the  value is a long, on machines with a 32-bit long either this limit is at most 2 GiB, or this resource is unlimited.


text:
Q: Al consultar la función me da el resultado en "null" como soluciono para que no me de null  create function calcula_subtotal (id integer,cantidad integer)
          returns int
          deterministic
          begin
             declare precio int;
             set precio = (select Precio from tbl_libros where isbn= id);
             return precio * cantidad;
          end//

A: La creación de la función como tal, está equivocada, modifícala y trata así:
create function calcula_subtotal(@id int, @cantidad int)
returns int as
          -- deterministic
BEGIN
          declare @precio int
             set @precio = (select Precio from tbl_libros where isbn= @id);
             return @precio * @cantidad
END

Luego:
select dbo.calcula_subtotal(111,2) RETORNO

El resultado sería:

Resultado

48

El DBFiddle para que lo veas detalladamente: https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=ce90b970ea2441e9ca0e5a4ce2e3ff11


text:
Q: objective c table view cell drawn before data source The data source for my UITableview cells is in:
- (void)connectionDidFinishLoading:(NSURLConnection *)conn {

    // We are just checking to make sure we are getting the XML
    NSString *xmlCheck = [[[NSString alloc] initWithData:xmlData encoding:NSWindowsCP1252StringEncoding] autorelease];
   // NSLog(@"xmlCheck2 = %@", xmlCheck);

    TFHpple *xpathParser = [[TFHpple alloc] initWithHTMLData:xmlData];
    for (int i=2; i<33; i++) {
        NSString *link=[NSString stringWithFormat:@"/html/body/table/tr[%d]/td",i];

        NSArray *elements = [xpathParser searchWithXPathQuery:link];

        NSString *date = [NSString stringWithFormat:@"%@, %@",[elements[5]text],[elements[1]text]];
        [times addObject:date];
        [names addObject:[elements[2]text]];
        [types addObject:[elements[3]text]];
        [places addObject:[elements[4]text]];

        NSLog(@"%@", elements);
        NSLog(@"%@", [elements[0] text]);
    }
}

But the method that draws the cell is called before the connection is finished even though the connection is started before I draw the cells. How do I delay the draw cell method or make sure the connection is finished before I draw the cells?

A: You need to set tableview's datasource & delegate properties only after you finish loading data.
    If you have set delegate & datasource of tableview from IB or Storyboard, remove it. Set delegate & datasource properties of tableview after you finish loading data. And reload table as well.
- (void)connectionDidFinishLoading:(NSURLConnection *)conn {

    // We are just checking to make sure we are getting the XML
    NSString *xmlCheck = [[[NSString alloc] initWithData:xmlData encoding:NSWindowsCP1252StringEncoding] autorelease];
   // NSLog(@"xmlCheck2 = %@", xmlCheck);

    TFHpple *xpathParser = [[TFHpple alloc] initWithHTMLData:xmlData];
    for (int i=2; i<33; i++) {
        NSString *link=[NSString stringWithFormat:@"/html/body/table/tr[%d]/td",i];

        NSArray *elements = [xpathParser searchWithXPathQuery:link];

        NSString *date = [NSString stringWithFormat:@"%@, %@",[elements[5]text],[elements[1]text]];
        [times addObject:date];
        [names addObject:[elements[2]text]];
        [types addObject:[elements[3]text]];
        [places addObject:[elements[4]text]];

        NSLog(@"%@", elements);
        NSLog(@"%@", [elements[0] text]);
    }

    [tableView setDelegate:self];// set delegate, datasource & reload data.
    [tableView setDatasource:self];
    [tableView reloadData];
}

A: that's the point of ASYNCHRONOUS networking :) Your main thread doesnt wait for it to finish! synchronous is there but it's bad
Have your UI handle the case that data isnt available yet.
a) set tableview hidden, show a spinning wheel and show and reload the table when connectionDidFinish is called
mock code
-viewWillAppear {
    table.hidden = YES;
    spinningActivity.hidden = NO;
    networkConnection start];
 }

-connectionDidFinish {
    spinningActivity.hidden = YES;
    [table reloadData];
    table.hidden = NO;
}

A: The method that provides cell information is only called if you tell it there are rows ready to display.  If you tell it the right thing in tableView:numberOfRowsInSection: -- which could be 0 if the connection hasn't finished -- there shouldn't be any incorrect calls to tableView:cellForRowAtIndexPath:.


text:
Q: VoiceOver not reading aria-label for links in iOS 10 VoiceOver is not reading aria-label for links. If the role is set to 'button' then it works. I could use 'title', which does work, but I that would require me to rewrite my code for links in my app. It did work in iOS 9.x, is there a work around for this?
Thx

A: This is an old question but it just popped up on my radar because it was modified today to have the wai-aria tag.
This problem was a real bug in iOS VoiceOver.  See https://bugs.webkit.org/show_bug.cgi?id=162578, but it was subsequently fixed in a couple .dot versions later.  It's working fine today with 12.1.4.
If, for some reason, there is a device still with iOS 10 and you need to work around the problem, you could use aria-describedby instead.  It wasn't broken.  The purpose of that attribute is slightly different from aria-labelledby, but it'd be a "good enough" hack for the time being.  But you'd have to go back and change aria-describedby back to aria-labelledby if the device was updated to a new iOS.


text:
Q: Python - Append string to existing lines of a file I have an origin file (fo.log) like below:
title1  title2  title3
o11     o12     o13
o21     o22     o23
o31     o32     o33

And a destination file (fd.log) like below:
d11   d12
d21   d22
d31   d32

Both files have the same number of lines (that could be millions of lines), except for the title line of the origin file. Thinking about memory usage, I don't want to read all lines to memory.
After processing my script, I would like to have the destination file (fd.log) like below:
d11   d12   o13
d21   d22   o23
d31   d32   o33

which means that I took the last information of each origin file line and appended it to the corresponding destination line.
Correspondence between lines from one file to another is just the line position and there is nothing to do with the information on it.
The closest script I could do is written bellow and it correctly prints the information I want.
from pathlib import Path

file_from = Path("path-to-origin-file/fo.log").open()
file_to = Path("path-to-destination-file/fd.log").open()

# create an enumerator to iterate over origin file lines
eft = enumerate(file_to)

# skip the first line with titles
next(eft)

for line_counter,line_to in eft:
    print(' '.join([
                line_to.rstrip('\n'),
                file_from.readline().split()[2]]))

file_from.close()
file_to.close()

A: For small enough files you can prepare the file contents as a list or a string and then write it to the file, e.g.:
from pathlib import Path

with Path('in-file').open() as in_file, Path('out-file').open('r+') as out_file:
    lines = []

    for line1, line2 in zip(in_file.readlines()[1:], out_file.readlines()):
        line = '{}   {}\n'.format(line2.rstrip(), line1.split()[-1])
        lines.append(line)

    out_file.seek(0)  # rewind the output file to the beginning
    out_file.writelines(lines)

For bigger files consider using a backup file as stdlib's fileinput module does.

A: with open('newfile.csv' 'r+b') as f:
    for line_counter,line_to in eft:
        print(' '.join(
            [line_to.rstrip('\n'),
            file_from.readline().split()[2]])
        )

A: with open('text1.txt', 'r') as istr:
    with open('text2.txt', 'r+') as ostr:
        iistr = istr.readlines()
        oostr = ostr.readlines()
        fstr = zip(iistr[1:], oostr)
        output_lines = []
        for iline, oline in fstr:
            # Get rid of the trailing newline (if any).
            output_lines.append(oline.rstrip('\n') + '  ' + iline.split()[2] + '\n')

        ostr.seek(0)
        ostr.writelines(output_lines)


text:
Q: Dúvida com switch no JavaScript Estou fazendo um curso de JavaScript, e preciso fazer um exercício com o enunciado "Escreva uma função que dado um total de anos de estudo retorna o quão experiente o usuário é."
Meu código:

function experiencia(anos) {
  switch (anos) {
    case 1:
      anos <= 1
      return 'Iniciante'
    case 2:
      anos > 1 && anos <= 3
      return 'Intermediário'
    case 3:
      anos >= 4 && anos <= 6
      return 'Avançado'
    default:
      anos > 7
      return 'Jedi'
  }
}

var anosEstudo = 3;
console.log(experiencia(anosEstudo));

Porém, ele printa no console 'Avançado'. Deveria ser 'Intermediário'.
Onde está o erro com esse código?

A: Note que no seu caso, se anos tiver exatamente o valor 7, não cairia em nenhum dos cases e nem no default. Acho que a condição do default deveria ser >= 7 ao invés de > 7.
O bloco switch serve para relacionar cada case com exatamente um único valor. Não dá para você mapear um case para uma faixa de valores dessa forma. Não existe isso de colocar uma expressão após o case ou o default tal como você estava tentando fazer. Não é assim que o switch funciona.
Aqui está um exemplo válido do switch. Note que cada case mapeia exatamente um valor:

function experiencia(anos) {
    if (anos < 0) return 'Impossível';
    switch (anos) {
        case 0:
        case 1:
            return 'Iniciante';
        case 2:
        case 3:
            return 'Intermediário';
        case 4:
        case 5:
        case 6:
            return 'Avançado';
        default:
            return 'Jedi';
    }
}

for (var i = -2; i <= 10; i++) {
    document.write(i + " anos: " + experiencia(i) + ".
");
}

Mas, há um truque que pode ser feito para forçar o switch a funcionar com intervalos ao colocar as expressões nos cases e true no switch:

function experiencia(anos) {
    switch (true) {
        case anos >= 0 && anos <= 1:
            return 'Iniciante';
        case anos > 1 && anos <= 3:
            return 'Intermediário';
        case anos >= 4 && anos <= 6:
            return 'Avançado';
        case anos >= 7:
            return 'Jedi';
        default:
            return 'Impossível';
    }
}

for (var i = -2; i <= 10; i++) {
    document.write(i + " anos: " + experiencia(i) + ".
");
}

Isso funciona porque JavaScript é uma linguagem interpretada com tipagem fraca. Em outras linguagens que também têm o switch mas que são compiladas, tais como C, C++, Objective-C, C# e Java, isso daí não funciona.
No entanto, se você for fazer uma coisa dessa, talvez abrir mão do switch e utilizar ifs seria mais fácil:

function experiencia(anos) {
    if (anos < 0) return 'Impossível';
    if (anos <= 1) return 'Iniciante';
    if (anos <= 3) return 'Intermediário';
    if (anos <= 6) return 'Avançado';
    return 'Jedi';
}

for (var i = -2; i <= 10; i++) {
    document.write(i + " anos: " + experiencia(i) + ".
");
}

Ou então você poderia usar o operador ternário:

function experiencia(anos) {
    return anos < 0 ? 'Impossível'
            : anos <= 1 ? 'Iniciante'
            : anos <= 3 ? 'Intermediário'
            : anos <= 6 ? 'Avançado'
            : 'Jedi';
}

for (var i = -2; i <= 10; i++) {
    document.write(i + " anos: " + experiencia(i) + ".
");
}

Na opinião de muita gente (minha inclusive), os switches são construções de linguagem horrorosas que nem deveriam existir. Em 99% das vezes que um switch é utilizado, existe alguma outra coisa que poderia ser utilizada em seu lugar que seria muito melhor ou no mínimo tão boa quanto.

A: Resumindo um pouco a resposta do Sam, o mais indicado aí seria o uso de um bloco if-else no lugar do switch, pois aí vc já faz o retorno conforme o valor de uma condição já testada.

function experiencia(anos) {
  if(anos == 0 || anos == 1){
    return 'Iniciante';
  } else if(anos > 1 && anos <= 3){
    return 'Intermediário';
  } else if(anos >= 4 && anos <= 6){
    return 'Avançado';
  } else if(anos > 7) {
    return 'Jedi';
  } else {
    return 'Impossível';  // caso digite nº negativos
  }
}

var anosEstudo = -10;
console.log(experiencia(anosEstudo));

A: Você enviou para a o switch o valor 3 pela variável anos. Com isso irá acessar o case 3.
Logo o return 'Avançado' será a única resposta. O código em case 2 jamais será acessado porque o valor passado ao switch não foi 2. Além do que as "comparações" feitas dentro de cada case são ignoradas porque não dizem nada, não estão dentro de um if, que seria o método para comparar valores.
E mesmo que você coloque todas as comparações dentro de um if, apenas a do case 3 será acessada, e retornaria undefined porque a variável anos (3) não se encaixaria na condição >= 4 && anos <= 6.
Resumindo, ao enviar o valor 3 para o switch, apenas o bloco case 3 será acessado.

A:


text:
Q: URL Images not playing videos with Augmented Reality (AR) Android I am implementing a bring Images to life feature, this is the blog that I was following, and I tried to convert the URL image to bitmap but it seems not connecting to a local video.
I am using Picasso, to download the image as a bitmap from a URL but it can't seem to be working.
Below is my code :
override fun getSessionConfiguration(session: Session): Config {

        fun loadAugmentedImageBitmap(imageName: String): Bitmap =
            requireContext().assets.open(imageName).use { return BitmapFactory.decodeStream(it) }

        val loader = activity?.applicationContext?.let { Coil.imageLoader(it) }

        var hashMap: HashMap<String, String> = HashMap<String, String>()

        hashMap.put(
            TEST_VIDEO_1,
            "https://res.cloudinary.com/do6g6dwlz/image/upload/v1594037658/lofsos15kot28ymz9fwb.jpg"
        )
        hashMap.put(
            TEST_VIDEO_2,
            "https://res.cloudinary.com/do6g6dwlz/image/upload/v1594038114/ijl9ngoomay9mleifv88.jpg"
        )
        hashMap.put(
            TEST_VIDEO_3,
            "https://res.cloudinary.com/do6g6dwlz/image/upload/v1594038131/po2fp4mviqsqkvwpztpe.jpg"
        )

        fun setupAugmentedImageDatabase(config: Config, session: Session): Boolean {
            try {
                config.augmentedImageDatabase = AugmentedImageDatabase(session).also { db ->

                    for ((key, value) in hashMap) {

                        print("load URL ---- $value")

                        Picasso.get().load(value).into(object : com.squareup.picasso.Target {
                            override fun onPrepareLoad(placeHolderDrawable: Drawable?) {
                                Toast.makeText(context,"Loading Images",Toast.LENGTH_SHORT).show()
                            }

                            override fun onBitmapFailed(
                                e: java.lang.Exception?,
                                errorDrawable: Drawable?
                            ) {
                                Toast.makeText(context,"Something wrong happened",Toast.LENGTH_SHORT).show()
                            }

                            override fun onBitmapLoaded(
                                bitmap: Bitmap?,
                                from: Picasso.LoadedFrom?
                            ) {
                                db.addImage(key, bitmap)
                            }

                        })
                    }
                }
                return true
            } catch (e: IllegalArgumentException) {
                Log.e(TAG, "Could not add bitmap to augmented image database", e)
            } catch (e: IOException) {
                Log.e(TAG, "IO exception loading augmented image bitmap.", e)
            }
            return false
        }

        return super.getSessionConfiguration(session).also {
            it.lightEstimationMode = Config.LightEstimationMode.DISABLED
            it.focusMode = Config.FocusMode.AUTO

            if (!setupAugmentedImageDatabase(it, session)) {
                Toast.makeText(
                    requireContext(),
                    "Could not setup augmented image database",
                    Toast.LENGTH_LONG
                ).show()
            }

  }
    }

This is the entire class and as well as the repository link
NOTE:
When both the Images and Videos are in the local project, it works fine, but trying to access both via URL  it doesn't work.

A: Please try this
try {
                hasmap.map {
                    addImage(key, convertURLtoBitmap(your_URL(value)), 0.5f)
                    Log.e(TAG, "bitmap added SuccessFully")
                }

for convertURLtoBitmap
private fun convertURLtoBitmap(your_url: String?): Bitmap? {

    return Glide.with(context)
        .asBitmap()
        .diskCacheStrategy(DiskCacheStrategy.DATA)
        .load(your_url)
        .submit()
        .get()
}


text:
Q: I want an implementation for LeaderRank algorithm Is there someone who has implemented LeaderRank? I have tried to program it in Python but without a result - so could anyone help me?
This is the code that I tried :
def leaderrank(G):

    # Nombre de nœuds
    num_nodes = G.number_of_nodes()
    nodes = G.nodes()
    # Ajouter le nœuds au réseau et se connecter à tous les nœuds
    G.add_node(0)
    for node in nodes:
        G.add_edge(0, node)
    # Initialisation de la valeur LR
    LR = dict.fromkeys(nodes, 1.0)
    LR[0] = 0.0
    # Itération pour que la condition d'arrêt soit remplie
    while True:
        tempLR = {}
        for node1 in G.nodes():
            s = 0.0
            for node2 in G.nodes():
                if node2 in G.neighbors(node1):
                    s += 1.0 / G.degree([node2])[node2] * LR[node2]
            tempLR[node1] = s
        # Conditions de résiliation : pas de changement de la valeur du LR
        error = 0.0
        for n in tempLR.keys():
            error += abs(tempLR[n] - LR[n])

        if error == 0.0:

            break
        LR = tempLR
    # La valeur LR du nœud g est divisée en parts égales entre les autres nœuds et le nœud est supprimé.
    avg = LR[0] / num_nodes
    LR.pop(0)
    for k in LR.keys():
        LR[k] += avg

    return LR


text:
Q: how to hook beforeRouteEnter in NuxtJs I am trying to get the previous route for my nuxtjs app, so for i used beforeRouteEnter, but beforeRouteEnter is not firing.
i tried to add key in nuxt-link : and still not working..
<nuxt-link :key="$route.path" :to="'/services/'+service.id">

so here is my code:

  created: function(){
    console.log("created");
  },

  mounted: function(){
    console.log("mounted");
  },

  mounted: function(){
    console.log("mounted");
  },

  beforeRouteEnter(to, from, next) {

    console.log("before route called");

    next(vm => {
      console.log("prev rout is: "+vm.prevRoute);
    })

  }

i expected :
before route called
prev rout is: /services
created
mounted

but i only get :
created
mounted

Is there anything that i'm doing wrong?

A: Trying your code in my current project based on nuxt ˆ2.0.0, I report to you my dev tools console, after navigation from / route to /_slug route.
_slug.js:200 before route called
_slug.js:192 created
_slug.js:198 mounted
_slug.js:205 prev rout is: undefined

When I refresh the page _slug is the same.
If you want the previous route why don't simply do:
beforeRouteEnter(to, from, next) {
   console.log("before route called");
   const previousRoute = from.path || from.fullPath
   console.log(`Previous Route ${previousRoute}`)
}

Which log is:
_slug.js:200 before route called
_slug.js:202 Previous Route /


text:
Q: Select a custom date range period to retrieve results from last month day I have a lot of data with a lot of dates (date begin, date end, date activation etc.). I would like to retrieve those data selecting a specific time range and returning a period date.
I want only results where:
(last month date) <= Date Activation and (last month date) > Date End
+ return the column containing the period
If I select a unique period:
select "client Name","Program" from "database"."schema"."table"
WHERE "Date Activation" <= '2020-12-31' AND "Date End" > '2020-12-31'

The aim is to retrieve results like this (I want it for all periods in my table):

client Name
Program
period

client 1
program 1
2020/11/30

client 2
program 2
2020/12/31

client 3
program 3
2020/12/31

client 3
program 3
2021/01/31

client 1
program 1
2021/01/31

client 2
program 4
2021/02/28

A: This should achieve what you want:
-- set parameter to be used as generator "constant" including the start day
-- set start and end dates to match the date range you want to report on
set num_days =  (Select datediff(day, TO_DATE('2020-01-01','YYYY-MM-DD'), current_date()+1));

-- generate all the dates between the start and end dates
with date_list as (
  select
    dateadd(
      day,
      '-' || row_number() over (order by null),
      dateadd(day, '+1', current_date())
    ) as date_val
  from table (generator(rowcount => ($num_days)))
),
-- create a distinct list of month-end dates from the list of dates
month_list as (
  select distinct last_day(date_val) as month_end
  from date_list
)

-- Join the list of month-end dates to your data table
select
cpd.client_name
,cpd.program
,ml.month_end
from month_list ml
inner join client_project_data cpd on cpd.Date_Activation <= ml.month_end and cpd.Date_End > ml.month_end;

-- clean up previously set variable
-- unset num_days;

A: I believe this is how you would get the first two columns:
SELECT DISTINCT "client Name", "Program"
FROM "database"."schema"."table"
WHERE "Date Activation" < "Date End" AND LAST_DAY("Date Activation") <> LAST_DAY("Date End")

But with the third one you will have to get creative.
If the difference between "Date Activation" and "Date End" can only be one month, then LAST_DAY("Date Activation") would do it.
But if the difference is bigger, then you will probably need two or more month ends to list. You should form some kind of array of month ends which are between "Date Activation" and "Date End". And the you would need to make separate rows out of such array.


text:
Q: Multi-dimensional arraylist or list in C#? Is it possible to create a multidimensional list in C#?
I can create an multidimensional array like so:
 string[,] results = new string[20, 2];

But I would like to be able to use some of the features in a list or arraylist like being able to add and delete elements.

A: you just make a list of lists like so:
List<List<string>> results = new List<List<string>>();

and then it's just a matter of using the functionality you want
results.Add(new List<string>()); //adds a new list to your list of lists
results[0].Add("this is a string"); //adds a string to the first list
results[0][0]; //gets the first string in your first list

A: Not exactly. But you can create a list of lists:
var ll = new List<List<int>>();
for(int i = 0; i < 10; ++i) {
    var l = new List<int>();
    ll.Add(l);
}

A: You can create a list of lists
   public class MultiDimList: List<List<string>> {  }

or a Dictionary of key-accessible Lists
   public class MultiDimDictList: Dictionary<string, List<int>>  { }
   MultiDimDictList myDicList = new MultiDimDictList ();
   myDicList.Add("ages", new List<int>());
   myDicList.Add("Salaries", new List<int>());
   myDicList.Add("AccountIds", new List<int>());

Generic versions, to implement suggestion in comment from @user420667
  public class MultiDimList<T>: List<List<T>> {  }

and for the dictionary,
   public class MultiDimDictList<K, T>: Dictionary<K, List<T>>  { }

  // to use it, in client code
   var myDicList = new MultiDimDictList<string, int> ();
   myDicList.Add("ages", new List<T>());
   myDicList["ages"].Add(23);
   myDicList["ages"].Add(32);
   myDicList["ages"].Add(18);

   myDicList.Add("salaries", new List<T>());
   myDicList["salaries"].Add(80000);
   myDicList["salaries"].Add(100000);

   myDicList.Add("accountIds", new List<T>());
   myDicList["accountIds"].Add(321123);
   myDicList["accountIds"].Add(342653);

or, even better, ...
   public class MultiDimDictList<K, T>: Dictionary<K, List<T>>
   {
       public void Add(K key, T addObject)
       {
           if(!ContainsKey(key)) Add(key, new List<T>());
           if (!base[key].Contains(addObject)) base[key].Add(addObject);
       }
   }

  // and to use it, in client code
    var myDicList = new MultiDimDictList<string, int> ();
    myDicList.Add("ages", 23);
    myDicList.Add("ages", 32);
    myDicList.Add("ages", 18);
    myDicList.Add("salaries", 80000);
    myDicList.Add("salaries", 110000);
    myDicList.Add("accountIds", 321123);
    myDicList.Add("accountIds", 342653);

EDIT:  to include an Add() method for nested instance:
public class NestedMultiDimDictList<K, K2, T>:
           MultiDimDictList<K, MultiDimDictList<K2, T>>:
{
       public void Add(K key, K2 key2, T addObject)
       {
           if(!ContainsKey(key)) Add(key,
                  new MultiDimDictList<K2, T>());
           if (!base[key].Contains(key2))
               base[key].Add(key2, addObject);
       }
}

A: Depending on your exact requirements, you may do best with a jagged array of sorts with:
List<string>[] results = new { new List<string>(), new List<string>() };

Or you may do well with a list of lists or some other such construct.

A: If you want to modify this I'd go with either of the following:
List<string[]> results;

-- or --
List<List<string>> results;

depending on your needs...


text:
Q: Image resize inside of an anchor tag I'm currently trying to style a page in NextJS. I have an image inside an anchor inside a div. I want to resize the image but no matter what I try, it doesn't seem to work.
I've tried applying properties to all three elements, each one individually, and two at a time.
The relevant code:

Title

Lorem ipsum etc..

.projectContainer {
  display: inline-block;
  width: 100vw;
  height: 10vh;
}

.projectDescriptionContainer {
  display: inline-block;
  width: 20vw;
  height: 10vh;
}

.projectPhotoContainer {
  display: inline-block;
  width: 20vw;
  height: 20vh;
}

.projectLink {
  display: inline-block;
}

.img {
  object-fit: cover;
  width: 100%;
  height: auto;
}

A: The link does not have any width size. add:
.projectLink {
  display: inline-block;
  width:100%;
}

Also, Your object-fit: cover; needs a height. auto won't work

A: Right, it's been a while this question has been asked, since I was in same situation few days ago and figured this out, I just wanna share it.
You have to work on the anchor tag, make sure to add the inline CSS code:
example- image is here

It will work mate!


text:
Q: Reduce Loopback4 build times in development (build + restart dev server) I am using Loopback4 to develop api in Node.
I was using the instruction given to build and watch with nodemon
It worked, but it was getting slow, like about 15 seconds in my case.
I search for other other solution and came up with idea of using Turborepo and the nodemon solution.
I wanted to know if there are better solutions or any issues with it
Gist of the solution

*

*run build in watch mode and restart the dev server if js files in dist folder change

*use Turbo repo to run these build and restart server tasks

Steps

*

*Setup build and watch with nodemon as described in the thread
you should have something like this in the script

  "scripts": {
   "dev:server:watch": "nodemon server.js"
  }

 // watch src folder
 // ignore dist
 // ext only ts files
 // npm start to start the dev server on any changes to the files
 "nodemonConfig": {
   "verbose": true,
   "watch": [
     "src/"
    ],
    "ignore": [
      "dist/*"
    ],
    "ext": "ts",
    "exec": "npm start"
 }

*

*Install turbo build system

yarn add turbo --dev

*

*Update nodemon config to restart server on changes in js files in dist folder after build step

 "nodemonConfig": {
    "verbose": true,
    "watch": [
      "./dist/"
    ],
    "ext": "js",
    "exec": "yarn run start"
  },

*

*Add turbo.json

{
    "pipeline": {
        "dev": {
            "dependsOn": ["build:watch", "dev:server:watch"]
        },
        "build:watch": {
            "outputs": [
                ".dist/**"
            ]
        },
        "lint": {
            "outputs": []
        }
    }
}

*

*Add dev script in package.json "scripts"

 "dev": "turbo run dev",

*

*Run

 yarn run dev

This seems to have reduced the build times to about 3 seconds
Can anyone confirm if this is an acceptable solution, points out any issues
Thanks


text:
Q: Relativity, and Lenz's law with respect to the Lorentz force acting on a wire? For this system:

It's simple for me to predict the induced EMF, and if the wire were connected to a complete circuit(for current $I$ to flow), the opposing Lorentz force($-F$):

However, if the uniform magnetic field was produced by a solenoid, and we now fixed the wire and moved the solenoid away from the wire with the same  $\| \mathbf{v} \|$ such as this diagram:

From the principle of relativity, I know that the wire would produce the same EMF as the second diagram,and possibly the same Lorentz force? Yet, how can that be true? Wouldn't the wire try to resist the change? Like so:

Related question.

A: I think the resolution to the op is quiet simple and the entire paradox is because the solenoid in the third figure, should be moving to the left and not to the right! (If you are in a car moving to the right, then according to you the trees are moving in the opposite direction, ie to the left!) In other words, the system:

in the reference frame of the wire looks like so:

and if you close the circuit it will be:

Note that in both reference frames the force acts in a way that resists the change as expected.


text:
Q: How to check multiple R columns for a value? I have an R dataframe with hundreds of columns which can contain a number. The columns all follow a naming scheme like:
1_parameter, 2_parameter, 3_parameter, ...

I want to filter for the rows where any of the above mentioned columns contains, lets say the number 97. How can I do this, instead of using an explicit filter like the dplyr command given below, where I have to write every single column explicitly?:
filter(1_parameter==97 | 2_parameter==97 | ...)

A: Something like this (assuming your data is named df)
# get the column names that follow this pattern
cols = grepl("[0-9]+_parameter", names(df))
# see if any of those columns have a 97
any(df[cols] == 97)

A base R way to filter for rows that have a 97 in any of those columns is this:
df[rowSums(df[cols] == 97) > 0, ]

A: Using dplyr:
df %>%
     filter_at(vars(ends_with("_parameter")), any_vars(. == 97))

A: In the new version of dplyr, the option would be
library(dplyr)
library(purrr)
 df %>%
    filter(across(ends_with('parameter'), ~ . == 97) %>% reduce(`|`))


text:
Q: angular reactive form - disabling control after changes not working I am having trouble updating a reactive form so that an input that was enabled is then disabled.  I am using Angular 8 and have tested using FF, Chrome, and Edge.
I have a component that shows a form.  The form represents an object that the component receives via an EventEmitter.  When an object is emitted, a new form is created.  Under certain conditions, controls that were enabled should be disabled after an update/new object.  However, on the web page, the input field stays enabled.  I've tried simplifying the case below.  I have verified that disable command to the form control for field2 below is called, but the input on the page does not disable.  Code on stackblitz here: https://stackblitz.com/edit/angular-xjqmjc
If there is a better way to accomplish this functionality, please let me know!  Thanks!
import {Component, EventEmitter, Input, OnInit} from "@angular/core";
import {FormBuilder, FormGroup} from "@angular/forms";
import {MyObject} from '../my-object';

@Component({
  selector: 'my-form',
  templateUrl: './my-form.component.html'
})
export class MyFormComponent implements OnInit {
    @Input() objectStream: EventEmitter<MyObject>;

  form: FormGroup = new FormGroup({});
  initialized: boolean = false;

  constructor(private fb: FormBuilder) {}

  ngOnInit(): void {
    this.objectStream.subscribe( (obj: MyObject) => {
      this.setupForm(obj);
    });
  }

  private setupForm(obj: MyObject): void {
    console.log("setting up form for", obj);
        let form: FormGroup = this.fb.group({
      field1: [obj.field1],
      field2: [obj.field2],
      field3: [obj.field3]
    });

    form.get("field1").disable(); //always disabled

    if(obj.condition) {
      form.get('field2').disable();
      console.log("the field was disabled!");
    }

    setTimeout( () => {
      this.form = form;
      this.initialized = true;
    });
  }
}

The form html code:

  <form novalidate [formGroup]="form">

        Field One

          <input type="text" formControlName="field1">

        Field Two

          <input type="text" formControlName="field2">

        Field Three

          <input type="text" formControlName="field3">

  </form>

A: The reason your form is not being disabled is because you are calling the setup form let form rather than the FormGroup that was created: this.form. If we take a look at how your app is run, we can find the issue.
In the my-form.component, you are subscribing to the object stream, and once this comes in, you are setting up a form with the obj: setupForm(obj: MyObject)...
Within this function you are setting up the form, and then checking if the obj has a condition. If so, you want to disable the form, but the form has already been created (on the first OnInit instance).
The simple change to get this to work is to change your if() statement within the setupForm(... function to the following:
In my-form.component.ts in the private setupForm(... change from:
if(obj.condition) {
   form.get('field2').disable();
   console.log("the field was disabled!");
}

to:
if(obj.condition) {
   this.form.get('field2').disable();
   console.log("the field was disabled!");
}

This will now disable the actual FormGroup rather than the variable you set up within the statement. Since you are using an if condition after setting up the form variable, this is the best approach to disable the FormGroup being used (this.form).
HERE is the updated StackBlitz, let me know if you have any questions


text:
Q: insert key-values to associative array in php from file I can't insert values from file into php associative array. Can anyone help?
The code is below, look at 3rd array item, I'd like to insert key-values from file, but every time I get en error. How to do that? (include, echo, or function result - doesn't work inside array!). How to do that?
<?
$somedeclaredvaiable = '0 => "value1", 1 => "value2", 2 => value3", 3 => "value4", 4 => "value5", 7 => 4';

$a = array(
1 => array(
   0 => "value1",
   1 => "value2",
   2 => "value3",
   3 => "value4",
   4 => "value5",
   7 => 4

),
2 => array(
   0 => "value1a",
   1 => "value2a",
   2 => "value3a",
   3 => "value4a",
   4 => "value5a",
   7 => 4
),
3 => array(
//THE PROBLEM IS HERE, can't include file, or echo an variable!
include 'filewitharray.txt';  //doesn't work
echo $somedeclaredvariable ;  //doesn't work
),
);

?>

A: This part of your code is syntactically incorrect :
3 => array(
//THE PROBLEM IS HERE, can't include file, or echo an variable!
include 'filewitharray.txt';  //doesn't work
echo $somedeclaredvariable ;  //doesn't work
),

Assuming that filewitharray.txt is a php file that would be returning an array (or something else), like this :
<?php
    return array('foo' => 'bar');

Then, you could do :
$a[] = require 'filewitharray.txt';

It will add the variable returned by filewitharray.txt into your table.
If filewitharray.txt is not supposed to be PHP code and you want the content of the file to be added into the array (as a string), then you could do :
<?php

$a[] = file_get_contents('filewitharray.txt');

A: Try it now.
<?php

  include 'filewitharray.txt';

    $somedeclaredvaiable = '0 => "value1", 1 => "value2", 2 => value3", 3 => "value4", 4 => "value5", 7 => 4';

    $a = array(
    1 => array(
       0 => "value1",
       1 => "value2",
       2 => "value3",
       3 => "value4",
       4 => "value5",
       7 => 4

    ),
    2 => array(
       0 => "value1a",
       1 => "value2a",
       2 => "value3a",
       3 => "value4a",
       4 => "value5a",
       7 => 4
    ),
    3 => array(

    ),
    );

    ?>

A: First, get the contents of the file beforehand:
$included = file_get_contents("file with array.txt");

Then in your array declaration:
...snip
3 => array(
    $included, $somedeclaredvariable
)
);


text:
Q: Error ORA-12560 using Toad I am using toad with Oracle now, and after the installation, I tried to connect using toad, but an error pops up:

ORA-12560: TNS:protocol adapter error

I have already tried to set the ORACLE_HOME and PATH environment variables but the issue is still here.
Could anybody help me with this?
p.s. I tried to start the listener but the NCA won't proceed to completion on my computer.


text:
Q: How can I get data from my import.io api servers I'm trying to get data from import.io servers but till now I got nothing. But when I use another api from another server with same code I get the data. Can you tell me what I'm doing  wrong.
This is working code, the problem is that I got nothing from import.io servers. but when I use another url from another service like kimonolabs I get data from this same code. Sorry my bad english.
I got this response code: 200
This is my code.
document.addEventListener('deviceready', onDeviceReady, false);

function onDeviceReady() {
    //console.log('device is ready');
    $.ajax({
        type: 'GET',
        url: 'https://api.import.io/store/data/6847842b-a779-46ba-874a-d1cfdcef2e3e/_query?input/webpage/url=http%3A%2F%2Fwww.girabola.com%2F%3Fp%3Djogos%26epoca%3D62%26jornada%3D1&_user=779609bc-1bfe-4bb3-aa45-465a3fc31d9a&_apikey=MY API KEY',
        dataType: 'jsonp',
        success: function(data) {

            console.log(data); //The log dont show me nothing.

            var output = '';
            //output += '
';

            output += '
';
            output += '
Equipa Técnica
';
            console.log(data);

            $(data.results).each(function(index, value) {
                output += '
' + this.casa + '
';
            });

            output += '
';

            $('#um').append(output).listview().listview('refresh');
        }
    });
}

A: the problem of your request is the datatype. You set dataType: 'jsonp' while you didn't add a callback parameter like described here.
I'm not sure if the API that you're querying is JSONP-ready but I tried with CORS and it works successfully. So if you use jQuery 1.5+, replace your ajax request with these options:
document.addEventListener('deviceready', onDeviceReady, false);
function onDeviceReady() {
    //console.log('device is ready');
    $.ajax({
        type: 'GET',
        url: 'https://api.import.io/store/data/6847842b-a779-46ba-874a-d1cfdcef2e3e/_query?input/webpage/url=http%3A%2F%2Fwww.girabola.com%2F%3Fp%3Djogos%26epoca%3D62%26jornada%3D1&_user=779609bc-1bfe-4bb3-aa45-465a3fc31d9a&_apikey=MY API KEY',
        dataType: 'json',
        crossDomain: true,
        success: function(data) {

            // Your code
        }
    });
}

If you want to know more about jQuery ajax options, have a look there. I hope it will help you :)


text:
Q: SmartGWT databound ListGrid -> DateItem in column title, reload column onChanged My task is : a databound ListGrid with a column. The title of this column should be "Information for {infoDate in format DD-MM-YYYY}" + a DateItem (icon picker only) from which users can modify the infoDate which is by default the current date. The values in the column change, according to the date chosen.
So, I took an idea from this question How to add button in HeaderSpan of SmartGWT to reach to the code below. Unfortunately there is a problem : the DateItem doesn't seem clickable, it looks just like an image. Besides, I cannot remove the TextField, it is either a text field or 3 selectable option fields.
I suggest that taking the innerHTML doesn't take the function of the picker itself, as I tried with Calendar, DateChooser and DatePicker and it worked, but the problem there was the view (I need only the calendar icon that will open the DatePicker onClick).
Thank you in advance for any help or idea!
The imports:
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.Node;
import com.google.gwt.dom.client.NodeList;
import com.smartgwt.client.widgets.events.DrawEvent;
import com.smartgwt.client.widgets.events.DrawHandler;
import com.smartgwt.client.widgets.grid.ListGrid;

The code:
ListGrid infoTable = new ListGrid();
infoTable.setShowRecordComponents(true);
infoTable.setShowRecordComponentsByCell(true);
infoTable.setWidth100();
infoTable.setDataSource(dataSource);
infoTable.setCanEdit(false);
infoTable.setCanCollapseGroup(false);
infoTable.setCanFreezeFields(false);
infoTable.setCanGroupBy(false);
infoTable.setCanMultiSort(false);
infoTable.setCanSort(false);
infoTable.setCanResizeFields(false);
infoTable.setAutoFetchData(false);
infoTable.addDrawHandler(new DrawHandler() {
    public void onDraw(final DrawEvent event) {
        for (Element element : DOMUtils.getElementsByTagName("td")) {

            if (element.getInnerHTML().startsWith("Information for")) {
                DOMUtils.removeAllChildNodes(element);

                final DynamicForm cal = new DynamicForm();

                final DateItem infoDate = new DateItem();
                infoDate.setDefaultValue(new Date());
                infoDate.setTitle("Information for ");
                infoDate.setTitleAlign(Alignment.LEFT);
                infoDate.setWrapTitle(false);
                infoDate.setDisplayFormat(DateDisplayFormat.TOEUROPEANSHORTDATE);
                infoDate.setUseTextField(true);
                infoDate.setAlign(Alignment.RIGHT);
                infoDate.addChangedHandler(new ChangedHandler() {
                    public void onChanged(final ChangedEvent event) {
                        //fetch new data, according to the date selected);
                    }
                });

                cal.setFields(infoDate);

                element.setInnerHTML(cal.getInnerHTML());

            }
        }

        // fetch data from DataSource class
        infoTable.fetchData();
    }
});

And the class DOMUtils:
class DOMUtils {
public static void removeAllChildNodes(Element element) {
    NodeList<Node> childList = element.getChildNodes();
    for(int childIndex = 0; childIndex < childList.getLength(); childIndex++) {
        element.removeChild(childList.getItem(childIndex));
    }
}

public static Element[] getElementsByTagName(String tagName)
{
    JavaScriptObject elements = getElementsByTagNameInternal(tagName);
    int length = getArrayLength(elements);
    Element[] result = new Element[length];
    for (int i=0; i<length; i++)
    {
        result[i] = getArrayElement(elements, i);
    }
    return result;
}

private static native JavaScriptObject getElementsByTagNameInternal(String tagName)/*-{
return $doc.getElementsByTagName(tagName);
  }-*/;

private static native int getArrayLength(JavaScriptObject array)/*-{
return array.length;
  }-*/;

private static native Element getArrayElement(JavaScriptObject array, int position)/*-{
return (position>=0 && position<array.length?array[position]:null);
  }-*/;
}

A: Wow, no need for any of this. You can use setShowFilterEditor(true) and the default interface for a field of type "date" is going to look just like what you want, except the picker launched from the calendar icon is going to allow the user enter a range of dates, which seems more functional than what you want.
If you don't want to support arbitrary date ranges, use setFilterEditorType() to replace the default control with your own, more limited control.
If you don't want two lines of headers (the normal headers plus the filterEditor) just use setShowHeader(false).

A: Ok, so I found the way to do it : as I can't override the Header itself, I use a HeaderSpan with the height of the Header, in order to have only the HeaderSpan visible. However ATTENTION, it works fine on FF, but it causes errors in other parts of the application in IE. Here is the code; the class DOMUtils can be found in my 1st post:
// class MyDataSource extends com.smartgwt.client.data.DataSource
MyDataSource dataSource = MyDataSource.getInstance();

final HeaderSpan headerSpanCol1 = new HeaderSpan();
headerSpanCol1.setTitle("column 1");
headerSpanCol1.setFields(MyDataSource.A);
headerSpanCol1.setHeight(26);

final HeaderSpan headerSpanCol2 = new HeaderSpan();
// make sure not to have the same element name
headerSpanCol2.setTitle("Information for");
headerSpanCol2.setFields(MyDataSource.D);
headerSpanCol2.setHeight(26);

final HeaderSpan headerSpanCol3 = new HeaderSpan();
headerSpanCol3.setTitle("column 2");
headerSpanCol3.setFields(MyDataSource.B);
headerSpanCol3.setHeight(26);

infoTable = new ListGrid() {

  @Override
  protected Canvas createRecordComponent(final ListGridRecord record, final Integer colNum) {

      final String fieldName = this.getFieldName(colNum);

    // include some icons that I need in the ListGrid here

  }
};
infoTable.setShowRecordComponents(true);
infoTable.setShowRecordComponentsByCell(true);

infoTable.setWidth100();
// make height equal to HeaderSpan's in order to hide header titles and show only the HeaderSpan
infoTable.setHeaderHeight(26);
infoTable.setDataSource(dataSource);
infoTable.setCanEdit(false);
infoTable.setCanCollapseGroup(false);
infoTable.setCanFreezeFields(false);
infoTable.setCanGroupBy(false);
infoTable.setCanMultiSort(false);
infoTable.setCanSort(false);
infoTable.setCanAutoFitFields(false);
infoTable.setCanResizeFields(false);
infoTable.setCanPickFields(false);
infoTable.setAutoFetchData(false);
infoTable.addDrawHandler(new DrawHandler() {
public void onDraw(final DrawEvent event) {

   for (Element element : DOMUtils.getElementsByTagName("td")) {
       // iterate over the elements of the page to find the HeaderSpan to replace

       if (element.getInnerHTML().equals("Information for")) {
          // replace the title of this HeaderSpan with a DateItem
          DOMUtils.removeAllChildNodes(element);

          final DynamicForm cal = new DynamicForm();

         final DateItem infoDate = new DateItem();
         infoDate.setDefaultValue(new Date());
         infoDate.setTitle("Select date");
         infoDate.setWrapTitle(false);
         infoDate.setDisplayFormat(DateDisplayFormat.TOEUROPEANSHORTDATE);
         infoDate.setUseTextField(true);
         infoDate.setAlign(Alignment.RIGHT);
         infoDate.addChangedHandler(new ChangedHandler() {
             public void onChanged(final ChangedEvent event) {
                 // reload table with newly fetched results
             }
         }); // ChangedHandler

         cal.setFields(infoDate);
         element.insertFirst(cal.getElement());

 break;
} // if
    } // for

    // fetch data from DataSource class
  infoTable.fetchData();
} // onDraw
}); // DrawHandler

infoTable.setHeaderSpans(headerSpanCol1, headerSpanCol2, headerSpanCol3);


text:
Q: Mask timeseries outside business hours Hello I have an hourly timeseries that I would like to mask if the timeseries index is outside business hours.
I can achieve what I want for business day data but not hourly data
import datetime
import pandas as pd
import numpy as np
from pandas.tseries.offsets import *

st = datetime.datetime(2013, 1, 1)
ed = datetime.datetime(2013, 2, 1)
myrange = pd.date_range(st, ed, freq='H')
ts = pd.Series(np.random.randn(len(myrange)), index=myrange)
ts.asfreq(BDay()).asfreq(Day())

I have tried generating a BDay date range and then changing the freq to hourly but this doesn't work.
newrange = pd.date_range(datetime.datetime(2013, 1, 1), datetime.datetime(2013, 1, 1), freq='B')
#but adding this doesn't work .asfreq(Hour())
ts[ts.index.isin(newrange)].asfreq(Hour()) #Of course this only gives one value on the day

Thanks

A: To restrict your times to Business days you could use:
ts = ts.ix[ts.index.map(BDay())]

and indexer_between_time to restrict between business hours:
ts = ts.ix[ts.index.indexer_between_time(time(7), time(18))]

To restrict to Business days within business hours (apply these in either order).


text:
Q: Consequence of violation of independence assumption on estimates of standard errors from the first chapter , Introduction to Multilevel Analysis , p.5 of the book , it is written that :

Standard statistical tests lean heavily on the assumption
  of independence of the observations. If this assumption is violated (and in multilevel data this is almost always the case) the estimates of the standard errors of conventional statistical tests are much too small, and this results in many spuriously 'significant' results.

*

*When units are not independent within a cluster , why are the estimates of the standard errors of conventional statistical tests much too small ?

The formula of variance is  $$\mathbb V(X+Y)=\mathbb V(X)+\mathbb V(Y)+2\mathbb {cov}(X,Y)$$
It seems to me from the formula that standard small can smaller or larger if $X$ and $Y$ are independent . Then why is it mentioned that

*

*the estimates of the standard errors of conventional statistical tests much too small ? Only mentioned the word small , not large .

My 2nd question is :

Small dependencies in combination with large group sizes still result in large biases in the standard errors .

How can i measure that even small dependency causes large biases ? That is , I want to visualize the picture .


text:
Q: What causes import command to fail as running through a service Our System V service runs a daemon that runs the import command. Running our service by sudo service myservice start seems to start the service but when it comes to take a screenshot, import does not work. The only way to grab a screenshot is starting service with /etc/init.d/myservice start. Following that, we are able to grab the screenshot with import command.
Any ideas?

A: There is no straight forward answer to your question, other than "it depends on the environment" i.e. the GNU / Linux distribution.
Before I go into semi-relevant details, you should know that the reason why sudo service import-image-service does not work is because the import command does not have enough information about the environment to know where and how to take the screenshot. Reading man sudo reveals:
 DESCRIPTION
   sudo allows a permitted user to execute a command as the superuser or
   another user, as specified by the security policy.

This is somewhat cryptic and learning about this "security policy" is fun, but perhaps not one of your favourite activities. I give you my word that this means commands started with sudo run in an isolated environment.
In contrast, /etc/init.d/myservice works because environment-setup-policy takes steps to configure some sane defaults such as export DISPLAY=:0.0. You will have to investigate the intricacies of the distribution in use to figure out how to properly inform a service about the presence of an X server. In the mean time, you can try sudo -E service myservice
  -E      The -E (preserve environment) option indicates to the secu‐
       rity policy that the user wishes to preserve their existing
       environment variables.  The security policy may return an
       error if the -E option is specified and the user does not
       have permission to preserve the environment.

Some background
warning: this section is semi-factual and biased historically
The services in a GNU / Linux system behave somewhat arbitrarily from one distribution to the next. Mostly, the difference is in the setup of the environment before the service is run. This depends on several factors, the most important ones being:

*

*init system

*

*plain System V init + posix shell (Slackware, Debian)

*OpenRC (Gentoo)

*Upstart (Ubuntu)

*systemd (many recent distros)

*distributions environment-setup-policy*

*details of the particular init script

Debian, Slackware and Gentoo (OpenRC) use a conceivably similar approach where /etc/init.d/ services are independent scripts that optionally get additional information from /etc/default/servicename, /etc/conf.d/servicename and similar. The scripts may or may not rely on distribution-specific init-function such as /lib/lsb/init-functions or /lib64/rc/sh/functions.sh. These additional shell libraries may get information (set up the environment) from additional distribution-specific sources.
Ubuntu (Upstart) and systemd have an "entirely" different approach where each service has a configuration file and the init system does all the magic.
To fully understand what's going on, one has to read and understand the init system and the quirks of the distribution in use.
* the process of initializing environment variables and starting a service.

A: This is very clearly explained in the manual page for the Linux old System V service in the very first sentence:

service runs a System V init script in as predictable environment as possible, removing most environment variables and with current working directory set to /.

How do you think that the image command knows where to find your X server?  It's the DISPLAY environment variable of course.
Don't rely upon the notion that services run in an interactive login environment with controlling terminals, DISPLAY environment variables, and so forth.  They do not.  If you've designed a service based upon these assumptions, then you've designed it wrongly, and you've designed something that isn't even working for you now, let alone that will work should you use a different init system such as systemd, upstart, nosh, runit and so forth, all of which ensure that services are not affected by the arbitrary values of an interactive shell's environment variables (and other process state) when a service is brought up/down.


text:
Q: swift NSURL gets back an "unable to read data" message even with https:// I am trying to learn iOS following a course and they ask to do the following:
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    //var string1 = "http://www.google.com"
    //var string1 = "https://www.weather-forecast.com/locations/San-Antonio/forecasts/latest"
    //var url = NSURL(string: string1)
    var url = NSURL(string: "https://google.com")

    print(url)

        if url != nil {

            let task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in

                var urlError = false

                if error == nil {

                    var urlContent = NSString(data: data!, encoding: NSUTF8StringEncoding)
                    print(urlContent)

                } else {

                    urlError = true

                }

                if urlError == true {
                    self.showError()
                }
        })

            task.resume()

        } else {

            showError()

    }
}

the app doesn't show any web page content and when debugging I find that the object for the url says that it is "unable to read data"
I have tried with http and https. I have tried with different web sites.
I have tried the address in the safari of the simulator and it loads.
Can someone tell me why is this not working
Thanks in advance.
gariva

A: You're using wrong encoding. The webpage you're trying to fetch (http://www.google.com/) uses ISO-8859-1.

I was able to reproduce your issue. Fetch worked when I changed encoding. Try this:
 var urlContent = NSString(data: data!, encoding: NSISOLatin1StringEncoding)

A: For display web page you should use UIWebView element. Something like this:
        let url = NSURL(string: "https://google.com")
        let webView = UIWebView(frame: self.view.frame)
        self.view.addSubview(webView)
        webView.loadRequest(NSURLRequest(URL: url!))


text:
Q: Is there a locally compact space which is not a k-space Definitions:

A locally compact space is a space where every point has a local base of compact neighborhoods.
A $k$-space $X$ has its topology generated by maps from compact Hausdorff spaces, i.e. $C$ is closed iff for every compact Hausdorff space $K$ and every continuous function $f: K \to X$, $f^{-1}[C]$ is closed in $K$. Strickland's notes call this compactly generated.

By compact I mean not necessarily Hausdorff.
The reason I ask is that standard constructions of non $k$-spaces for example the square of the one-point compactification of $\mathbb{Q}$ and the product $\mathbb{R}\setminus \{1,\frac{1}{2},\frac{1}{3}\} \times \mathbb{R}/\mathbb{Z}$ where the second quotient means identifying $\mathbb{Z}$ to one point, are usually not locally compact.
I'm looking for a locally compact space which is not a $k$-space.

A: The answer is that, assuming AC, there are locally compact spaces which are not compactly generated. (That is, do not have topologies which are final with respect to all maps with compact Hausdorff domains. i.e. do not belong to the monocoreflective hull of the class of compact Hausdorff spaces as computed in $Top$.)
The construction of such a space is due to J. Isbell, A Distinguishing Example in k-Spaces, Proc. Am. Math. Soc. 100 (1987), 593-594. Below is my attempt at his details.
Let $X=\omega_1+1$, where $\omega_1$ is the first uncountable ordinal, and topologise $X$ by giving it the base of closed sets generated by $(i)$ countable initial segments $[0,\alpha]$, and $(ii)$ the singleton $\{\omega\}$. The space $X$ is our counterexample.

$X$ is locally compact.

Proof: Indeed, more is true: every subspace of $A\subseteq X$ is compact. For $A$, if nonempty, contains a least element, every neighbourhood of which contains all of $A$ except for possibly $\omega_1$. $\square$

$X$ is not compactly generated.

Proof: The claim is that there is a non-closed subspace $A\subseteq X$ with the property that whenever $f:K\rightarrow X$ is a continuous function with $K$ a compact Hausdorff space, the preimage $f^{-1}(A)$ is a closed subset of $K$. We will show that the open subspace $A=[0,\omega_1)$ has this property.
So take $K$ and $f$ as above and suppose $f^{-1}[0,\omega)\subset K$ is not closed. Fix a countable ordinal $\alpha_1$ and consider the closed set $f^{-1}[0,\alpha_1]\subseteq K$. This is disjoint from the closed set $K\setminus f^{-1}[0,\omega_1)$, so by normality of $K$ there are disjoint open sets $U_1,V_1\subset K$ with $f^{-1}[0,\alpha_1]\subseteq U_1\subseteq X\setminus V_1\subseteq f^{-1}[0,\omega_1)$. Because we are assuming that $f^{-1}[0,\omega_1)$ is not closed we have $X\setminus V_1\neq f^{-1}[0,\alpha)$, so in particular the inclusion $U_1\subseteq f^{-1}[0,\omega_1)$ is proper. Thus there is a countable $\alpha_2>\alpha_1$ for which there is a proper inclusion $U_1\subseteq f^{-1}[0,\alpha_2]$.
Now iterate the process to obtain a sequence of proper inclusions
$$f^{-1}[0,\alpha_1]\subseteq U_1\subseteq f^{-1}[0,\alpha_2]\subseteq U_2\subseteq\dots$$
Since $\bigcup_\mathbb{N}\alpha_i$ is countable, $\bigcup f^{-1}[0,\alpha_i]=f^{-1}(\bigcup [0,\alpha_i])$ is closed in $K$ and hence compact. On the other hand it is covered by the $U_i$, but by no finite subfamily of them. Thus there is a contradiction. It must be that $f^{-1}[0,\omega_1)$ is closed in $K$. $\square$
Remark: $(i)$ All that was needed of $K$ was its compactness and normality. A more general statement from which the proof flows is contained in Isbell's paper. $(ii)$ We quietly used the axiom of choice to ensure that $\bigcup\alpha_i$ as countable.

A: https://en.wikipedia.org/wiki/Compactly_generated_space In the example section it is said that locally compact space are $k$-space.

A: Surely yes. For every C$^*$-algebra $A$, the primitive ideal space $Prim(A)$ is locally compact (in the sense of each point having a neighbourhood base of compact sets) in the hull-kernel topology. But $Prim(A)$ is seldom Hausdorff.
What about the C$^*$-algebra $A$ of the bounded operators on a separable Hilbert space? Then $Prim(A)$ consists of the ideal $\{0\}$ and the ideal $K(H)$ of compact operators. Topologically it is a two-point $T_0$ space with one point open and the other point closed. Is that a $k$-space?


text:
Q: Using array of string in C I am just practicing to understand dynamic allocation in C. I am getting a segmentation fault error. I am not sure where I made mistake.
int wordcount = 5;
char **args = (char**)malloc(wordcount * sizeof(char*));

for ( int i = 0; i < wordcount; i++) {
    args[i] = (char*)malloc(167 * sizeof(char));
}

int c=0;
while(c < wordcount){
    strcpy("hello\n",  args[c]);
    c++;
}

A: You are trying to copy args[c] to the location of the "hello\n" string, which is in read only memory, you should change the order of the parameters.


text:
Q: Confluent kafkarest ERROR Server died unexpectedly Atleast one of bootstrap.servers or zookeeper.connect needs to be configured I am running Kafka via Confluent platform. I have followed the steps as per documented here, https://docs.confluent.io/2.0.0/quickstart.html#quickstart
start zookeeper,
$ sudo ./bin/zookeeper-server-start ./etc/kafka/zookeeper.properties

start kafka,
$ sudo ./bin/kafka-server-start ./etc/kafka/server.properties

start schema-registry command,
$ sudo ./bin/schema-registry-start ./etc/schema-registry/schema-registry.properties

All are running fine.
Next I want to run REST proxy commands, as per documented here, https://docs.confluent.io/2.0.0/kafka-rest/docs/intro.html#quickstart
$ sudo bin/kafka-rest-start

But this commands fail with the following error. (ERROR Server died unexpectedly:  (io.confluent.kafkarest.KafkaRestMain:63)
    java.lang.RuntimeException: Atleast one of bootstrap.servers or zookeeper.connect needs to be configured).
All are running fine. I don't understand why am I getting this error, could you please help solving this?
ESDGH-C02K648W:confluent-4.0.0 user$ sudo bin/kafka-rest-start
[2018-01-09 14:44:06,922] INFO KafkaRestConfig values:
    metric.reporters = []
    client.security.protocol = PLAINTEXT
    bootstrap.servers =
    response.mediatype.default = application/vnd.kafka.v1+json
    authentication.realm =
    ssl.keystore.type = JKS
    metrics.jmx.prefix = kafka.rest
    ssl.truststore.password = [hidden]
    id =
    host.name =
    consumer.request.max.bytes = 67108864
    client.ssl.truststore.location =
    ssl.endpoint.identification.algorithm =
    compression.enable = false
    client.zk.session.timeout.ms = 30000
    client.ssl.keystore.type = JKS
    client.ssl.cipher.suites =
    client.ssl.keymanager.algorithm = SunX509
    client.ssl.protocol = TLS
    response.mediatype.preferred = [application/vnd.kafka.v1+json, application/vnd.kafka+json, application/json]
    client.sasl.kerberos.ticket.renew.window.factor = 0.8
    ssl.truststore.type = JKS
    consumer.iterator.backoff.ms = 50
    access.control.allow.origin =
    ssl.truststore.location =
    ssl.keystore.password = [hidden]
    zookeeper.connect =
    port = 8082
    client.ssl.keystore.password = [hidden]
    client.ssl.provider =
    client.init.timeout.ms = 60000
    simpleconsumer.pool.size.max = 25
    simpleconsumer.pool.timeout.ms = 1000
    ssl.client.auth = false
    consumer.iterator.timeout.ms = 1
    client.sasl.kerberos.service.name =
    ssl.trustmanager.algorithm =
    authentication.method = NONE
    schema.registry.url = http://localhost:8081
    client.ssl.truststore.type = JKS
    request.logger.name = io.confluent.rest-utils.requests
    ssl.key.password = [hidden]
    client.sasl.kerberos.ticket.renew.jitter = 0.05
    client.ssl.endpoint.identification.algorithm =
    authentication.roles = [*]
    client.ssl.trustmanager.algorithm = PKIX
    metrics.num.samples = 2
    consumer.threads = 1
    ssl.protocol = TLS
    client.ssl.keystore.location =
    debug = false
    listeners = []
    ssl.provider =
    ssl.enabled.protocols = []
    client.sasl.kerberos.min.time.before.relogin = 60000
    producer.threads = 5
    shutdown.graceful.ms = 1000
    ssl.keystore.location =
    consumer.request.timeout.ms = 1000
    ssl.cipher.suites = []
    client.timeout.ms = 500
    consumer.instance.timeout.ms = 300000
    client.sasl.kerberos.kinit.cmd = /usr/bin/kinit
    client.ssl.key.password = [hidden]
    access.control.allow.methods =
    ssl.keymanager.algorithm =
    metrics.sample.window.ms = 30000
    client.ssl.truststore.password = [hidden]
    client.ssl.enabled.protocols = TLSv1.2,TLSv1.1,TLSv1
    kafka.rest.resource.extension.class =
    client.sasl.mechanism = GSSAPI
 (io.confluent.kafkarest.KafkaRestConfig:175)
[2018-01-09 14:44:06,954] INFO Logging initialized @402ms (org.eclipse.jetty.util.log:186)
[2018-01-09 14:44:07,154] ERROR Server died unexpectedly:  (io.confluent.kafkarest.KafkaRestMain:63)
java.lang.RuntimeException: Atleast one of bootstrap.servers or zookeeper.connect needs to be configured
    at io.confluent.kafkarest.KafkaRestApplication.setupInjectedResources(KafkaRestApplication.java:104)
    at io.confluent.kafkarest.KafkaRestApplication.setupResources(KafkaRestApplication.java:83)
    at io.confluent.kafkarest.KafkaRestApplication.setupResources(KafkaRestApplication.java:45)
    at io.confluent.rest.Application.createServer(Application.java:157)
    at io.confluent.rest.Application.start(Application.java:495)
    at io.confluent.kafkarest.KafkaRestMain.main(KafkaRestMain.java:56)
ESDGH-C02K648W:confluent-4.0.0 user$

A: The kafka-rest-start script takes a properties file as an argument. This is documented further down in the quick start you have linked.

A: The kafka-rest-start script takes a properties file as an argument. you must pass ./etc/kafka-rest/kafka-rest.properties in command line.
bin/kafka-rest-start ./etc/kafka-rest/kafka-rest.properties


text:
Q: Remove the last item from feature group in Leaflet I just need to delete the last item in a featuregroup.
This code gives me that I have TWO objects in in the featureGroup featRouteL:
console.log("so many objects: "+featRouteL.getLayers().length);

Now, I just want to delete the LAST item. But how do I do that? I have tried so far but get error no matter what direction I go. I think I should get the id of the last layer item and then delete this layer id. Unfortunatly I get errors no matter what I do...
            var xlayers = featRouteL.getLayers();
            var xlength = xlayers.length;
            console.log("no of layers: "+xlength); //this gives me the correct no

            xlayers.forEach(function(layer) {
                //xlayers.removeLayer(layer); // -> xlayers.removeLayer is not a function
                //console.log(layer.get("name")); // -> layer.get is not a function
                //console.log(layer.getLayerId()); // -> Cannot read property '_leaflet_id' of undefined
            });

            console.log("layers: "+xlength);

            //for (var i = 0; i < xlength; i++) {
                //l = xlayers.item(i); //-> xlayers.item is not a function
            //}

A: If just want to remove the last layer in the array of layers you get with featRouteL.getLayers() call, that's easy:
var layers = featRouteL.getLayers();
layers[layers.length - 1].remove();

Question here is if this is really the layer you want to remove.


text:
Q: Configure nginx as reverse proxy http uri -> private individual servers I have a server, with no domain set on it. I access it by ip on port 80. I have IIS on it with 3 websites on ports 8080, 8081, 8082.
All I want is when someone enters SERVER_IP/foo1, nginx show content from 192.168.1.100:8080
SERVER_IP/foo2 -> 192.168.1.100:8081
SERVER_IP/foo3 -> 192.168.1.100:8082
these private servers are complicated web applications and have authentications, other pages and etc.
I appreciate any help.
my current config is putting
location  /foo1/   {
        if ($request_uri ~* "/foo1/(.*)") {
        proxy_pass  http://192.168.1.100:8080/$1;
        }

in default server block of nginx, and obviously it doesn't work.

A: There's no "obviously" here, you demonstrate the problem and post full configuration, error log, and ideally a curl or similar to show what happens.
However I think something like this should work, though you may have to play with the expression a little - I don't write them often so it takes me a while to get them right. There are a few examples on this page.
location ~ ^/foo1/(.*)$ {
  proxy_pass       http://192.168.1.100:8080/$1;
}

It might work better with something more like this as the first line
location /foo1/(.*)$ {


text:
Q: Check if a string is null or empty in XSLT How can I check if a value is null or empty with XSL?
For example, if categoryName is empty? I'm using a when choosing construct.
For example:
<xsl:choose>
    <xsl:when test="categoryName !=null">
        <xsl:value-of select="categoryName " />
    </xsl:when>
    <xsl:otherwise>
        <xsl:value-of select="other" />
    </xsl:otherwise>
</xsl:choose>

A:
How can I check if a value is null or empty with XSL?
For example, if categoryName is empty?

This is probably the simplest XPath expression (the one in accepted answer provides a test for the opposite, and would be longer, if negated):
not(string(categoryName))

Explanation:
The argument to the not() function above is false() exactly when there is no categoryName child ("null") of the context item, or the (single such) categoryName child has string value -- the empty string.

I'm using a when choosing construct.
For example:
<xsl:choose>
    <xsl:when test="categoryName !=null">
        <xsl:value-of select="categoryName " />
    </xsl:when>
    <xsl:otherwise>
        <xsl:value-of select="other" />
    </xsl:otherwise>
</xsl:choose>

In XSLT 2.0 use:
<xsl:copy-of select="concat(categoryName,  $vOther[not(string(current()/categoryName))])"/>

Here is a complete example:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
     <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:variable name="vOther" select="'Other'"/>

 <xsl:template match="/">
  <xsl:copy-of select="concat(categoryName,$vOther[not(string(current()/categoryName))])"/>
 </xsl:template>
</xsl:stylesheet>

When this transformation is applied on the following XML document:
<categoryName>X</categoryName>

the wanted, correct result is produced:
X

When applied on this XML document:
<categoryName></categoryName>

or on this:
<categoryName/>

or on this
<somethingElse>Y</somethingElse>

the correct result is produced:
Other

Similarly, use this XSLT 1.0 transformation:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:variable name="vOther" select="'Other'"/>

  <xsl:template match="/">
    <xsl:copy-of select=
    "concat(categoryName,  substring($vOther, 1 div not(string(categoryName))))"/>
  </xsl:template>
</xsl:stylesheet>

Do note: No conditionals are used at all. Learn more about the importance of avoiding conditional constructs in this nice Pluralsight course:
"Tactical Design Patterns in .NET: Control Flow"

A: From Empty Element:
To test if the value of a certain node is empty
It depends on what you mean by empty.

*

*Contains no child nodes: not(node())

*Contains no text content: not(string(.))

*Contains no text other than whitespace: not(normalize-space(.))

*Contains nothing except comments: not(node()[not(self::comment())])

A: In some cases, you might want to know when the value is specifically null, which is particularly necessary when using XML which has been serialized from .NET objects.  While the accepted answer works for this, it also returns the same result when the string is blank or empty, i.e. '', so you can't differentiate.
<group>
    <item>
        <id>item 1</id>
        <CategoryName xsi:nil="true" />
    </item>
</group>

So you can simply test the attribute.
<xsl:if test="CategoryName/@xsi:nil='true'">
   Hello World.
</xsl:if>

Sometimes it's necessary to know the exact state and you can't simply check if CategoryName is instantiated, because unlike say Javascript
<xsl:if test="CategoryName">
   Hello World.
</xsl:if>

Will return true for a null element.

A: I know this question is old, but between all the answers, I miss one that is a common approach for this use-case in XSLT development.
I am imagining that the missing code from the OP looks something like this:
<xsl:template match="category">
    <xsl:choose>
        <xsl:when test="categoryName !=null">
            <xsl:value-of select="categoryName " />
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="other" />
        </xsl:otherwise>
    </xsl:choose>
</category>

And that the input looks something like this:
<categories>
    <category>
       <categoryName>Books</categoryName>
    </category>
    <category>
       <categoryName>Magazines</categoryName>
       <categoryName>Periodicals</categoryName>
       <categoryName>Journals</categoryName>
    </category>
    <category>
        <categoryName><!-- please fill in category --></categoryName>
    </category>
    <category>
        <categoryName />
    </category>
    <category />
</categories>

I.e., I assume there can be zero, empty, single or multiple categoryName elements. To deal with all these cases using xsl:choose-style constructs, or in other words, imperatively, is quickly getting messy (even more so if elements can be at different levels!). A typical programming idiom in XSLT is using templates (hence the T in XSLT), which is declarative programming, not imperative (you don't tell the processor what to do, you just tell what you want output if certain conditions are met). For this use-case, that can look something like the following:
<!-- positive test, any category with a valid categoryName -->
<xsl:template match="category[categoryName[text()]]">
    <xsl:apply-templates />
</xsl:template>

<!-- any other category (without categoryName, "null", with comments etc) -->
<xsl:template match="category">
    <xsl:text>Category: Other</xsl:text>
</xsl:template>

<!-- matching the categoryName itself for easy handling of multiple names -->
<xsl:template match="categoryName">
    <xsl:text>Category: </xsl:text>
    <xsl:value-of select="." />
</xsl:template>

This works (with any XSLT version), because the first one above has a higher precedence (it has a predicate). The "fall-through" matching template, the second one, catches anything that is not valid. The third one then takes care of outputting the categoryName value in a proper way.
Note that in this scenario there is no need to specifially match categories or category, because the processor will automatically process all children, unless we tell it otherwise (in this example, the second and third template do not further process the children, because there is no xsl:apply-templates in them).
This approach is more easily extendible then the imperative approach, because it automically deals with multiple categories and it can be expanded for other elements or exceptions by just adding another matching template. Programming without if-branches.
Note: there is no such thing as null in XML. There is xsi:nil, but that is rarely used, especially rarely in untyped scenarios without a schema of some sort.

A: If there is a possibility that the element does not exist in the XML I would test both that the element is present and that the string-length is greater than zero:
<xsl:choose>
    <xsl:when test="categoryName and string-length(categoryName) > 0">
        <xsl:value-of select="categoryName " />
    </xsl:when>
    <xsl:otherwise>
        <xsl:value-of select="other" />
    </xsl:otherwise>
</xsl:choose>

A: test="categoryName != ''"

Edit: This covers the most likely interpretation, in my opinion, of "[not] null or empty" as inferred from the question, including it's pseudo-code and my own early experience with XSLT. I.e., "What is the equivalent of the following Java?":
// Equivalent Java, NOT XSLT
!(categoryName == null || categoryName.equals(""))

For more details e.g., distinctly identifying null vs. empty, see johnvey's answer below and/or the XSLT 'fiddle' I've adapted from that answer, which includes the option in Michael Kay's comment as well as the sixth possible interpretation.

A: If a node has no value available in the input xml like below xpath,
<node>
    <ErrorCode/>
</node>

string() function converts into empty value. So this works fine:
string(/Node/ErrorCode) =''

A: Absent of any other information, I'll assume the following XML:
<group>
    <item>
        <id>item 1</id>
        <CategoryName>blue</CategoryName>
    </item>
    <item>
        <id>item 2</id>
        <CategoryName></CategoryName>
    </item>
    <item>
        <id>item 3</id>
    </item>
    ...
</group>

A sample use case would look like:
<xsl:for-each select="/group/item">
    <xsl:if test="CategoryName">
        <!-- will be instantiated for item #1 and item #2 -->
    </xsl:if>
    <xsl:if test="not(CategoryName)">
        <!-- will be instantiated for item #3 -->
    </xsl:if>
    <xsl:if test="CategoryName != ''">
        <!-- will be instantiated for item #1 -->
    </xsl:if>
    <xsl:if test="CategoryName = ''">
        <!-- will be instantiated for item #2 -->
    </xsl:if>
</xsl:for-each>

A: What about?
test="not(normalize-space(categoryName)='')"

A: Something like this works for me:
<xsl:choose>
  <xsl:when test="string(number(categoryName)) = 'NaN'"> - </xsl:when>
  <xsl:otherwise>
    <xsl:number value="categoryName" />
  </xsl:otherwise>
</xsl:choose>

Or the other way around:
<xsl:choose>
  <xsl:when test="string(number(categoryName)) != 'NaN'">
    <xsl:number value="categoryName" />
  </xsl:when>
  <xsl:otherwise> - </xsl:otherwise>
</xsl:choose>

Note: If you don't check null values or handle null values, IE7 returns -2147483648 instead of NaN.

A: First two deal with null value and second two deal with empty string.
<xsl:if test="USER/FIRSTNAME">
    USERNAME is not null
</xsl:if>
<xsl:if test="not(USER/FIRSTNAME)">
    USERNAME is null
 </xsl:if>
 <xsl:if test="USER/FIRSTNAME=''">
     USERNAME is empty string
 </xsl:if>
 <xsl:if test="USER/FIRSTNAME!=''">
     USERNAME is not empty string
 </xsl:if>

A: I actually found it better just testing for string length since many times the field is not null, just empty

<xsl:when test="string-length(field-you-want-to-test)<1">

A: By my experience the best way is:
<xsl:when test="not(string(categoryName))">
    <xsl:value-of select="other" />
</xsl:when>
<otherwise>
    <xsl:value-of select="categoryName" />
</otherwise>

A: Use simple categoryName/text() Such test works fine on <categoryName/> and also <categoryName></categoryName>.
<xsl:choose>
    <xsl:when test="categoryName/text()">
        <xsl:value-of select="categoryName" />
    </xsl:when>
    <xsl:otherwise>
        <xsl:value-of select="other" />
    </xsl:otherwise>
</xsl:choose>


text:
Q: Playing sound through STREAM_ALARM doesn't start from beginning in Marshmallow I'm playing a sound through STREAM_ALARM:
MediaPlayer mp = new MediaPlayer();
mp.setDataSource(context, notificationSoundUri);
mp.setAudioStreamType(AudioManager.STREAM_ALARM);
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
    @Override
    public void onPrepared(MediaPlayer mp) {
        mp.start();
    }
});
mp.prepare();

It worked ok until I tried on Android 6. On Android 6 sound doesn't play from beginning, so if I play short sounds, no sound is heard. I tried using seekTo(0) and initializing MediaPlayer in other ways.
It only happens in Android 6 when using STREAM_ALARM (other streams work well).
Any help?
EDIT: I realized that sound actually starts playing from start, but at very low volume, and after about 2 seconds volume increases... do you know how to deactivate this behavior?

A: It sounds like an equalization problem (maybe this audio stream comes with an audioSessionId which is already handled by the system equalizer?)
I will try the following trick before the MediaPlayer initialization:
1) Change the STREAM_ALARM volume
AudioManager mAudioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
int maxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM);
mAudioManager.setStreamVolume(AudioManager.STREAM_ALARM, maxVolume, 0 /*flags*/);

2) Set volume after prepare()
//...
mp.prepare();
mp.setVolume(1.0f, 1.0f);

3) Change the audioSessionId
//...
mp.setAudioStreamType(AudioManager.STREAM_ALARM);
mp.setAudioSessionId(CUSTOM_ID); //manually assign an ID here
//...

UPDATE
4) Try to use the SoundPool API instead of MediaPlayer and see if the problem persists (I also suspect that this is a device-dependent issue).
5) Try to call start() ==> pause() ==> start() on MediaPlayer
@Override
public void onPrepared(MediaPlayer mp) {
    mp.start();
    mp.pause();
    mp.start();
}

6) Try to trick the initial "low volume" period using the following logic:

*

*before play, set volume to 0

*play

*after 2 seconds of playback, seek to position 0 (this may consume the silent period)

*set the volume to max

*play again

In this way, you may be able to do a normal playback, with an initial delay of few seconds.

Let us know your progress, I'll update this answer accordingly with more information and suggestions.