text:
Q: React Link isn't serving up new page although the url is now updated I'm trying to get  to work on my site but for some reason, it would only update the URL but not the page. I've looked at other similar questions on this issue, but none of them really helped me get past my issue.
I'm just trying to have my logo and the nav bar load different pages. But I'm unable to make it work because maybe of how I'm doing it.
It's my first React project, and I'm just trying to learn how to do it. Sorry if it may be a really simple solution for everyone else.
Here are the two classes that I have:
App.js

import React from "react";
import "./App.css";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import Header from "./Header";

function App() {
  return (

      <Router>
        <Switch>
          <Route path="/checkout" exact>

Checkout Page!

          </Route>
          <Route path="/login" exact>

Login Page!

          </Route>
          {/* This is the default route, */}

          <Route path="/" exact>

Home Page!

          </Route>
        </Switch>
        </Router>

  );
}

export default App;

Header.js

import React from "react";
import "./Header.css";
import { Link } from "react-router-dom";
import SearchIcon from "@mui/icons-material/Search";

function Header() {
  return (

      <Link to="/checkout" exact>
        {/* logo on the left -> img*/}

      </Link>
      {/* Search box*/}

        <input type="text" className="header__searchInput" />
        <SearchIcon className="header__searchIcon" />

      {/* 3 links */}

        {/* 1st link */}
        <Link to="/login" className="header__link">

            Hello me
            Sign In

        </Link>

        {/* 2nd link */}

        {/* 3rd link */}

        {/* 4th link */}

      {/* Basket icon with number*/}

  );
}

export default Header;

My dependencies:

 "dependencies": {
    "@emotion/react": "^11.9.0",
    "@emotion/styled": "^11.8.1",
    "@mui/icons-material": "^5.6.2",
    "@mui/material": "^5.6.3",
    "@testing-library/jest-dom": "^5.16.4",
    "@testing-library/react": "^13.1.1",
    "@testing-library/user-event": "^13.5.0",
    "firebase": "^9.7.0",
    "history": "^4.10.1",
    "react": "^18.1.0",
    "react-dom": "^18.1.0",
    "react-router-dom": "^5.2.0",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"
  }


text:
Q: ngResource does not connect to proxy I have a yeoman angular app, I have configured grunt-connect-proxy in Gruntfile.js like this:
module.exports = function (grunt) {
  grunt.loadNpmTasks('grunt-connect-proxy');

[...]

connect: {
  options: {
    port: 9000,
    // Change this to '0.0.0.0' to access the server from outside.
    hostname: 'localhost',
    livereload: 35729
  },
  dev: {
    proxies: [
    {
      context: '/api/v1',
      host: '127.0.0.1',
      port: 3000,
      https: false,
    }
    ]
  },
  pro: {
    appendProxies: false,
    proxies: [{
      context: '/api',
      host: 'example.org'
    }]
  },
  livereload: {
    options: {
      open: true,
      middleware: function (connect) {
        return [
          require('grunt-connect-proxy/lib/utils').proxyRequest,
          connect.static('.tmp'),
          connect().use(
            '/bower_components',
            connect.static('./bower_components')
          ),
          connect().use(
            '/app/styles',
            connect.static('./app/styles')
          ),
          connect.static(appConfig.app)
        ];
      }
    }
  },
  test: {
    options: {
      port: 9001,
      middleware: function (connect) {
        return [
          connect.static('.tmp'),
          connect.static('test'),
          connect().use(
            '/bower_components',
            connect.static('./bower_components')
          ),
          connect.static(appConfig.app)
        ];
      }
    }
  },
  dist: {
    options: {
      open: true,
      base: '<%= yeoman.dist %>'
    }
  }
},

[...]

grunt.registerTask('serve', 'Compile then start a connect web server', function (target) {
if (target === 'dist') {
  return grunt.task.run(['build', 'connect:dist:keepalive']);
}

  grunt.task.run([
    'clean:server',
    'wiredep',
    'concurrent:server',
    'postcss:server',
    'configureProxies:dev',
    'connect:livereload',
    'watch'
  ]);
});

grunt.registerTask('build', [
  'clean:dist',
  'configureProxies:pro',
  'wiredep',
  'useminPrepare',
  'concurrent:dist',
  'postcss',
  'ngtemplates',
  'concat',
  'ngAnnotate',
  'copy:dist',
  'cdnify',
  'cssmin',
  'uglify',
  'filerev',
  'usemin',
  'htmlmin'
]);

I got this in angular console:
Running "configureProxies:dev" (configureProxies) task
Proxy created for: /api/v1 to 127.0.0.1:3000

my ngResource:
'use strict';

/**
 * @ngdoc service
 * @name doMasApp.Client
 * @description
 * # Client
 * Service in the doMasApp.
 */
angular.module('doMasApp')
.factory('Client', [
    '$resource',
    function ($resource) {
      var client = $resource(
          '/clients/:id',
          { id: '@id' },
          {
            query: { isArray: false },
            update: { method: 'PUT' }
          });
      return client;
    }])
;

but when I try to connect to server and get resource, I got this:
GET http://localhost:9000/clients 404 (Not Found)

please help!!!

A: the factory url must be like this:
angular.module('doMasApp')
.factory('Client', [
    '$resource',
    function ($resource) {
      var client = $resource(
          '/aoi/v1/clients/:id',
          { id: '@id' },
          {
            query: { isArray: false },
            update: { method: 'PUT' }
          });
      return client;
    }])
;

the proxy context must be added to the factory url.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Change Container Assigned IP address I want to create a container with its own static IP address.
I am using this command:
$sudo docker run -d -p 172.17.0.55::3306 mysql

And the result is:
e7e8d812163bfcc333f24bdad23b67382fdb5b9ca57e75cb65d8ed0feb4e2dc3

Error response from daemon: Cannot start container
e7e8d812163bfcc333f24bdad23b67382fdb5b9ca57e75cb65d8ed0feb4e2dc3:
Error starting

userland proxy: listen tcp 172.17.0.55:32827: bind: cannot assign requested address

where it went wrong??

A: To give static ip to you containers you can use either weave or rancher. If you love to work from command line i suggest using weave.
Weave creates its own network and assigns static ips to containers. Also weave is lightweight with just 10 mb container. So you can assign ips like 10.42.0.1 etc.


text:
Q: Best numerical integration method for this integral I have an integral as follows $$\int_0^\infty r^k \psi(r) dr \tag{1}$$ where $$\psi=e^{-ar-br^2-cr^3-dr^4}\tag{2}$$
I want to evaluate (1) numerically using a code (in Mathematica). Normal integration command returns error, so I'm going to write an algorithm myself, but I don't know what is the best method to do so. Any idea?


text:
Q: Integer number as condition - Android studio Good morning. I would like to ask how Can i check if the number is integer or it isn't? I work in AndroidStudio and wanted to check this condition. I've written smth like this but with no success.Application crashes.
int value = 0;

    if (!et.equals(temp)) {
        value = Integer.parseInt(temp);
    }
    if (value != 0 && value < 10 && value > 1 && (value -(int)value!=0)) {

A: You can check it like this:
button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String inputNumber = editText.getText().toString();
                if (inputNumber.contains(".")) {
                    editText.setError("Your Error Message Here");
                } else {
                    int num = Integer.parseInt(inputNumber);
                    // you got your interger ...
                }
            }
        });

And use android:inputType="numberDecimal" in your EditText .


text:
Q: Making faceted line charts with errorbands (aka Trellis charts with confidence intervals) in Vega-Lite.jl I have a dataset of the following format, with a price index and a confidence interval (lower and upper) for each date:
 Row │ borough   house_class  index    ci₀      ci₁      dates
     │ String15  String7      Float64  Float64  Float64  Date
─────┼──────────────────────────────────────────────────────────────
   1 │ Queens    SFH          1.0      1.0      1.0      2003-03-31
   2 │ Queens    SFH          1.10301  1.13093  1.07645  2003-06-30
   3 │ Queens    SFH          1.17184  1.2096   1.13636  2003-09-30
   4 │ Queens    SFH          1.23384  1.28435  1.18716  2003-12-31
   5 │ Queens    SFH          1.28346  1.34361  1.22847  2004-03-31

I can successfully create a line plot with the below Vega Lite code for the entire city:
idx |>
@vlplot(x=:dates) +
@vlplot(:line,
   y={
        :index,
        title="NYC Price Index",
        scale= {zero = false }
    },
) +
@vlplot(mark=:errorband,
    y=:ci₀,
    y2=:ci₁,
    x="dates")

Now I would like to expand this to chart to be multi-faceted, by borough and by house_class.
The line part works great by just adding a row and column but I can't get it to work with my confidence interval error bands.
idxb |>
@vlplot(x=:dates,
    :line,
   y={
        :index,
        title="NYC Price Index",
        scale= {zero = false }
    },
    row=:borough,
    column=:house_class
)

When I try this:
idxb |>
@vlplot(x=:dates) +
@vlplot(:line,
   y={
        :index,
        title="NYC Price Index",
        scale= {zero = false }
    },
) +
@vlplot(mark=:errorband,
    row=:borough,
    column=:house_class,
    y=:ci₀,
    y2=:ci₁,
    x="dates")

I get the following error:
SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at /Users/ilya/.julia/artifacts/5cc2ca447001163b90bb24e24a389e4f7b0f1e88/vg2svg.js:42:32
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
TypeError: Cannot read property 'length' of undefined

A: you should use facet and inside its spec use layer, for example something like:
data |> @vlplot(facet = {row = {field = "x1"}},
                 spec = {
                 layer = [
                    {mark = :point, x = :x2, y = :x3},
                     {mark = :line, x = :x2, y = :x3}
                 ]
                 }
                 )


text:
Q: Regarding the dual cone in a normed space $X$ is a normed space and $C\subset X$ a convex and closed cone ($\lambda C\subset C\ \forall \lambda\geq0$), and $C':=\{x'\in X':x'(x)\geq0\ \forall x\in C\}$ the dual cone of $C$.
I want to show:

$(i):\quad C\neq X\Rightarrow C'\neq\{0\}$
$(ii):\quad x'(x)\geq0\ \forall x'\in C'\Rightarrow x\in C$

Because in class we talked about separation theorems, my approach so far was:
Let $C\neq X$ then $\exists x_0\notin C$. Then $\{x_0\}$ is closed and convex, the Hahn-Banach-Separation-Theorem provides $x_0'$ such that $x_0'(x_0)<\inf_{x\in C}x_0'(x)\leq0$.
This is were I'm stuck...

A: Your approach is good, you just need to use the cone property of $C$: By the separation theorem there exist $a\in \mathbb{R}$ and $x_0^*\in X^*$ such that
$$x_0^*(x_0)<a<x_0^*(x), \ \forall x\in C.$$
If there existed an $y_0\in C$ such that $x_0^*(y_0)<0$, then $ny_0\in C$ for every $n\in \mathbb{N}$, so $\lim_{n\rightarrow \infty} x_0^*(ny_0) =-\infty$ which would contradict  the fact that $x_0^*(x_0)<a<x_0^*(x), \ \forall x\in C.$
So $x_0^*(x)\geq 0$, for every $x\in C$. Since $x_0^*(0)=0$ and $0\in C$, we have that $a<0$. This solves both (i) and (ii) simultaneously.


text:
Q: Piecewise polynomial fitting a sinusoid Question, I have a sinusoid which I have to resemble as perfect as possible using piecewise polynomials in the domain 0..2pi.
Unfortunately there are some constraints:

*

*Polynomials can have a maximum order of 4.

*Up to 16 polynomials can be used.

*The fit is to be continuous.

*The first and second derivative also need to be continuous.

*The error for the fit should be minimized, likewise, for the first and second order derivative.

*The error in the frequency content should also be minimized. (This is actually the most important criteria)

What I would like to see: ideas on how to achieve this, applied or advanced literature or an actual implementation, for instance in Matlab.

A: I found a script which was able to fit on almost all criteria I had,
http://nl.mathworks.com/matlabcentral/fileexchange/13812-splinefit


text:
Q: My cdh5.2 cluster get FileNotFoundException when running hbase MR jobs My cdh5.2 cluster has a problem to run hbase MR jobs.
For example, I added the hbase classpath into the hadoop classpath:
vi /etc/hadoop/conf/hadoop-env.sh

add the line:
export HADOOP_CLASSPATH="/usr/lib/hbase/bin/hbase classpath:$HADOOP_CLASSPATH"

And when I am running:
hadoop jar /usr/lib/hbase/hbase-server-0.98.6-cdh5.2.1.jar rowcounter "mytable"
I get the following exception:
14/12/09 03:44:02 WARN security.UserGroupInformation: PriviledgedActionException as:root (auth:SIMPLE) cause:java.io.FileNotFoundException: File does not exist: hdfs://clusterName/usr/lib/hbase/lib/hbase-client-0.98.6-cdh5.2.1.jar
Exception in thread "main" java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at org.apache.hadoop.hbase.mapreduce.Driver.main(Driver.java:54)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at org.apache.hadoop.util.RunJar.main(RunJar.java:212)
Caused by: java.io.FileNotFoundException: File does not exist: hdfs://clusterName/usr/lib/hbase/lib/hbase-client-0.98.6-cdh5.2.1.jar
        at org.apache.hadoop.hdfs.DistributedFileSystem$17.doCall(DistributedFileSystem.java:1083)
        at org.apache.hadoop.hdfs.DistributedFileSystem$17.doCall(DistributedFileSystem.java:1075)
        at org.apache.hadoop.fs.FileSystemLinkResolver.resolve(FileSystemLinkResolver.java:81)
        at org.apache.hadoop.hdfs.DistributedFileSystem.getFileStatus(DistributedFileSystem.java:1075)
        at org.apache.hadoop.mapreduce.filecache.ClientDistributedCacheManager.getFileStatus(ClientDistributedCacheManager.java:288)
        at org.apache.hadoop.mapreduce.filecache.ClientDistributedCacheManager.getFileStatus(ClientDistributedCacheManager.java:224)
        at org.apache.hadoop.mapreduce.filecache.ClientDistributedCacheManager.determineTimestamps(ClientDistributedCacheManager.java:93)
        at org.apache.hadoop.mapreduce.filecache.ClientDistributedCacheManager.determineTimestampsAndCacheVisibilities(ClientDistributedCacheManager.java:57)
        at org.apache.hadoop.mapreduce.JobSubmitter.copyAndConfigureFiles(JobSubmitter.java:265)
        at org.apache.hadoop.mapreduce.JobSubmitter.copyAndConfigureFiles(JobSubmitter.java:301)
        at org.apache.hadoop.mapreduce.JobSubmitter.submitJobInternal(JobSubmitter.java:394)
        at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1295)
        at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1292)
        at java.security.AccessController.doPrivileged(Native Method)
        at javax.security.auth.Subject.doAs(Subject.java:415)
        at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1614)
        at org.apache.hadoop.mapreduce.Job.submit(Job.java:1292)
        at org.apache.hadoop.mapreduce.Job.waitForCompletion(Job.java:1313)
        at org.apache.hadoop.hbase.mapreduce.RowCounter.main(RowCounter.java:191)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at org.apache.hadoop.util.ProgramDriver$ProgramDescription.invoke(ProgramDriver.java:72)
        at org.apache.hadoop.util.ProgramDriver.run(ProgramDriver.java:145)
        at org.apache.hadoop.util.ProgramDriver.driver(ProgramDriver.java:153)

A: Even I have the same problem with CDH 5.2.0. as a work around,
I manually copied the jar file in to hdfs, then exceptions are not coming

A: So, The problem was environment issue:
When I added the below jars into /usr/lib/hadoop/lib. all worked fine
hbase-client-0.98.6-cdh5.2.1.jar
hbase-common-0.98.6-cdh5.2.1.jar
hbase-protocol-0.98.6-cdh5.2.1.jar
hbase-server-0.98.6-cdh5.2.1.jar
hbase-prefix-tree-0.98.6-cdh5.2.1.jar
hadoop-core-2.5.0-mr1-cdh5.2.1.jar
htrace-core-2.04.jar

My machine has the following rpms in it:
>> rpm -qa | grep cdh
zookeeper-3.4.5+cdh5.2.1+84-1.cdh5.2.1.p0.13.el6.x86_64
hadoop-2.5.0+cdh5.2.1+578-1.cdh5.2.1.p0.14.el6.x86_64
hadoop-0.20-mapreduce-2.5.0+cdh5.2.1+578-1.cdh5.2.1.p0.14.el6.x86_64
hbase-regionserver-0.98.6+cdh5.2.1+64-1.cdh5.2.1.p0.9.el6.x86_64
cloudera-cdh-5-0.x86_64
bigtop-utils-0.7.0+cdh5.2.1+0-1.cdh5.2.1.p0.13.el6.noarch
bigtop-jsvc-0.6.0+cdh5.2.1+578-1.cdh5.2.1.p0.13.el6.x86_64
parquet-1.5.0+cdh5.2.1+38-1.cdh5.2.1.p0.12.el6.noarch
hadoop-hdfs-2.5.0+cdh5.2.1+578-1.cdh5.2.1.p0.14.el6.x86_64
hadoop-mapreduce-2.5.0+cdh5.2.1+578-1.cdh5.2.1.p0.14.el6.x86_64
hadoop-0.20-mapreduce-tasktracker-2.5.0+cdh5.2.1+578-1.cdh5.2.1.p0.14.el6.x86_64
hbase-0.98.6+cdh5.2.1+64-1.cdh5.2.1.p0.9.el6.x86_64
avro-libs-1.7.6+cdh5.2.1+69-1.cdh5.2.1.p0.13.el6.noarch
parquet-format-2.1.0+cdh5.2.1+6-1.cdh5.2.1.p0.14.el6.noarch
hadoop-yarn-2.5.0+cdh5.2.1+578-1.cdh5.2.1.p0.14.el6.x86_64
hadoop-hdfs-datanode-2.5.0+cdh5.2.1+578-1.cdh5.2.1.p0.14.el6.x86_64

I still wonder which rpm is missing.

A: Instead of adding the file manually to HDFS, you can add the hbase library path to the .bashrc file. Add the lib folder in hbase to the CLASSPATH.
Also, add the classpath of hbase to HADOOP_CLASSPATH.
Your .bashrc file should contain the following:
export HADOOP_CLASSPATH=$HADOOP_CLASSPATH:`${HBASE_HOME}/bin/hbase classpath`
export HADOOP_CLASSPATH=$HADOOP_CLASSPATH:`${HBASE_HOME}/bin/hbase mapredcp`

export CLASSPATH=${HBASE_HOME}/lib/*

Note: The CLASSPATH should point to the lib folder of your hbase installation folder. Use the following to compile and run your java code.
javac Example.java
java -classpath $CLASSPATH:. Example


text:
Q: Confused about HTTP in Wireshark I'm currently using Wireshark and I'm trying to fill out a table
that what's the Packet Number for the HTTP request and HTTP Response. I've used the filter in Wireshark however, I'm not sure what packet is the right one.
How do I know which is the right HTTP Request and HTTP Response? Image of packets

A: You have filtered for http.request. Therefore you only see HTTP requests (and some protocols that build on HTTP requests). All lines with GET are http requests.
If you want to see both requests and responses, you need a different filter, for example just http.


text:
Q: How to check for multiple values in MySQL using IN and a parameter? I'm generating a string of values (colors) like so:
  'red|green|blue|yellow|orange|black'

Can I pass this as a parameter (param_cols) to a MySQL stored procedure and check against it like so:
  SELECT tbl.products
  FROM table AS tbl
  WHERE tbl.color IN ( param_cols );

Question:
Is this possible using a parameter? Should I use IN, LIKE or REGEX?
EDIT:
THANKS for the hints. However I'm more concerned about whether I can pass my list of colors as a variable into the stored procedure vs having to insert each color individually?

A: There seems to be a FIND_IN_SET function:
 SELECT tbl.products
 FROM table AS tbl
 WHERE FIND_IN_SET(tbl.color , 'red,green,blue,yellow,orange,black');

I am not sure if this can be used with an index, though.

A: If your colors have an int index, you're better off using that.
But you're on the right track, you can use IN
SELECT tbl.products FROM table as tbl WHERE tbl.color
IN ('red','green','blue','yellow','orange','black')

This will only look for exact matches though.


text:
Q: Is there a way to write rules for incoming calls? I'd like to write some rules for incoming calls on my iPhone.  For instance, if a call from a certain number comes in, I'd like it to go to voice-mail.  Or simply hang up and not answer at all.
Is there a way to do this natively on the iPhone or perhaps an app that does that?

A: Without jail breaking iOS - you can't get a phone call on any app but the Apple phone app (which doesn't support call screening as you asked).
Some carriers will let you set this up - but it's nothing to do with the iPhone.
Lastly, there are tons of services that require another phone number. Google Voice is one where you can program quiet hours, white list or black list and have exactly such control.
The downside to these other apps is that you'll need to have people call your alternate number, so it's not as easy - even with the ability to port an existing number to GV and then get a new number from your carrier.
Several iOS apps work with Google Voice like the official app and GV Mobile + and there are probably a hundred other VOIP solutions on the app store, but Google and Skype are the big players today.

A: If you DO want to jailbreak, iBlacklist works great for this.
You can have blacklists, whitelists, lists just for SMS, lists that occur during a certain schedule (say work hours), multiple lists active simultaneously, and different actions for different lists, etc.
So you could use it to ignore some calls, some some calls straight to voicemail, and ignore other calls while automatically sending that number an SMS that says "At work, will call you back tonight" etc

A: While there are some jailbreak options, which I think have all been discussed in other answers here. Have you tried just calling up your network and seeing if they will block calls from the specific number from ever getting through? You can certainly do this on landlines so I can't see why a mobile would be any different.
There is no feature built into the iPhone, nor any 3rd party iPhone app that will do what you're after. Unless you join the darkside ;)

A: Settings/Do Not Disturb - select manual on(green), allow calls from (all contacts), silence (always).  This will allow all contacts on your contact list to ring through.  Everyone else gets the silent treatment.

A: just turn your phone on airplane mode!! and if you have wi-fi then you can turn on the wifi and still use the internet but you will not recieve phone calls or texts from anyone it will go straight to voicemail.. if you only want it for certain people tho then you need to call your carier and have them blocked. hope this helps


text:
Q: Как сделать так чтобы при запуске Томката он сразу открывал баузер с нужным URL? Например
http ://localhost:8080/MyWebProject/

A: Создайте батник (или шелл-скрипт), который будет вызывать батник (или шелл-скрип), запускающий томкат, а затем вызывать команду открытия страницы в браузере, вроде такой.
Только имейте в виду, что время подготовки томкатом приложения может зависеть от многих факторов. Старт самого томката еще не означает, что приложение готово к использованию. Возможно, решением будет некоторая заданная пауза между запуском томката и открытием браузера.


text:
Q: Rx.Net - disposing of resources created during Observable.Create() I am trying to use Rx(.net) for a project and I have an issue with how to properly dispose resources that are created during Observable.Create() and emitted with OnNext(). My setup looks like this (shortened to the relevant bits only, hopefully):
var obs = Observable.Create<ReactiveRunData>(async (o) =>
  {
    if (someCondition)
    {
      RunData runData = await CreateRunData(); // RunData is IDisposable, needs to be disposed
      o.OnNext(runData);
    }

    o.OnCompleted();

    return Disposable.Empty;
  })
  .Concat(Observable.Empty<RunData>().Delay(TimeSpan.FromSeconds(2)))
  .Repeat() // Resubscribe indefinitely after source completes
  .Publish().RefCount() // see http://northhorizon.net/2011/sharing-in-rx/
  ;

This is my implementation of an observable collection that's infinite and produces an item (of type RunData) every 2 seconds.
Then I do the actual reactive stuff by transforming the IObservable stream using all kinds of operators:
var final = obs
    .Select(runData => ...)
    // lots of other operations
    .Select(tuple => (tuple.runData, tuple.result));`

The final observable returns a tuple (RunData, Result).
When subscribing to that observable, at the end I explicitly dispose of the RunData instances, like so:
final.Subscribe(
    async (tuple) =>
    {
        var (runData, result) = tuple;
        try
        {
            // ... do something with result and runData, await some stuff, ...

        } catch (Exception e)
        {
            // error handling
        } finally
        {
            // dispose of runData
            runData.Dispose();
        }
    },
    (Exception e) =>
    {
        // error handling
    });

I suspect this implementation is leaky in various ways, such as when exceptions are thrown from different places, in some cases of which I believe the RunData instance won't get disposed, but is just gone, replaced by an exception travelling through the pipe.
I believe I'd also run into problems if I would add a second subscriber to my observable, right? I don't need more than one subscriber, but that also makes me question my implementation.
I feel like the whole idea of passing data that needs to be disposed by subscribers is wrong, but I couldn't come up with a better way. I tried using Observable.Using(), but afaik that only disposes the resource when the sequence ends, which in my case is never. And I really need an infinite sequence because I want to be able to use functionality like Scan() to reference previous data to build intermediate data structures over time.
I also tried using the callback that is returned from the lambda of Observable.Create() but that fires as soon as Observable.Create() is done and not after the subscriber is done, so that led to race conditions (but I'm not even sure if I understood that correctly, RX + async is tricky).
So... how can I implement this properly?
For some background info, RunData includes (among other things) a DB transaction and an Autofac LifetimeScope, both of which I want to use throughout the pipeline, and both of which need to be disposed at the end, after the subscriber is done.

A: This would be easily solved if all return type of operators during your pipe are all IDisposable (and dispose RunData under the hood), which should be logic in what you try to achieve.
Observable
    .FromAsync<MemoryStream>(async => Task.FromResult(new MemoryStream()))
    .Select(d => Observable.Return(d)
                           // Run  dangerous operators here
                           .Select(s => new FileStream("r", FileMode.Open))
                           // Catch and return IDisposable if error
                           .Catch((Exception ex) => Observable.Return((IDisposable) d)))
    .Switch()
    .Do(d => d.Dispose()) // Dispose will be always called
    .Repeat()
    .Subscribe();

Note :

*

*I just replace your IDisposable object with MemoryStream() for the example and use FromAsync operator instead of create

*The higher order observable is here to avoid breaking the subscription during the catch

A: Your code has several issues that prevent it being safe to use in a production environment. I'll try to go thru them all, but I'll hit the most major design issue first.
When using IDisposable objects in C#, you have two ways to manage lifetime.

*

*Either the creator of the IDisposable must call Dispose(),

*Or, you're writing a factory method, so the consumer must call Dispose().

That's not specifically about observables, that's whenever, anyway, and at all times, when you create disposables in C#.
Now, when an observable returns disposables then you are effectively writing a factory method, so the creator cannot call Dispose().
But, you have no control of how many subscribers there are for your observable, so none of the consumers (observers/subscriptions) can know when they are done with the disposable.
The bottom-line is that you CANNOT safely manage disposables if they are the output of an observable. DO NOT DO IT.
Rx does offer a safe way of dealing with disposables that allows the pipeline to effectively manage the disposables lifetime - and that's with the Using operator. That's what you should use.
Before I give an example, I'll just cover off on the 3 other issue I see in your code.

*

*You use external state with your if (someCondition). External state is bad in observables and you should learn to avoid it always. It's hard to tell what you're using this for in your code, so I'll ignore this issue for now.

*You're using a async in the Create call - while that's OK for create as there is a Func<IObserver<T>, Task<IDisposable>> overload, I'm always suspicious of this kind of code as the framework converts Func<Task> into Action as fire-and-forget calls - and these are hard to debug. Try to avoid!

*You're returning Disposable.Empty inside the Create. Whenever you do this it is likely that you're doing something wrong. Often this creates code that you cannot cancel and/or that creates deadlocks. There are very few times that you need to resort to Create in this way. Try to avoid!

From your code in the question it appears that RunData produces a result. I'll assume that there is a GetResult() method on RunData that produces a value of type Result.
To start, since CreateRunData is async you should add this handy helper method:
public static class ObservableEx
{
    public static IObservable<T> Using<T, R>(Func<Task<R>> resourceFactory, Func<R, IObservable<T>> observableFactory) where R : IDisposable =>
        from r in Observable.FromAsync(resourceFactory)
        from t in Observable.Using(() => r, observableFactory)
        select t;
}

Here are the two ways that I would write your code.
(1)
IObservable<Result> obs =
    ObservableEx
        .Using(
            () => CreateRunData(),
            rd =>
                Observable
                    .Interval(TimeSpan.FromSeconds(2.0))
                    .Where(t => someCondition) // don't do this
                    .Select(t => rd.GetResult()))
        .Publish()
        .RefCount();

This approach creates one instance of your resource and continues to use it until all of your subscribers have disposed of their subscriptions.
(2)
IObservable<Result> obs =
    Observable
        .Interval(TimeSpan.FromSeconds(2.0))
        .Where(t => someCondition) // don't do this
        .SelectMany(t =>
            ObservableEx
                .Using(
                    () => CreateRunData(),
                    rd => Observable.Return(rd.GetResult())))
        .Publish()
        .RefCount();

This version creates a new resource for each tick pf the Interval.
Should GetResult actually be async then do these replacements:
(1)
Replace .Select(t => rd.GetResult())) with .SelectMany(t => Observable.FromAsync(() => rd.GetResultAsync()))).
(2)
Replace rd => Observable.Return(rd.GetResult()))) with rd => Observable.FromAsync(() => rd.GetResultAsync()))).
Let me know if this helps.


text:
Q: What favors island growth of a sputtered material? What would be the best choice of parameters in general if one would like to get pure island growth (i.e. Volmer-Weber growth) in a sputtering deposition process and what would be a good estimate of the maximum height of these islands (e.g. 10 nm) before they will form a continuous film?
By parameters I mean the temperature of the substrate, the argon ion pressure and the applied voltage. If you can think of anything else that could be changed, please add.
Also, how do these parameters depend on the material? I can't find good references for different materials online, just a few special cases such as silver or gold islands on a sapphire substrate. Can one make a general statement about different lattices and defects in a substrate, e.g. a cleaved surface that basically provides no nucleation sites except step edges, which unfortunately won't lead to islands but to "lines" along these edges.
A sketch of the sputtering process :

A: The wetting behavior is basically defined through the surface and interface energies. A material A will wet material B if:
$$ E_{surf}(A) + E_{int}(AB) < E_{surf}(B) $$
The surface of material B is minimized by wetting material A (and therefore leading to layer-by-layer growth. The reverse case leads to island formation, namely if:
$$ E_{surf}(B) + E_{int}(AB) < E_{surf}(A) $$
So, this all in all does not really depend on the growth conditions or process. This is e.g. discussed in "Epitaxy of Dissimilar Materials" by C. Palmstrom
From a more practical perspective: You can try to modify the interface energy by various things: E.g. think about off-cut wafers, where you have a lot of surface steps present or even wafers with a different orientation, if this is an option. Further things to be changed or considered are surface defects, adhesion agents, e.g. sputtering of a thin film, to create a surface, which will favor island growth (may or may not be an option), and so on.


text:
Q: Highchart datepicker I am trying to get jquery-ui datepicker to work with highcharts so that a user can select a date an example being
A user selects 10th October  to 25th October
Once the user has selected the dates the highchart should redraw and show the hours for the projects that have done along with the tasks. My chart looks like the following:
Chart
From the photo currently the highchart shows the hours a user has done for a task against the project "Asda".
At the moment I have the chart simply displays the hours for the current week. What I am trying to do is use the jquery datepicker so that it can display past hours that the user has entered. If the user selects "from 10th October" "to "25th October" the chart should redraw and show the hours and projects for the selected date range.
My code follows:
Index.html.erb
<%= javascript_include_tag 'highcharts', 'exporting' %>

<%= render 'projectselect' %>

From
<input type="text" id="from" name="from" size="15"/>
to
<input type="text" id="to" name="to" size="15"/>

<button id="button">Redraw</button>

What would be the best way to approach this?

A: In onSelect callback of datepickers, you should validate, if both #from and #to are selected (or provide sensible defaults if not) and at the end fire and xhr request to server to get new series of data.
onSelect: function( selectedDate ) {
  var option = this.id == "from" ? "minDate" : "maxDate",
  instance = $( this ).data( "datepicker" ),
    date = $.datepicker.parseDate(
      instance.settings.dateFormat || $.datepicker._defaults.dateFormat,
      selectedDate,
      instance.settings
    );
    dates.not( this ).datepicker( "option", option, date );

    // validate if we have both dates and get new series from server
    if ($(dates[0]).datepicker("getDate") &&
        $(dates[1]).datepicker("getDate")) {
      $.ajax({
        type: 'POST',
        url: '<%= user_projects_path(params[:user_id]) %>',
        data: {"from": $(dates[0]).datepicker("getDate"), "to" : $(dates[1]).datepicker("getDate") },
        success: function(data) {
          // now we have new series of data to display in graph
          // we remove the old one, add the new and redraw the chart
          for(var i=0; i<chart.series.length; i++) {
            chart.get(chart.series[i].options.id).remove();
          }

          // fiddle with json data from xhr response to form valid series
          var series = data;
          chart.addSeries(series, true); // second param says we want to redraw chart
        }
      });
    }
}

Controller method under user_projects_path url needs to exists and return JSON formatted series data for given user_id of course. You can filter your series data before returning with params sent by jquery xhr request (from and to).
Quick and dirty solution but I hope you got the point...


text:
Q: React / Next - importing component from external library cause : Element type is invalid: expected a string or a class/function but got: undefined I'm trying to create a React components library then integrated into a NextJs project.
In the library I have a generic "CmsBlock" component that take a type and the data and generate a component (Paragraph or ZigZag). Here is the code :
src/Block.tsx
import React from "react";
import Paragraph from "./components/Paragraph/Paragraph";
import ZigZag from "./components/ZigZag/ZigZag";

const CMS_BLOCKS: {
  [key: string]: any;
} = {
  ZigZag: ZigZag,
  Paragraph: Paragraph,
};

const CmsBlock = ({ type, data }: { type: string; data: unknown }) => {
  const CurrentBlock = CMS_BLOCKS[type];

  if (!CurrentBlock) {
    throw new Error("Unknown block type");
  }

  return <CurrentBlock data={data} />;
};

export default CmsBlock;

src/components/Paragraph/Paragraph.tsx
import React, { FC } from "react";
import { CmsProps } from "../props";

export interface ParagraphData {
  text: string;
}
const Paragraph: FC<CmsProps<ParagraphData>> = ({ data }) => {
  return (

{data.text}

  );
};

Paragraph.defaultProps = {
  data: {
    text: `Lorem ipsum dolor sit amet. Et ullam quis et repellat nulla sit consequatur praesentium est voluptatem dolorem ut voluptate eveniet At consequatur veniam aut vero pariatur? Et consequatur repudiandae ut illum voluptas est unde dolore et enim blanditiis et asperiores perspiciatis et rerum eveniet ad molestiae pariatur. Aut nostrum itaque a assumenda consequatur ad numquam expedita ex rerum officia? Eum delectus incidunt quo incidunt nemo est itaque similique est tempora iure.`,
  },
};

export default Paragraph;

And then my index.ts (input for rollup)
export { default as CmsBlock } from "./Block";

In my NextJS project, I use the CmsBlock like that :
import { CmsBlock } from "cms-components";

export default function Bloc(data: {
  blocks: { id: string; type: string; data: unknown }[];
}) {
  return (

      {data.blocks.map((block) => (
        <CmsBlock data={block.data} type={block.type} key={block.id} />
      ))}

  );
}

It loads well but I have that modal with error  :

Unhandled Runtime Error
Error: Element type is invalid: expected a string (for built-in
components) or a class/function (for composite components) but got:
undefined. You likely forgot to export your component from the file
it's defined in, or you might have mixed up default and named imports.
Check the render method of Bloc.

It look like I messed up with a import/export but I can't handle to find it.

edit : Just discover that when I try a "next build", I have that error :
./src/pages/[[...slug]].tsx
Attempted import error: 'CmsBlock' is not exported from '@cleverconnect/cms-components' (imported as 'CmsBlock').

A: It's likely that block.data and/or block.type are undefined when you pass them to CmsBlock in the Bloc component. You can check that the data.blocks is not empty before mapping it.
Either approach bellow would do:
import { CmsBlock } from "cms-components";

export default function Bloc(data: {
  blocks: { id: string; type: string; data: unknown }[];
}) {
  return (

      {data.blocks && data.blocks.map((block) => (
        <CmsBlock data={block.data} type={block.type} key={block.id} />
      ))}

  );
}

or :
import { CmsBlock } from "cms-components";

export default function Bloc(data: {
  blocks: { id: string; type: string; data: unknown }[];
}) {
  return (

      {data.blocks.length ? data.blocks.map((block) => (
        <CmsBlock data={block.data} type={block.type} key={block.id} />
      )) : <> Some custom fallback message here: no data yet, sorry</>}

  );
}

A: Disclaimer: this is not really a solution, but more a dirty workaround.
I have exactly the same problem. It seems as thought the imported component is only undefined when NextJs does the initial render. Not sure exactly how that happens, but you can do a check to ensure that the import is not undefined before moving on with the real rendering.
import { CmsBlock } from "cms-components";

export default function Bloc(data: {
  blocks: { id: string; type: string; data: unknown }[];
}) {
  return CmsBlock ? (

      {data.blocks.map((block) => (
        <CmsBlock data={block.data} type={block.type} key={block.id} />
      ))}

  ) : null;
}


text:
Q: Set the HttpRequestExecutingMessageHandler's expectedResponseType to a Page I'm using a MessagingGateway to perform HTTP calls to another service.
This endpoint returns a slice of the data (using Pagination), the problem is that the returned result, is of type Page which is an interface. I know that the implementation of that interface is a class of type PageImpl but the problem is that when I'm trying to deserialize it, this class doesn't have any default constructor so it fails. I can create a POJO that contain the property needed and that will solve the problem, but I was wondering if there is any spring-trick that allow me to solve this in a better way.
This is an example of my message gateway configuration:
    Map<String, Expression> uriVariableExp = getDefaultEndpointProperties(host, apiKey);
    SpelExpressionParser parser = new SpelExpressionParser();

    uriVariableExp.put("parameter1", parser.parseExpression("payload.parameter1"));
    String endpoint =
            "{host}/resource?parameter1={parameter1}";

    HttpRequestExecutingMessageHandler gateway = new HttpRequestExecutingMessageHandler(endpoint, getRestTemplate());
    gateway.setRequiresReply(true);
    gateway.setHttpMethod(HttpMethod.GET);
    ParameterizedTypeReference<Page<ResourceModel>> typeReference = new ParameterizedTypeReference<Page<ResourceModel>>(){};
    gateway.setExpectedResponseTypeExpression(new ValueExpression<>(typeReference));
    gateway.setUriVariableExpressions(uriVariableExp);
    return gateway;

As you can see, the expectedResponseType is my problem, I tried with the PageImpl but this throw the error of no constructor found.

A: No, there is no such a built-in trick. Even worse: you client HttpRequestExecutingMessageHandler must not know about the model of the server and not have any Spring Data jars in its classpath. From big height that REST service should not return such a model into the response. Not only your application may be client to that.
Since you have already such a problem you just don't have choice unless introduce some VO POJO to be able to deserialize Page properly, or implement your own HttpMessageConverter to have a hook to instantiate the PageImpl as it is required by the Spring Data.


text:
Q: Get the latitude and longitude of multiple addresses using Google API I have a database of around 16000 records and i like to go through each address and get their latitude and longitude values.
I have tried exporting all records into excel sheet and then creat a macro to have a lat and lang values. It works for 80% of addresses, but google map api would return more results than Bing map as i have tried few addresses (which were not working with bing map) in google map and google is returning accurate values.
I like to use Google Map API to get latitude and longitude values as it has a limit of 25k requests per day.
I have got this java script which works fine but i don't know how can i use it with multiple addresses? I can loop through dataset but not sure if i need to call this java script function in the code behind page against every single address?
What is the best way to do this?
<script type="text/javascript">
<!--
    function GetLocation() {
        var geocoder = new google.maps.Geocoder();
        var address = document.getElementById("txtAddress").value;
        geocoder.geocode({ 'address': address }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                var latitude = results[0].geometry.location.lat();
                var longitude = results[0].geometry.location.lng();
                alert("Latitude: " + latitude + "\nLongitude: " + longitude);
            } else {
                alert("Request failed.")
            }
        });
    };
    //-->
</script>

A: You would need to call this function for each address and then store the resultant long and lat. You would also need to throttle the requests (possibly using setTimeout()) as the API also has a rate limit. You can only make so many requests per second.
Bear in mind though that the storing and subsequent display of results from the geocoding service is against Google's TOS. You will be breaking the licence agreement without a paid subscription, under section 10.1.3 c.

(c) No Mass Downloads or Bulk Feeds of Content. You must not use the Service in a manner that gives you or any other person access to mass downloads or bulk feeds of any Content, including but not limited to numerical latitude or longitude coordinates, imagery, visible map data, or places data (including business listings). For example, you are not permitted to offer a batch geocoding service that uses Content contained in the Maps API(s).

I think 16k coordinates will certainly count as bulk.

A: Google Usage Limits for Geocoding is 2,500 (Not 25k as you stated).

The Google Geocoding API has the following limits in place: 2,500
  requests per 24 hour period.
Google Maps API for Business customers have higher limits: 100,000
  requests per 24 hour period.

Here is my question regarding that in SO.
Your JavaScript code won't be counted in 2,500 limit, because it is run on client machine.
However, if you geocode using Geocoding API from code behind, then it counts in 2,500 limit.
protected void Button1_Click(object sender, EventArgs e)
{
    var uri = "http://maps.googleapis.com/maps/api/geocode/json?address=dallas&sensor=false";
    var result = new WebClient().DownloadString(uri);
}

Answer to your question

I have a database of around 16000 records and i like to go through
  each address and get their latitude and longitude values.

Easiest way will be to use WebClient, and Geocode 2,500/days and save them in database.

A: We can geocode the addresses directly in c# using the following code. Loop through excel records and convert addresses to the following format "1600+Amphitheatre+Parkway,+Mountain+View,+CA".
Sample Code: Change this code as per your needs
string url = "http://maps.googleapis.com/maps/api/geocode/" + "xml?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false";

WebResponse response = null;
bool is_geocoded = true;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
response = request.GetResponse();
string lat = "";
string lng = "";
string loc_type = "";
if (response != null)
{
    XPathDocument document = new XPathDocument(response.GetResponseStream());
    XPathNavigator navigator = document.CreateNavigator();

    // get response status
    XPathNodeIterator statusIterator = navigator.Select("/GeocodeResponse/status");
    while (statusIterator.MoveNext())
    {
        if (statusIterator.Current.Value != "OK")
        {
            is_geocoded = false;
        }
    }

    // get results
    if (is_geocoded)
    {
        XPathNodeIterator resultIterator = navigator.Select("/GeocodeResponse/result");
        while (resultIterator.MoveNext())
        {

            XPathNodeIterator geometryIterator = resultIterator.Current.Select("geometry");
            while (geometryIterator.MoveNext())
            {
                XPathNodeIterator locationIterator = geometryIterator.Current.Select("location");
                while (locationIterator.MoveNext())
                {
                    XPathNodeIterator latIterator = locationIterator.Current.Select("lat");
                    while (latIterator.MoveNext())
                    {
                        lat = latIterator.Current.Value;
                    }

                    XPathNodeIterator lngIterator = locationIterator.Current.Select("lng");
                    while (lngIterator.MoveNext())
                    {
                        lng = lngIterator.Current.Value;

                    }
                    XPathNodeIterator locationTypeIterator = geometryIterator.Current.Select("location_type");
                    while (locationTypeIterator.MoveNext())
                    {
                        loc_type = locationTypeIterator.Current.Value;
                    }
                }

            }
        }
    }
}

Note:
Google has limitations on Geo requests/Day. Check this link for usage limits and billing - https://developers.google.com/maps/documentation/javascript/usage?hl=en . Contact google based on your needs.
Also add Thread sleep for 1 or 2 ms just to make sure we are not overloading the google servers.


text:
Q: SQL Server OPENJSON read nested JSON same key array I am following the idea from Ed.Schavelev on article 'SQL Server OPENJSON read nested json'. But I need instead of repeating the rows I wanted them (4) to be in the columns. Is this possible?
I have tried as below:
DECLARE @json NVARCHAR(MAX)
SET @json =
  N'[

   {
      "EmployeeScheduleXRefCode":"#DF_10212",
      "EmployeeXRefCode":"7274",
      "TimeStart":"2022-10-31T05:30:00",
      "TimeEnd":"2022-10-31T15:30:00",
      "Published":false,
      "Breaks":[

      ],
      "Activities":[

      ],
      "Skills":[

      ],
      "LaborMetrics":[
         {
            "CodeXRefCode":"MEDIUM",
            "TypeXRefCode":"ACUITY_LM"
         },
         {
            "CodeXRefCode":"ATA",
            "TypeXRefCode":"EMPLOYEE_TYPE_LM"
         },
         {
            "CodeXRefCode":"BM02KR",
            "TypeXRefCode":"TEAM_NAME_LM"
         },
         {
            "CodeXRefCode":"AV_LM",
            "TypeXRefCode":"JOB_TYPE_LM"
         }
      ],
      "Segments":[

      ]
   },
   {
      "EmployeeScheduleXRefCode":"#DF_10200",
      "EmployeeXRefCode":"7269",
      "TimeStart":"2022-10-31T05:30:00",
      "TimeEnd":"2022-10-31T15:30:00",
      "Published":false,
      "Breaks":[

      ],
      "Activities":[

      ],
      "Skills":[

      ],
      "LaborMetrics":[
         {
            "CodeXRefCode":"MEDIUM",
            "TypeXRefCode":"ACUITY_LM"
         },
         {
            "CodeXRefCode":"ATA",
            "TypeXRefCode":"EMPLOYEE_TYPE_LM"
         },
         {
            "CodeXRefCode":"BM01KR",
            "TypeXRefCode":"TEAM_NAME_LM"
         },
         {
            "CodeXRefCode":"AV_LM",
            "TypeXRefCode":"JOB_TYPE_LM"
         }
      ],
      "Segments":[

      ]
   }
 ]'

SELECT Shifts.*,LaborMetrics.* FROM
 OPENJSON ( @json )
WITH (
              EmployeeScheduleXRefCode   varchar(200) '$.EmployeeScheduleXRefCode' ,
              EmployeeXRefCode     varchar(200)     '$.EmployeeXRefCode',
              TimeStart Datetime '$.TimeStart',
              TimeEnd Datetime '$.TimeEnd',
              LaborMetrics nvarchar(max) as json
 ) as Shifts
 cross apply openjson (Shifts.LaborMetrics)
 with
(
    CodeXRefCode nvarchar(100),
    TypeXRefCode nvarchar(100)
) as LaborMetrics

But the result is repeating 4 rows and I want them to have them in 4 different columns in a single row.


text:
Q: Github SSH is connected but fails when cloning a repository into Digital ocean droplet I'm setting up a laravel website with a Digital Ocean droplet.
This process is so difficult and frustrating, I'm losing logic sense...
I'm connected with an ssh key that is connected with github, because I tried this code to test my connection:
ssh -T git@github.com

with this as response:
> Hi (My name)! You've successfully authenticated, but GitHub does not
> provide shell access.

So it is connected.
However, when I want to clone my repository into my online droplet. I get the error:
git@github.com: Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

So I have no idea how to fix this..
My ssh key inside my digital ocean settings is the same as in my github ssh settings.
Any ideas how to fix this?

A: I've found the solution myself!
So what was the problem?
I was using the ssh key from my localhost as an access key for cloning private github repositories. That is why I couldn't clone into an online service because that online service has it's own specific ssh key. So inside my server, I generated an ssh-key and registered that one on github. When I tried cloning me repo inside my droplet
everything worked as it should do.


text:
Q: .net Connectivity to mainframe Can any one please suggest me the best approach to connect to mainframe from .net.
I have to develop an web application, in which i have to follow NIEM standards for data exchange between two end clients. the interface i have to develop will be on .net. i don't have any knowledge on mainframe, i have come across that there are ODBC connectivity/ MQ series. i'm afraid which approach to follow on as i have less knowledge on the mainframe system. any suggestion would be really helpfully to me.
any article , links or sample code will be greatly appreciated
Thanks

A: If you need to connect to a DB2 database residing on a mainframe, DB2Connect is the way to go (I think it may be literally the only way to go).
If you need your .Net software to talk to software running on a mainframe, however, your life will be less happy, especially if you know nothing about mainframes and the person responsible for the mainframe software knows nothing about Windows.  I've been in this latter situation a few times, and the simplest, most aspirin-free way to deal with it is to set up a file-share location on the mainframe that is accessible both to the mainframe code and to the Windows network, and have both sides exchange data by writing to and reading from files located there (yes, this is a hack, but one which works quite well).

A: More detail would be good.

*

*are you talking TCP/IP - which is possible but probably a PITA?

*are you talking direct database (e.g. DB2) interactions (see other answer)?

*are you talking about something more complex such as use of the WebSphere MQ mechanisms (which offer general data connectivity abstractions across multiple platforms/languages)?

A: Really need more information to provide a good answer.  But you can use ODBC or DB2connect for database access.
If you need XML for the NIEM data exchange you can use xml4c, xml4j or IBM Cobol has built-in XML parsing.
To move XML files between the two, your mainframe will support NFS, raw TCP/IP sockets, ftp, JCA, http, MQ...pretty much all the options you have on other platforms.
What mainframe technologies are you hooking up to?  CICS? WebSphere? z/Linux? USS? TSO? Batch Jobs?  IMS/DC?  If you provide some more information, perhaps a better answer can be given.

A: DB2Connection cn = new DB2Connection("Database=TEST;UserID=db2admin;Password=password;Server=IS500");
DB2Command cmd = new DB2Command("SELECT COUNT(*) FROM EMP01", cn);
int count = Convert.ToInt32(cmd.ExecuteScalar());

Refer to this link to clarify your doubts:
http://www.codeproject.com/Articles/4870/Connect-to-DB-from-Microsoft-NET


text:
Q: how to get the if else condition using filter operation of java stream? Question :
from the list of an integer get the square of odd number and half the even number and then return the list of value.
Ans : 1> i will write the logic and  if else condition inside the map() method.
List<Integer> output = intArray.stream().map(x-> {
                        if(x%2 ==0){
                            x=x/2;
                        }else{
                            x= x*x;
                        }
                     }).collect(Collectors.toList());

Is their any better way to do this specially using Filter?

A: Try using map:
map(x -> x % 2 == 0? x / 2: x * x);

Let me know if this works for you.
You can learn more about map and filter here

A: As you are transforming data (performing a math operation), you cannot use Filter here. Filter is used to filter out elements in your stream. For example if you only want to preserve the even numbers, you could use a Filter
What you need to use is the Map, as you already did. Do note that a map should always return data. Your code is missing this return statement.
To make it more readable, you could split your mapping logic in a method. This makes your stream easy to read and easy to follow (when you give the method a good name ofcourse).
Code example
List<Integer> output = intArray.stream()
            .map(test::divideOrPow)
            .collect(Collectors.toList());

private int divideOrPow(intx) {
    if (x % 2 == 0) {
        return x / 2;
    } else {
        return x * x;
    }
}


text:
Q: PySpark - Format String using Column Values I'm trying to create a new column that creates a string using 4 columns.
df.withColumn("input",
                    F.lit("http://address.com/process?field1={}&field2={}&field3={}&field4={}".format(F.col('field1'),F.col('field2'),F.col('field3'),F.col('field4'))).show()

However, where I'm trying to insert the column values into the string, it's showing up as field1=Column<'field1'> instead of the actual value. I tried wraping it in F.format_string as well but I'm not getting the actual values.
So what it should be returning is something like this, assuming that each column has a string = VALUE.
http://address.com/process?field1=VALUE&field2=VALUE&field3=VALUE&field4=VALUE

A: You can use format_string function like this:
import pyspark.sql.functions as F

df = df.withColumn(
    "input",
    F.format_string(
        "http://address.com/process?field1=%s&field2=%s&field3=%s&field4=%s",
        F.col('field1'), F.col('field2'), F.col('field3'), F.col('field4')
    )
)

df.show(truncate=False)

#+------+------+------+------+--------------------------------------------------------------+
#|field1|field2|field3|field4|input                                                         |
#+------+------+------+------+--------------------------------------------------------------+
#|a     |b     |c     |d     |http://address.com/process?field1=a&field2=b&field3=c&field4=d|
#+------+------+------+------+--------------------------------------------------------------+

A: You should use concat, not lit, so something like F.concat(F.lit('http://example.com/'), F.col('field1'), F.lit('/'), F.col('field2'))


text:
Q: Question about Importing Swift code into objective c code I read this documentation for importing swift code into objective c.
https://developer.apple.com/documentation/swift/imported_c_and_objective-c_apis/importing_swift_into_objective-c
I have a few questions.

*

*Can I put @objc annotation for a Struct?

*

Do I need to inherit all the class that I want to export to obj to be child of NSobject ? I am getting error 'error: only classes that inherit from NSObject can be declared @objc'

*When I export a swift class with @objc, I need to add @objc to all its parent classes, protocol and interface and also class and structure in all its methods, is that correct?

A: *

*No. Objective-C cannot see a native Swift struct.

*Yes. Objective-C classes must basically be derived from NSObject. Objective-C can be made aware of the existence of other classes, but it cannot do anything useful with them.

*You can mark the class with @objcMembers, in which case you will give everything within it full visibility to Objective-C.


text:
Q: md-autocomplete input height issue in safari I am using AngularJS v1.5.6 and AngularJS Material Design v1.1.8, md-autocomplete works fine in all browsers except Safari. Height of the input search box is not filled 100%. See below image for reference
Safari Version 12.0.3 (14606.4.5)

A: you can add css override the default cssStyle to hack the Safari. such as input 100%


text:
Q: The connection string 'SGPHARM' in the application's configuration file does not contain the required providerName attribute I'm new in .net, and i'm developping a desktop application with C# and postgres database usin npgsql.
Here is my app.config connectionString:
<connectionStrings> <add name="SGPHARM" connectionString="host=localhost; port=5432; database=SGPHARM; user id=postgres; password=admin" providerName="Npgsql" /> </connectionStrings>

I'm using alsow Code First Approach.
When i'm trying to create a new Product i'm getting the folowing error:
"configuration file does not contain the required providerName attribute"
But my providername is specified in the app.config file.
I'm don't now where is the problem.
thanks in advance

A: I found the solution myself.
The provider name npgsql was not specified in the project_name.exe.config file.


text:
Q: Pushing a navigation controller is not supported- performing segues I created a new navigation controller in my storyboard (not programmatically!) and set it to be "Root View Controller" to a regular UIViewController and added a button in it which says- forward to the next view controller (this second view controller is a view controller which I want that will have a back button to link to the initial view controller).
Now, whenever I try to link the button to the next view controller- "Pushing a navigation controller is not supported".
Help me please, and thanks
EDIT:
I accidentally subclassed UINavigationController, and not UIViewController in my class.
Thank you anyway.

A: I've tried this and have no problems, its all done in IB with no additional code required  ...

*

*Start a new project, "Single View Application" using story boards

*Select storyboard and delete the views its produced.

*Drag on a new Navigation Controller (it will bring a table view with it)

*Delete the table and the table view controller, so you are just left with the Navigation Controller

*Drag on a normal view controller

*Right Click and drag from the Navigation controller to the new View and choose "Relationship - Root View Controller"

*Drag a "Bar Button Item" on to the Navbar which should be visible on the top of your ViewController, you can rename this Forward if you wish.

*Now drag on another view controller which is the one your "Forward" button will push in to view.

*Right Click and drag from the bar button to the 2nd View Controller, and choose "Push"

Run the project and you will get a Single view with a Navbar and your button, clicking your button will Push the other view and give you a Back Button to return to the first View Controller. I'll try and post a picture of my storyboard if it helps.

Plasma

A: I had the same trouble. I wanted to have a navigation controller on each storyboard, so that each could run independently, be individually debugged, and so that the look would be right with the navigation bar.
Using other approaches, I found the UINavigationController would be retained from the original storyboard -- which I didn't want -- or I'd get errors.
Using the AppDelegate in your view controller to set the rootViewController worked for me (borrowing segue naming conventions from Segue to another storyboard?):
- (void)showStartupNavigationController {
NSLog(@"-- Loading storyboard --");

//Get the storyboard from the main bundle.
UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Startup" bundle:nil];
//The navigation controller, not the view controller, is marked as the initial scene.
UINavigationController *theInitialViewController = [storyBoard instantiateInitialViewController];

NSLog(@"-- Loading storyboard -- Nav controller: %@", theInitialViewController);

//Remove the current navigation controller.
[self.navigationController.view removeFromSuperview];
UIWindow *window = [(AppDelegate *)[[UIApplication sharedApplication] delegate] window];
window.rootViewController = theInitialViewController;

A: To swap views Programatically you would need to select the segue and give it an Identifier like "PushView" then call it like this  ....
[self performSegueWithIdentifier:@"PushView" sender:self];

That will programatically do the same as clicking the forward button. I've created you an example project with the code discussed above. Has an -(IBAction) with code in you can use for programatially changing the view.
PushView.zip

A: I also wanted to do this, present a screen (that had an embedded navigation controller) when the user pushes a button.
At my first attempt, I connected the segue from the button in the fist screen to the Navigation Controller, and the app was crashing with this error "Pushing a navigation controller is not supported".
This is the solution I found:
Select the segue from the button in the first screen to the navigation controller.
If it had an identifier, copy its name. Then delete that segue.
Then create a new segue by CTRL-clicking the button in the first view controller and dragging to the VIEW CONTROLLER YOU WANT TO PRESENT (not to the Navigation Controller that is pointing at it), and select Push in the small pop up window.
Then click the icon in the middle of the segue and paste the name you copied in the first step as an identifier for it.
IB is going to give you a warning "Scene is unreachable due to lack of entry points and does not have an identifier for runtime access via -instantiateViewControllerWithIdentifier:."  Don't worry, it works perfectly.
If you want to customize the string that is shown as the Back button to return, you can add this line in the viewDidLoad method OF THE VIEW CONTROLLER THAT IS BEING SHOWED AFTER THE BUTTON IS PRESSED, that is the Child view controller.
(replace "Settings" with the name you need)
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationController.navigationBar.topItem.title = @"Settings";
    ...

}


text:
Q: java.lang.OutOfMemoryError A camera app I have an issue/ problem, i've been searching for a couple of weeks and still no solution.
this app is for taking a photo with a frame inside it. the frame is in PNG.
When I start the app everythong goes great, but when I click the button to take a picture the app crashes . sometimes it give OutOfMemoryError and sometimes ArrayIndexOutOfBoundsException so I tried almost everything and yet nothing.
should I change the size of the drawbles? or should I set the size of the final bmp ?
I'm sorry for my English since I'm french..
here is the code
private class CapturePictureCallback implements PictureCallback {

    @Override
    public void onPictureTaken(byte[] data, Camera camera) {

        Bitmap picBitmap = BitmapFactory.decodeByteArray(data, 10,
                data.length);

        final ViewFlipper flipper = (ViewFlipper) findViewById(R.id.main_flipper);
        View flipperView = flipper.getCurrentView();

        Bitmap flipperBitmap = Bitmap.createBitmap(flipperView.getWidth(), flipperView.getHeight(), Bitmap.Config.ARGB_4444);
        Canvas flipperCanvas = new Canvas(flipperBitmap);
        flipperView.draw(flipperCanvas);
        Bitmap resizedFlipperBitmap = Bitmap.createScaledBitmap(flipperBitmap, 500, 300, true);

        // Insert image on top
        Bitmap overlaidBitmap = overlay(picBitmap, resizedFlipperBitmap);

        picBitmap.recycle();
        resizedFlipperBitmap.recycle();

        // Create file
        save(overlaidBitmap);
        overlaidBitmap.recycle();
        camera.startPreview();
    }

    private Bitmap overlay(Bitmap bmp1, Bitmap bmp2) {
        Bitmap bmOverlay = Bitmap.createBitmap( 0,0, bmp1.getConfig());
        Canvas canvas = new Canvas(bmOverlay);
        canvas.drawBitmap(bmp1, new Matrix(), null);
        canvas.drawBitmap(bmp2, new Matrix(), null);
        return bmOverlay;
    }

    private void save(Bitmap bitmap) {
        File picturesFolder = null;
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.ECLAIR_MR1) {
            picturesFolder = new File(
                    Environment.getExternalStorageDirectory(), "Pictures");
        } else {
            picturesFolder = Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        }

        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
        String dateString = sdf.format(date);
        String fileName = "kissthepresident" + dateString + ".jpeg";
        File pictureFile = new File(picturesFolder, fileName);

        try {
            FileOutputStream fos = new FileOutputStream(pictureFile);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bos);
            bitmap.recycle();

            if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.ECLAIR_MR1) {
                ContentValues values = new ContentValues(7);

                values.put(Images.Media.TITLE, fileName);
                values.put(Images.Media.DISPLAY_NAME, fileName);
                values.put(Images.Media.DATE_TAKEN, dateString);
                values.put(Images.Media.MIME_TYPE, "image/jpeg");
                values.put(Images.Media.ORIENTATION, 0);
                values.put(Images.Media.DATA,
                        pictureFile.toString());
                values.put(Images.Media.SIZE, pictureFile.length());

                Uri uri = Uri.fromFile(pictureFile);
                getContentResolver().insert(uri, values);

            } else {
                MediaScannerConnection.scanFile(getApplicationContext(),
                        new String[] { pictureFile.toString() }, null,
                        new MediaScannerConnection.OnScanCompletedListener() {
                    public void onScanCompleted(String path, Uri uri) {
                        Log.i("ExternalStorage", "Scanned " + path + ":");
                        Log.i("ExternalStorage", "-> uri=" + uri);
                    }
                });

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
@Override
protected void onDestroy() {
    super.onDestroy();

    unbindDrawables(findViewById(R.id.main_layout));
    System.gc();
}

private void unbindDrawables(View view) {
    if (view.getBackground() != null) {
        view.getBackground().setCallback(null);
    }
    if (view instanceof View) {
        for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
            unbindDrawables(((ViewGroup) view).getChildAt(i));
        }
        ((ViewGroup) view).removeAllViews();
    }
}

and here is the catlog
FATAL EXCEPTION: main java.lang.ArrayIndexOutOfBoundsException
at android.graphics.BitmapFactory.decodeByteArray(BitmapFactory.java:403)
at android.graphics.BitmapFactory.decodeByteArray(BitmapFactory.java:418)
at com.kissthepresidents.Main$CapturePictureCallback.onPictureTaken(Main.java:255)
at android.hardware.Camera$EventHandler.handleMessage(Camera.java:529)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:3701)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:862)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
at dalvik.system.NativeStart.main(Native Method)

A: One problem: decodeByteArray(byte[] data, int offset, int length)
Bitmap picBitmap = BitmapFactory.decodeByteArray(data, 10,
            data.length);

Should be (I don't know what your offset of 10 is about, but you should correct the length).
Bitmap picBitmap = BitmapFactory.decodeByteArray(data, 10,
            data.length - 10);


text:
Q: Wikitude crash on Xamarin.Android app No virtual method setLightEstimationMode I'm running Xamarin.Wikitude.SDK.JS plugin, version 8.6.0 on a Xamarin.Android Project.
When loading the Wikitude provided example, the app crashes.
The example is https://github.com/Wikitude/wikitude-sdk-samples/tree/master/05_InstantTracking_3_Interactivity
I've added code to check if ARCore is installed. If not an alert is shown so users can install ARCore if the device is supported.
Here is the console Output:

No pending exception expected: java.lang.NoSuchMethodError: No virtual
  method
  setLightEstimationMode(Lcom/google/ar/core/Config$LightEstimationMode;)V
  in class Lcom/google/ar/core/Config; or its super classes (declaration
  of 'com.google.ar.core.Config' appears in
  /data/app/XXXXXXXXXXXXXXXX-2o7U_ByKTJBW9vPIXZeXHA==/base.apk) at
  com.google.ar.core.Config
  com.wikitude.common.arcore.internal.ArCoreTracker.k() (SourceFile:462)
  at void com.wikitude.common.arcore.internal.ArCoreTracker.a()
  (SourceFile:177) at void
  com.wikitude.common.arcore.internal.NativeArCoreInterface.start()
  (SourceFile:42) at void
  com.wikitude.common.camera.internal.NativeCameraInterface.nativeCameraReleased(long)
  (SourceFile:-2) at void
  com.wikitude.common.camera.internal.NativeCameraInterface.b()
  (SourceFile:194) at void
  com.wikitude.common.camera.internal.DeviceCamera2.l() (SourceFile:368)
  at void com.wikitude.common.camera.internal.d.b() (SourceFile:85) at
  void
  com.wikitude.common.camera.internal.NativeCameraInterface.doStop()
  (SourceFile:37) at void
  com.wikitude.architect.PlatformBridge.callAsyncImplInternal(long,
  java.lang.String) (SourceFile:-2) at void
  com.wikitude.architect.PlatformBridge.callAsyncImpl(java.lang.String)
  (SourceFile:134) at void
  com.wikitude.architect.PlatformBridge$a.a(java.util.List, int)
  (SourceFile:66) at void com.wikitude.architect.PlatformBridge$a.run()
  (SourceFile:40)

I've tried another example without AR (ImageOnTarget) and it's working so I suppose Wikitude is correctly configured.

A: I've found out!
The problem was the package Xamarin.Google.ARCore used to check if device supports AR and user had installed ARCore.
This plugin conflicts with Wikitude SDK so after removing it, Wikitude AR started working


text:
Q: Get first element in each row of 2d array How do you iterate through a 2d array and get the first element in each row? For example:
int[,] array = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12} };

desired output: 1 4 7 10

A: Something like this should do the trick:
int[,] array = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12} };
for (int row = 0; row < array.GetLength(0); ++row)
{
    Console.WriteLine(array[row, 0]);
}

Try it online


text:
Q: How to feed the classifier to train on Tensorflow I read the images that will be used to train my classifier in a Dataset as follows:
filename_strings = []
label_strings = []
for dirname, dirnames, filenames in os.walk('training'):
    for filename in filenames:
        filename_strings.append(dirname + '\\' + filename)
        label_strings.append(dirname)

filenames = tf.constant(filename_strings)
labels    = tf.constant(label_strings)
dataset = tf.contrib.data.Dataset.from_tensor_slices((filenames, labels))
dataset_train = dataset.map(_parse_function)

_parse_function:
# Reads an image from a file, decodes it into a dense tensor, and resizes it
# to a fixed shape.
def _parse_function(filename, label):
    image_string = tf.read_file(filename)
    image_decoded = tf.image.decode_png(image_string)
    image_resized = tf.image.resize_images(image_decoded, [28, 28])
    return image_decoded, label

But now I am not able to feed the train step.:
# Create the Estimator
mnist_classifier = tf.estimator.Estimator(
model_fn=cnn_model_fn, model_dir="/model")
# Set up logging for predictions
tensors_to_log = {"probabilities": "softmax_tensor"}
logging_hook = tf.train.LoggingTensorHook(
tensors=tensors_to_log, every_n_iter=50)

# Train the model
train_input_fn = tf.estimator.inputs.numpy_input_fn(
    x= {"x": dataset_train },
    y= dataset_train,
    batch_size=100,
    num_epochs=None,
    shuffle=True)
mnist_classifier.train(
    input_fn=train_input_fn,
    steps=200,
    hooks=[logging_hook])

I am trying to follow this tutorial A Guide to TF Layers: Building a Convolutional Neural Network  but with my own image set.
Can I not use the dataset directly to feed the train step? I mean, I just have a tensor with the feature and label for each image.

A: The tutorial you refer to reads the data into a numpy array (see the code here) and pass the input with tf.estimator.inputs.numpy_input_fn. This is the easiest way.
However, if you prefer to operate with tensors from the very beginning, it's possible as well using a custom input function. Here's a trivial example:
def read_images(batch_size):
  # A stub. Should read the next batch, shuffle it, etc
  images = tf.zeros([batch_size, 28, 28, 1]) # 4-rank tensor
  labels = tf.ones([batch_size])             # 1-rank tensor (not one-hot encoded)
  return images, labels

def simple_input():
  x, labels = read_images(batch_size=10)
  return {"x": x}, labels

tensors_to_log = {"probabilities": "softmax_tensor"}
logging_hook = tf.train.LoggingTensorHook(tensors=tensors_to_log, every_n_iter=50)

classifier.train(input_fn=simple_input,
                 steps=10,
                 hooks=[logging_hook])


text:
Q: Plotting large number of time series using ggplot. Is it possible to speed up? I am working with thousands of meteorological time series data (Sample data can be downloaded from here)
https://dl.dropboxusercontent.com/s/bxioonfzqa4np6y/timeSeries.txt
Plotting these data using ggplot2 on my Linux Mint PC (64bit, 8GB RAM, Dual-core 2.6 GHz) took a lot of time. I'm wondering if there is a way to speed it up or a better way to plot these data? Thank you very much in advance for any suggestion!
This is the code I'm using for now
##############################################################################
#### load required libraries
library(RCurl)
library(reshape2)
library(dplyr)
library(ggplot2)

##############################################################################
#### Read data from URL
dataURL <- "https://dl.dropboxusercontent.com/s/bxioonfzqa4np6y/timeSeries.txt"
tmp <- getURL(dataURL)
df <- tbl_df(read.table(text = tmp, header = TRUE))
df

##############################################################################
#### Plot time series using ggplot2
# Melt the data by date first
df_melt <- melt(df, id = "date")
str(df_melt)

df_plot <- ggplot(data = df_melt, aes(x = date, y = value, color = variable)) +
  geom_point() +
  scale_colour_discrete("Station #") +
  xlab("Date") +
  ylab("Daily Precipitation [mm]") +
  ggtitle("Daily precipitation from 1915 to 2011") +
  theme(plot.title = element_text(size = 16, face = "bold", vjust = 2)) + # Change size & distance of the title
  theme(axis.text.x = element_text(angle = 0, size = 12, vjust = 0.5)) + # Change size of tick text
  theme(axis.text.y = element_text(angle = 0, size = 12, vjust = 0.5)) +
  theme( # Move x- & y-axis lables away from the axises
    axis.title.x = element_text(size = 14, color = "black", vjust = -0.35),
    axis.title.y = element_text(size = 14, color = "black", vjust = 0.35)) +
  theme(legend.title = element_text(colour = "chocolate", size = 14, face = "bold")) + # Change Legend text size
  guides(colour = guide_legend(override.aes = list(size = 4))) + # Change legend symbol size
  guides(fill = guide_legend(ncols = 2))
df_plot

A: Part of your question asks for a "better way to plot these data".
In that spirit, you seem to have two problems, First, you expect to plot >35,000 points along the x-axis, which, as some of the comments point out, will result in pixel overlap on anything but an extremely large, high resolution monitor. Second, and more important IMO, you are trying to plot 69 time series (stations) on the same plot. In this type of situation a heatmap might be a better approach.
library(data.table)
library(ggplot2)
library(reshape2)          # for melt(...)
library(RColorBrewer)      # for brewer.pal(...)
url <-  "http://dl.dropboxusercontent.com/s/bxioonfzqa4np6y/timeSeries.txt"
dt  <- fread(url)
dt[,Year:=year(as.Date(date))]

dt.melt  <- melt(dt[,-1,with=F],id="Year",variable.name="Station")
dt.agg   <- dt.melt[,list(y=sum(value)),by=list(Year,Station)]
dt.agg[,Station:=factor(Station,levels=rev(levels(Station)))]
ggplot(dt.agg,aes(x=Year,y=Station)) +
  geom_tile(aes(fill=y)) +
  scale_fill_gradientn("Annual\nPrecip. [mm]",
                       colours=rev(brewer.pal(9,"Spectral")))+
  scale_x_continuous(expand=c(0,0))+
  coord_fixed()

Note the use of data.tables. Your dataset is fairly large (because of all the columns; 35,000 rows is not all that large). In this situation data.tables will speed up processing substantially, especially fread(...) which is much faster than the text import functions in base R.


text:
Q: RestTemplate & Jackson - Custom JSON deserializing? The webservice returns an empty string instead of NULL which causes Jackson to crash.
So I created a custom parser, and I'm trying to parse it manually? Any idea How I could achieve this?
What Am I doing wrong here? All I'm trying to do is to parse JSON to object as I normally would. The field names are added to my properties using @JsonProperty so the parser should know how to convert it.
public class InsertReplyDeserializer extends JsonDeserializer<ListingReply> {

    @Override
    public ListingReply deserialize(JsonParser jsonParser, DeserializationContext arg1)
            throws IOException, JsonProcessingException {

        ObjectCodec oc = jsonParser.getCodec();
        JsonNode node = oc.readTree(jsonParser);

        // If service returns "" instead of null return a NULL object and don't try to parse
        if (node.getValueAsText() == "")
            return null;

       ObjectMapper objectMapper = new ObjectMapper();
       ListingReply listingReply = objectMapper.readValue(node, ListingReply.class);

       return listingReply;
    }

}

A: Here is how I resolved it
@Override
public MyObject deserialize(JsonParser jsonParser, DeserializationContext arg1)
        throws IOException, JsonProcessingException {

    ObjectCodec oc = jsonParser.getCodec();
    JsonNode node = oc.readTree(jsonParser);

    if (node.getValueAsText() == "")
        return null;

    MyObject myObject = new MyObject();
    myObject.setMyStirng(node.get("myString").getTextValue());

    JsonNode childNode = node.get("childObject");
    ObjectMapper objectMapper = new ObjectMapper();
    ChildObject childObject = objectMapper.readValue(childNode,
            ChildObject.class);

             myObject.setChildObject(childObject);
             return myObject;
}

A: I am not sure you need to manually parse response. You solution would work but seems sub-optimal in my opinion. Since it looks like that you are using RestTemplate, you should rather write (or move your parser code to) your own message converter. Then add this converter to your rest template object which will internally deserialize the value for you. Something along the lines,
public class CustomHttpmsgConverter extends  AbstractHttpMessageConverter<Object> {
private ObjectMapper objectMapper = new ObjectMapper();
@Override
protected Object readInternal(Class clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
   InputStream istream = inputMessage.getBody();
   String responseString = IOUtils.toString(istream);
   if(responseString.isEmpty()) //if your response is empty
     return null;
   JavaType javaType = getJavaType(clazz);
   try {
       return this.objectMapper.readValue(responseString, javaType);
   } catch (Exception ex) {
    throw new HttpMessageNotReadableException(responseString);
    }
}

//add this converter to your resttemplate
    RestTemplate template = new RestTemplate();
    List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
    converters.add(new CustomHttpmsgConverter());
    template.setMessageConverters(converters);


text:
Q: How to make change to line in .js with css I am trying to change arrow style of Fancybox in WordPress plugin called Elementor Add-ons. Support replied that I need to make change to line number 1190 of assets/js/lae-blocks.js file, add the option btnTpl, and also grab the current instance so that updates don't swipe them away.
//These are from fancybox web - https://fancyapps.com/fancybox/3/docs/#options
btnTpl: {
    arrowLeft:
      '<button data-fancybox-prev class="fancybox-button fancybox-button--arrow_left" title="{{PREV}}">' +
      '
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M11.28 15.7l-1.34 1.37L5 12l4.94-5.07 1.34 1.38-2.68 2.72H19v1.94H8.6z"/></svg>
' +
      "</button>",

    arrowRight:
      '<button data-fancybox-next class="fancybox-button fancybox-button--arrow_right" title="{{NEXT}}">' +
      '
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M15.4 12.97l-2.68 2.72 1.34 1.38L19 12l-4.94-5.07-1.34 1.38 2.68 2.72H5v1.94z"/></svg>
' +
      "</button>"
}

// For current instance
var instance = $.fancybox.getInstance()

//Base64 of my new buttons are:
//right
data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/PjxzdmcgaGVpZ2h0PSI0OCIgdmlld0JveD0iMCAwIDQ4IDQ4IiB3aWR0aD0iNDgiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTE3LjE3IDMyLjkybDkuMTctOS4xNy05LjE3LTkuMTcgMi44My0yLjgzIDEyIDEyLTEyIDEyeiIvPjxwYXRoIGQ9Ik0wLS4yNWg0OHY0OGgtNDh6IiBmaWxsPSJub25lIi8+PC9zdmc+

//left
data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/PjxzdmcgaGVpZ2h0PSI0OCIgdmlld0JveD0iMCAwIDQ4IDQ4IiB3aWR0aD0iNDgiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTMwLjgzIDMyLjY3bC05LjE3LTkuMTcgOS4xNy05LjE3LTIuODMtMi44My0xMiAxMiAxMiAxMnoiLz48cGF0aCBkPSJNMC0uNWg0OHY0OGgtNDh6IiBmaWxsPSJub25lIi8+PC9zdmc+

I simply lack knowledge putting it all together. How do I do this?

A: You can simply change defaults, like this:
$.fancybox.defaults = $.extend(true, {}, $.fancybox.defaults, {
  btnTpl: {
    arrowLeft: '<button data-fancybox-prev class="fancybox-button fancybox-button--arrow_left" title="{{PREV}}">' +
      '

' +
      "</button>",

    arrowRight: '<button data-fancybox-next class="fancybox-button fancybox-button--arrow_right" title="{{NEXT}}">' +
      '

' +
      "</button>",
  }
});

DEMO https://codepen.io/fancyapps/pen/YgmBOx

A: I think that what you want is to replace the content within the <svg> tags of arrowLeft and arrowRight with your own SVGs. This would be:
btnTpl: {
    arrowLeft:
        '<button data-fancybox-prev class="fancybox-button fancybox-button--arrow_left" title="{{PREV}}">' +
        '
<svg xmlns="http://www.w3.org/2000/svg" height="48" viewBox="0 0 48 48" width="48"><path d="M30.83 32.67l-9.17-9.17 9.17-9.17-2.83-2.83-12 12 12 12z"/><path d="M0-.5h48v48h-48z" fill="none"/></svg>
' +
        '</button>',

    arrowRight:
        '<button data-fancybox-next class="fancybox-button fancybox-button-- arrow_right" title="{{NEXT}}">' +
        '
<svg xmlns="http://www.w3.org/2000/svg" height="48" viewBox="0 0 48 48" width="48"><path d="M17.17 32.92l9.17-9.17-9.17-9.17 2.83-2.83 12 12-12 12z"/><path d="M0-.25h48v48h-48z" fill="none"/></svg>
' +
        '</button>'
}

Hope this works!


text:
Q: How to replace arguments.callee to be able to 'use strict' I have some old code and I need to refactor/rewrite arguments.callee.caller.caller and arguments.callee.caller in two funcs to be able to 'use strict'.
Can be max up to ECMAScript 2019, thanks!
const utils = {
/**
 * @return {string}
 */
caller: function (string, callerName) {
    const caller = /^function\s+([^(]+)/.exec(/** @type{string} */ arguments.callee.caller.caller.toString());
    return caller ? caller[1] : '';
},
/**
 * @return {string}
 */
function_name: function () {
    const caller = /^function\s+([^(]+)/.exec(/** @type{string} */ arguments.callee.caller.toString());
    return caller ? caller[1] : '';
}

};


text:
Q: Puppet best practice for storing scripts for custom modules I have Windows agent nodes. I am creating my own module which has some custom powershell scripts. I am wondering where should i be keeping these powershell scripts. Within my module itself in some folder (say, scripts dir) or somewhere outside my module's directory? What's the recommended/best practice in such scenario?
git/
    - client
        - hieradata
        - manifests
        - modules
            - my_module
                - scripts/ # 1) Should it be within this dir?
                    - my_script.ps1
        - scripts/         # 2) Should it be within this dir or elsewhere?
            - my_script.ps1
        - templates

A: A module can ship with its own files and templates:
[modules_root]
    my_module
        files
            my_script
        manifests
            init.pp
        templates
            other_script.erb

As OPs post suggests installing templates out of the modules scope, ... I feel it is necessary to also note that we would install these with:
file {
    "/etc/toto":
        source => "puppet:///modules/my_module/my_script";
    "/etc/tata":
        content => template("my_module/other_script.erb");
}

A: Modules are self-contained bundles of code and data. You can download pre-built modules from the Puppet Forge or you can write your own modules.
According to the official documentation, there isn't any "good" practice where to put your personal scripts for a custom module.
However, the folder files can contain Contains static files, which managed nodes can download which is the closest place to put some personal scripts.
You could also create a script folder, if you believe it's clear enough for others people to read, and understand your module.
 On disk, a module is simply a directory tree with a specific, predictable structure:

 - manifests
 - files
 - templates
 - lib
 - facts.d
 - examples
 - spec
 - functions
 - types

In term of more general best practice, I would recommend you to read this.

A: The only place you should be storing those scripts is in the module's files directory.
You can then deploy the script using the source parameter of the file resource like so:
file {'myfile':
  ensure => file,
  source => 'puppet:///modules/mymodule/myfile',
}


text:
Q: using d3 to visualize data in a webmapping application built with Openlayers I am trying to build a web mapping application using openlayers 3 for map interaction and d3 to visualize data on the map , i tried this example: https://openlayers.org/en/latest/examples/d3.html but it seems it didn't work; there is a problem of precesion as you can see in this picture :result
here is my code:
var canvasNbr = function(extent, resolution, pixelRatio,
  size, projection) {
var canvasWidth = size[0];
var canvasHeight = size[1];

var canvas = d3.select(document.createElement('canvas'));
canvas.attr('width', canvasWidth).attr('height', canvasHeight);

var context = canvas.node().getContext('2d');

var d3Projection = d3.geo.conicConformal()
. scale ( 1 );
var d3Path = d3.geo.path().projection(d3Projection);

var pixelBounds = d3Path.bounds(regions);
var pixelBoundsWidth = pixelBounds[1][0] - pixelBounds[0][0];
var pixelBoundsHeight = pixelBounds[1][1] - pixelBounds[0][1];

var geoBounds = d3.geo.bounds(regions);
var geoBoundsLeftBottom = ol.proj.transform(
    geoBounds[0], 'EPSG:4326', projection);
var geoBoundsRightTop = ol.proj.transform(
    geoBounds[1], 'EPSG:4326', projection);
var geoBoundsWidth = geoBoundsRightTop[0] - geoBoundsLeftBottom[0];
if (geoBoundsWidth < 0) {
  geoBoundsWidth += ol.extent.getWidth(projection.getExtent());
}
var geoBoundsHeight = geoBoundsRightTop[1] - geoBoundsLeftBottom[1];

var widthResolution = geoBoundsWidth / pixelBoundsWidth;
var heightResolution = geoBoundsHeight / pixelBoundsHeight;
var r = Math.max(widthResolution, heightResolution);
var scale = r / (resolution / pixelRatio);

var center = ol.proj.transform(ol.extent.getCenter(extent),
    projection, 'EPSG:4326');
d3Projection.scale(scale).center(center)
    .translate([canvasWidth / 2, canvasHeight / 2]);
d3Path = d3Path.projection(d3Projection).context(context);

d3Path(regions);
context.stroke();

return canvas[0][0];
};
var nbrLayer = new ol.layer.Image({
  source: new ol.source.ImageCanvas({
    canvasFunction: canvasNbr,
    projection: 'EPSG:4326'
  })
});
map.addLayer(nbrLayer);

also i want to know how to do this  d3 map example in openlayers
here is the code using d3:
// radius of circles
var radius = d3
  .scaleSqrt()
  .domain([0, 164])
  .range([0, 15]);
// define colors
  var colorScale = d3.scaleSequential(d3.interpolateBlues).domain([0,165]);
// scale legend
const scaleLegend=[10,50,100,150,200]
svg.selectAll("circle")
    .data(regions.features)
  .enter().append("circle")
  .attr("fill",(d:any)=> colorScale(d.properties.nbr_cas))
  .attr("cx", function (d:any) {return projection([d.properties.long,d.properties.lat])[0]; })
  .attr("cy", function (d:any) { return projection([d.properties.long,d.properties.lat])[1]; })
  .attr("r",(d:any)=> radius(d.properties.nbr_cas));


text:
Q: Bibliography Style - Order of Appearance I am looking for a bibliography style with the following characteristics:

*

*Numbers references in the order they appear in text.

*Does not strike out repeated authors like (siam.bst).

*Very plain formatting on titles (i.e. articles, book, journal).

*Is able to handle a wide variety of reference types (i.e. journals, book chapters, websites, personal communications, etc.).

I have looked around and tried a handful of alternatives without finding one that fits for my purpose, which is a graduate thesis (i.e. a formal document, but without the space constraints of a journal article).
If there are alternative ways to manage this type of request using the biblatex that'd be fine too.

A: As Seamus has said, there are a lot of styles that cover more or less all of this. I'd probably start with the biblatex style numeric-comp, which seems to cover what you want. Perhaps you might try that and then ask specific questions on aspects of the formatting which you wish to adjust.
To get you started, a simple example using a couple of references from my own database:
\begin{filecontents}{example.bib}
@ARTICLE{Rauchfuss2008,
  author = {Barton, Bryan E. and Olsen, Matthew T. and Rauchfuss, Thomas B.},
  title = {Aza- and Oxadithiolates Are Probable Proton Relays in Functional
    Models for the [FeFe]-Hydrogenases},
  journaltitle = {J. Am. Chem. Soc.},
  year = {2008},
  volume = {130},
  pages = {16834-16835},
  number = {50},
  doi = {10.1021/ja8057666},
}

@BOOK{Clegg1998,
  title = {Crystal Structure Determination},
  publisher = {Oxford University Press},
  year = {1998},
  author = {Clegg, William},
  isbn = {978-0-19-855901-6},
  location = {Oxford, U.K.},
}
\end{filecontents}
\documentclass{article}
\usepackage[style=numeric-comp]{biblatex}
\bibliography{example}
\begin{document}
\nocite{*}
\printbibliography
\end{document}

The filecontents stuff here is simply to generate a .bib file, and I've used \nocite{*} to include all references rather than selected citations.

A: The previous posted examples work.. HOWEVER, by default the bibliography will be sorted by name and numbers will be assigned accordingly, which means that if your first three citations start with the letters C,A,B they will be assigned number 3,1,2.. and that is not what you. You can solve this by adding the sorting = none to your preamble. I think you also have  to define the style of citation and bibliography separately in this case, so your preamble could look something like this:
\usepackage[bibstyle= nature, citestyle=numeric-comp, sorting=none]{biblatex}


text:
Q: How can one declare unreachable code in Java? I have a complex case in a switch statement that (as it happens) always abruptly terminates (with a return, or break or ...).  I'd like to put something like lint's  /*UNREACHABLE*/ declaration so as to indicate to anyone reading the code that it doesn't fall through to the next case (a common bug in Java).  I'm looking for a more formal way to indicate this, ideally something that would cause a compiler warning or error if it was not unreachable.  Any ideas?
    switch (x) {
        case 1:
           if (...) {
             switch (.) {
                ...
             }
           } else {
             ...
           }
           /*UNREACHABLE*/
        case 2:
           ...
    }

The code is truly unreachable and the Java compiler knows it is, so I can't put any (normal) code there because it would be marked as unreachable code by the compiler.

A: If you are open to wild hacks, you can insert unused cases between the valid ones:
switch (x) {
    case 1:
       if (...) {
         switch (.) {
            ...
         }
       } else {
         ...
       }
    case -1:
       /*UNREACHABLE*/
       throw new RuntimeException("nope");

    case 2:
       ...
}

Personally I do not think I would use this, but it should work.


text:
Q: jQuery plugin that suggests/autocompletes within a textarea Is there a jQuery plugin that suggests/autocompletes within a textarea?
What I want is to have suggested words or autocompleted text proffered to the user in a textarea like the example image below:

A: Well there is the autocomplete plugin that does just that, and if you want to pull data from a database I recomment using the ajax API that is included in jQuery.
something like this
$('textarea').keyup(function(){
  $.post('ajax/test.php', function(data) {
   $('#example').autocomplete(data);

   });

});

Also remember this is just the basic structure to give you an idea.
P.S. I just found this it should fill all your needs.

A: If you reference jQueryUI (same website as jQuery) you can use the following for auto complete: http://jqueryui.com/demos/autocomplete/
It's a simple implementation as well :)
Hope that helps!

A: This might look like a hack, but you can try imitating to the user that he is typing in the textarea, whereas he would actually be typing in the textinput which is at the position for the next word in a textarea.Once the user selects a suggestion from autocomplete or hits enter or space inside this overlaid textinput, you can remove the text-input with the current word inside the textinput appended to the textarea.
For an autocomplete in text-input you can use on plugin from the plethora of plugins available for jquery.

A: you can try gcomplete uses the google api for autocomplete anything, with a little modification to the source code, you can change the behavior about the tag input[text].
i made changes for the plugin and autocomplete the last word, you can test in github.com/rkmax/gcomplete.
I'm working on:
- Autocomplete the current word.
- Determine the number of lines (visual) and Textarea the current cursor position to display the list of words right next to the cursor, thanks to SimpleCoder