text:
Q: What happens if @2x image is available but not regular resolution image? I'm wondering what will happen on a non-retina display device if only the @2x image is copied to the resources? Will it scale down the retina display image by 0.5 to accommodate the frame of the UIImageView?
I hope this isn't a silly question!

A: The high resolution @2x images are not automatically down-sampled on non-retina devices.
Apple did not implement such feature because non-retina devices generally don't have enough memory to load and down-sample many high resolution images during initialization, it might cause trouble in case too many images need to be initialized.
EDIT (Based on answer by WendiKidd)
Non-retina devices will however down-size and display the high resolution @2x images, but without down-samling them, which causes poor image quality.

A: I know for a fact that it will use the @2x images if no regular image is available, because I have tested it myself.  (Though I agree with David's comment--this is rather easy to test yourself.)  Now the image quality is decreased, because it's trying to resize an image that is much larger than the space you're trying to put it in.  But it absolutely will work.  Go give it a try and you'll see :)


text:
Q: Time Elapsed To Continue Even After Declaring In JS I have a code here in which the value of imgNumb is defined by timeElapsed variable. As the time goes by the value of imgNumb starting from 0 goes to max of 4 after which I would like it to start back from 0 again; like in a loop. The function which does most of the work is autoFade().
Problem: The problem is after I declare elapsedTime equal to delay it remains 4 only for rest of the duration and does not increase like before.
Please help me! if you can, I would really appreciate it! Thanks.
And here is the code below:
var a = document.getElementById("slidermain");
var b = a.getElementsByTagName("IMG");
var len = b.length;

var cusOpac = 0;
var delay = 4;
var imgNumb = 0;
var elem;
var now, before = new Date();

function autoFade(){
    var loop = setInterval(function(){
    now = new Date();
    var timeDiff = (now.getTime() - before.getTime());
    var elapsedTime = Math.floor(timeDiff/1000);
    var lendelay = len*delay;
    var currentFrame = Math.floor(elapsedTime/delay)-1;
    var imgNumb = currentFrame % 5;
    initFade(imgNumb);
    }, delay*1000);
}

function initFade(imgNumb){
    elem = b[imgNumb];
    startFadeEffect(elem);
}

function startFadeEffect(elem){
    opacSetting = cusOpac / 10;
    elem.style.opacity = opacSetting;
    elem.style.display = "block";
    cusOpac++;
    if(cusOpac > 10){
         cusOpac = 10;
    }
    var timer = setTimeout(function() { startFadeEffect(elem); }, 55);
    if(opacSetting == 1){
        clearTimeout(timer);
        cusOpac = 10;
        elem.style.opacity = 1;
        setTimeout(function() { endFadeEffect(elem); }, (delay*1000)/2);
    }
}

function endFadeEffect(elem){
    opacSetting = cusOpac / 10;
    elem.style.opacity = opacSetting;
    cusOpac--;
    if(cusOpac < 0){
        cusOpac = 0;
    }
    var timer = setTimeout(function() { endFadeEffect(elem); }, 55);
    if(opacSetting == 0){
        clearTimeout(timer);
        elem.style.opacity = 0;
        elem.style.display = "none";
        cusOpac = 0;
        return false;
    }
}

Please note I am looking for a javascript only solution!

A: Please format the code properly and try to reduce it to the absolute minimum necessary. In your case I believe you're asking to create a function f(elapsedTimeSeconds) -> imgNumb, that works like this:

*

*If delay * 0 <= elapsedTimeSeconds < delay * 1, imgNumb = 0

*If delay * 1 <= elapsedTimeSeconds < delay * 2, imgNumb = 0

*If delay * 2 <= elapsedTimeSeconds < delay * 3, imgNumb = 1

*If delay * 3 <= elapsedTimeSeconds < delay * 4, imgNumb = 2

*If delay * 4 <= elapsedTimeSeconds < delay * 5, imgNumb = 3

*If delay * 5 <= elapsedTimeSeconds < delay * 6, imgNumb = 4

*If delay * 6 <= elapsedTimeSeconds < delay * 7, imgNumb = 0

*If delay * 7 <= elapsedTimeSeconds < delay * 8, imgNumb = 1

...and so on.
You have already figured out that Math.floor(elapsedTimeSeconds/delay)-1 gives you what you need if delay*1 <= elapsedTimeSeconds < delay*6, but after that it continues to grow.
So what you need is a function that produces:

*

*0 -> 0

*...

*4 -> 4

*5 -> 0

*6 -> 1

*...

*9 -> 4

.. and so on. That's the modulo operation:
 var currentFrame = Math.floor(elapsedTimeSeconds/delay)-1;
 var imgNumb = currentFrame % 5;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get very specific url I want to get very specific string over my url to add as parameter in js:
 function cambiarContrasena(usuario, completado, fallo) {
            apiService.post('/api/usuario/cambiarContrasena?token=', usuario,
            completado,
            fallo);
        }

URL
http://localhost:55728/Cliente/#/cambiarContrasena.html?Token=e12009cf-d48d-42e7-ba43-83b5082019bb

I want to get only Guid afrer Token= like:
e12009cf-d48d-42e7-ba43-83b5082019bb

I try using:
   var url = (location.pathname + location.search).substr(1);
    function cambiarContrasena(usuario, completado, fallo) {
        apiService.post('/api/usuario/cambiarContrasena?token='+url, usuario,
        completado,
        fallo);
    }

But I get
http://localhost:55718/api/usuario/cambiarContrasena?token=Cliente/

I try too:
var guid = url.substr(url.indexOf('Token=') + 6);
        function cambiarContrasena(usuario, completado, fallo) {
            apiService.post('/api/usuario/cambiarContrasena?token='+guid, usuario,
            completado,
            fallo);
        }

But I get

Uncaught ReferenceError: url is not defined

What I need to do to get only parameters after Token= ?
I try as this question:
 function getParameterByName(name, url) {
            if (!url) {
                url = window.location.href;
            }
            name = name.replace(/[\[\]]/g, "\\$&");
            var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
                results = regex.exec(url);
            if (!results) return null;
            if (!results[2]) return '';
            return decodeURIComponent(results[2].replace(/\+/g, " "));
        }
        function cambiarContrasena(usuario, completado, fallo) {
            apiService.post('/api/usuario/cambiarContrasena?token='+getParameterByName, usuario,
            completado,
            fallo);
        }

But I get an error:

POST
  http://localhost:55718/api/usuario/cambiarContrasena?token=function%20getPa…%20%20var%20regex%20=%20new%20RegExp(%22[?&]%22%20+%20name%20+%20%22(=([^&
  400 (Bad Request)

A: just try this :
var url = window.location.hash.split('?Token=')[1];
var guid = url || '';


text:
Q: bower concat CSS problems Grunt novice here....what I am trying to do seems so simple, but I am at my wits end here.  I am trying to concat the JS from a few separate bower components and then do the same with the CSS.  Here is the relevant code from my grunt.file:
bower_concat: {
      all: {
        dest: 'builds/development/js/_bower.js',
        cssDest: 'builds/development/css/_bower.css'
    }
}

This is the last item in my config so does not need a comma after the final "}".
All the needed files are listed under "main" in their respective bower.json files.  For example:
"main": [
    "dist/owl.carousel.js",
    "dist/assets/owl.carousel.css",
    "dist/assets/owl.theme.css",
    "dist/assets/owl.transitions.css"
  ],

I am positive these paths and file names are correct. The JS concats fine.  The CSS does nothing.  If I remove the "dest:..." line from my gruntfile (in an attempt to concat ONLY the CSS) terminal gives me the error ":Warning: You should specify "dest" and/or "cssDest" properties in your Gruntfile".
I clearly am specifying this. Help!

A: Finally got it to work with this:
bower_concat: {
        all: {
            dest: {
                js: 'builds/development/js/_bower.js',
                css: 'builds/development/css/_bower.css'
            },

        },
    }

Essentially needed one more set of nested curly braces inside of "dest:".  For the record you DO NOT need to specify mainFiles if they are designated in the bower_components json.

A: Ah, easy. You need to specify the component or library and then its mainFiles in your Gruntfile under grunt-bower-concat. Don't worry about messing with the individual components' files.
bower_concat: {
    all: {
        dest: 'builds/development/js/_bower.js',
        cssDest: 'builds/development/css/_bower.css'
    }
    mainFiles: [
        owlcarousel: [
            "dist/owl.carousel.js",
            "dist/assets/owl.carousel.css",
            "dist/assets/owl.theme.css",
            "dist/assets/owl.transitions.css"
        ],
    ],
}

FYI My current bower-concat for owlcarousel looks like this so double-check your bower_components folder tree structure.
bower_concat: {
    all: {
        dest: 'builds/development/js/_bower.js',
        cssDest: 'builds/development/css/_bower.css'
    }
    mainFiles: [
        owlcarousel: [
            "owl-carousel/owl.carousel.js",
            "owl-carousel/owl.carousel.css",
            "owl-carousel/owl.theme.css",
            "owl-carousel/owl.transitions.css"
        ],    // (Version 1.3.2)
    ],
}


text:
Q: How to maintain the background color while adding an image in JavaFX? I am writing a JavaFX program to play chess. Currently, I am using the JavaFX Rectangle class and setting them up with dark and light colors. However, when I go to add the image, it clears the entire background even though I intentionally found images with clear backgrounds. Currently the code I am using to put the image on the Rectangles is:
rectangleArray[i][row].setFill(new ImagePattern(image));

where image is the image I want in this particular case. Do I need to use different JavaFX classes in order to be able to do this? Or am I simply using the wrong methods?

A: You can only set a single fill on a Rectangle. Setting the fill to a different value replaces the old fill instead of "adding" to it.
You should use a pane with a background instead and add a ImageView to it, e.g.:
@Override
public void start(Stage primaryStage) throws Exception {
    final double size = 50;

    ImageView pawn = new ImageView("https://upload.wikimedia.org/wikipedia/commons/9/93/Chess_tile_pd.png");
    pawn.setFitWidth(size);
    pawn.setFitHeight(size);

    final Background grey = new Background(new BackgroundFill(Color.GRAY, CornerRadii.EMPTY, Insets.EMPTY));
    final Background white = new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY));

    GridPane grid = new GridPane();
    ColumnConstraints columnConstraints = new ColumnConstraints(size);
    RowConstraints rowConstraints = new RowConstraints(size);
    for (int i = 0; i < 8; i++) {
        grid.getColumnConstraints().add(columnConstraints);
        grid.getRowConstraints().add(rowConstraints);

        for (int j = 0; j < 8; j++) {
            StackPane field = new StackPane();
            field.setBackground(((i + j) & 1) == 0 ? white : grey);
            grid.add(field, i, j);
            field.setOnMouseClicked(evt -> {
                if (pawn.getParent() != field) {
                    field.getChildren().add(pawn); // move pawn to this field on click
                }
            });
        }
    }

    ((Pane) grid.getChildren().get(0)).getChildren().add(pawn);

    Scene scene = new Scene(grid);

    primaryStage.setScene(scene);
    primaryStage.show();
}


text:
Q: Python 3.3: How to create a loop for a string I apologize for the title not being clear, anyways how do I create a loop that will put numbers into a string, what i mean is (this is from the assignment im doing):
Enter number of courses:
Enter grade for course no. 1:
Enter weight for course no. 1:
Enter grade for course no. 2
......
Enter grade for course no. 7
......
Enter weight for course no. 9
So how would i do something like this, i have to create an input statement which has numbers in order (1-infinity but limited by number of courses). Thank you if you need anymore information or for me to clarify let me know.

A: You can use string formatting:
noc = int(input('Enter number of courses: '))
for i in range(1, noc+1):
    grade = input('Enter grade for course no. {}: '.format(i))
    weight = input('Enter weight for course no. {}: '.format(i))
    #do something with grade and weight here.


text:
Q: Spring Boot Kafka newbie question on serializing / deserializing I'm new to Kafka (using Spring Boot 2.2.4) and I'm seeing samples where the KafkaTemplate's are String, String to just send a string. I was looking at sending Json objects and I'm seeing 2 different approaches there... some folks are using String, Object and some are using String, TheActualModelClass.
Is there pros/cons between the two? I'm kind of assuming the main diff is that the typed template would only be good for one model whereas the object could send any type to any topic? Anything beyond that?

A: While I might be late in answering it , but it might be useful for those who are looking for solution.
You can look at detailed solution at https://github.com/CODINGSAINT/kafka-stream-spring
Think if we have a custom java bean
public class Quote {
private String content;
private Set<String> tags;
private String author;
}

You are required to write Kafka Producer as well as Consumer configurations
 /**
 * Configurations for KafkaStreams
 * @param kafkaProperties Will take defaults from application YAML or Properties file with spring.kafka
 * @return kafkaConfiguration
 */
@Bean(name= KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_CONFIG_BEAN_NAME)
public KafkaStreamsConfiguration kafkaConfiguration(final KafkaProperties kafkaProperties){
    Map<String, Object> config = new HashMap<>();
    config.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaProperties.getBootstrapServers());
    config.put(StreamsConfig.APPLICATION_ID_CONFIG, kafkaProperties.getClientId());
    config.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
    config.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, QuoteSerde.class.getName() );
    config.put(StreamsConfig.DEFAULT_DESERIALIZATION_EXCEPTION_HANDLER_CLASS_CONFIG, LogAndContinueExceptionHandler.class);
    return new KafkaStreamsConfiguration(config);
}

/**
 * The Stream which delegates each incoming topic to respective destination topic
 * @param kStreamsBuilder
 * @return
 */
@Bean
public KStream<String,Quote> kStream(StreamsBuilder kStreamsBuilder){
    KStream<String,Quote> stream=kStreamsBuilder.stream(inputTopic);
    for(String topic:allTopics){
        stream.filter((s, quote) -> quote.getTags().contains(topic)).to(topic);
    }
    return stream;

}

/**
 * Kafka ConsumerFactory configurations
 * @return
 */
@Bean
public ConsumerFactory<String, Quote> consumerFactory() {
    Map<String, Object> props = new HashMap<>();
    props.put(
            ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,
            kafkaProperties.getBootstrapServers());
    props.put(
            ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,
            StringDeserializer.class);
    props.put(
            ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,
            BytesDeserializer.class);
    return new DefaultKafkaConsumerFactory<>(props);
}

/**
 * Required Configuration for POJO to JSON
 * @return ConcurrentKafkaListenerContainerFactory
 */
@Bean
public ConcurrentKafkaListenerContainerFactory<String, Quote>
kafkaListenerContainerFactory() {

    ConcurrentKafkaListenerContainerFactory<String, Quote> factory =
            new ConcurrentKafkaListenerContainerFactory<>();
    factory.setConsumerFactory(consumerFactory());
    factory.setMessageConverter(new StringJsonMessageConverter());
    return factory;
}

Then we require a Serializer
public class QuoteSerializer implements Serializer<Quote> {

    @Override
    public byte[] serialize(String s, Quote quote) {
        byte[] retVal = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            retVal = objectMapper.writeValueAsString(quote).getBytes();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return retVal;
    }
}

And a Deserializer
public class QuoteDeserializer implements Deserializer<Quote> {

    @Override
    public Quote deserialize(String s, byte[] bytes) {
        ObjectMapper mapper = new ObjectMapper();
        Quote quote = null;
        try {
            quote = mapper.readValue(bytes, Quote.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return quote;
    }
}

To make use of both Serializer and Deserializer a Serde
public class QuoteSerde implements Serde<Quote> {
    public QuoteSerde() {
    }

    @Override
    public Serializer<Quote> serializer() {
        return new QuoteSerializer();
    }

    @Override
    public Deserializer<Quote> deserializer() {
        return new QuoteDeserializer();
    }
}

Now our listener can listen
@Component
public class TopicConsumers {
    private static final Logger LOGGER = LoggerFactory.getLogger(TopicConsumers.class);

    @Value("#{'${kafka.topic.output}'.split(',')}")
    private List<String> allTopics;

    /**
     * For simplicity we are listening all topics at one listener
     */

    @KafkaListener(id = "allTopics", topics = "#{'${kafka.topic.output}'.split(',')}",
            containerFactory = "kafkaListenerContainerFactory")
    public void consume(@Payload Quote quote,
                        @Header(KafkaHeaders.RECEIVED_PARTITION_ID) int partition,
                        @Header(KafkaHeaders.RECEIVED_TOPIC) String incomingTopic,
                        @Header(KafkaHeaders.RECEIVED_TIMESTAMP) long ts
    ) {
        LOGGER.info("Incoming quote {}-> {}", incomingTopic, quote);
    }
}

Below is application.yml file
spring:
  kafka:
    listener:
      missing-topics-fatal: false
    client-id : quotes-app
    bootstrap-server:
      - localhost:9091
      - localhost:9001
      - localhost:9092
    template:
      default-topic: quotes
    producer:
      key-serializer: org.apache.kafka.common.serialization.StringSerializer
      value-serializer: com.codingsaint.learning.kafkastreamspring.QuoteSerializer
    consumer:
      properties:
        partition:
          assignment:
            strategy: org.apache.kafka.clients.consumer.RoundRobinAssignor
      group-id: random-consumer
      auto-offset-reset: earliest
      key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
      value-deserializer: com.codingsaint.learning.kafkastreamspring.QuoteDeserializer
---
kafka:
  topic:
    input: quotes
    output: business,education,faith,famous-quotes,friendship,future,happiness,inspirational,life,love,nature,politics,proverb,religion,science,success,technology

A: While using spring-kafka library i would suggest use the spring JsonSerializer and JsonDeserializer to avoid lot's of boiler plate code, you can find more information about Spring Serialization, Deserialization, and Message Conversion
Apache kafka only provides high-level API for serializing and deserializing, so user need a custom implementation for serializing or deserializing
org.apache.kafka.common.serialization.Serializer<T>
org.apache.kafka.common.serialization.Deserializer<T>

Apache Kafka provides a high-level API for serializing and deserializing record values as well as their keys. It is present with the org.apache.kafka.common.serialization.Serializer and org.apache.kafka.common.serialization.Deserializer abstractions with some built-in implementations. Meanwhile, we can specify serializer and deserializer classes by using Producer or Consumer configuration properties.

But Spring-kafka provides JsonSerializer and JsonDeserializer based on ObjectMapper

Spring for Apache Kafka also provides JsonSerializer and JsonDeserializer implementations that are based on the Jackson JSON object mapper. The JsonSerializer allows writing any Java object as a JSON byte[]. The JsonDeserializer requires an additional Class targetType argument to allow the deserialization of a consumed byte[] to the proper target object.

And it also provides deserializing different type of JSON objects to respective java POJO classes using Type Mappings and @KafkaListener on a Class

A: JSON is just a string. At the end of the code sequence, your model object would be serialized to bytes anyway
Which one you prefer depends how much Kafka serializer code you want to abstract away


text:
Q: Combine Multiple Dataframes in R by Average (Mixed datatypes) I've done some research about this (here and here), but I haven't found what I actually want to achieve. The closest I've found to what I'm looking for is here, but the code doesn't seem to work or do what I desire. Besides, I found out that rbindlist has been deprecated in favour of bind_rows, but I haven't been able to use bind_rows to achieve what I want.
I have a list of 30 dataframes each with the same number of rows and columns, as well as the same column datatypes (though each column could be either continuous and categorical). I want to merge them into a single dataframe of the same number of rows and columns, but with each cell as a mean/median/majority voting of the corresponding 30 cells from the list of dataframes, for continuous, integer, and categorical columns, respectively. Here's an example with three dataframes:
df 1:

A       B       C
2.3     5       3
12      3       1
0.4     13      2

df_2:

A       B       C
4.3     23      1
1       7       2
0.4     10      2

df_3:

A       B       C
1.3      3      3
2.2      4      2
12.4     10     1

And the resulting dataframe would be something like:
df_result:

A       B        C
2.63     5       3
5.06     4       2
4.4     10       2

Any directions to more appropriate ways of combining each of the datatypes would also be highly appreciated.

A: Put a ROW ID on your tables
df_1 <- read_table("A       B       C
2.3     5       3
12      3       1
0.4     13      2") %>%
  rowid_to_column("ROW")

df_2 <- read_table("A       B       C
4.3     23      1
1       7       2
0.4     10      2") %>%
  rowid_to_column("ROW")

df_3 <- read_table("A       B       C
1.3      3      3
2.2      4      2
12.4     10     1") %>%
  rowid_to_column("ROW")

Bind them together in an ensemble
ensamb <- bind_rows(df_1, df_2, df_3)

group_by row and then summarize each one by its own method
ensamb %>%
  group_by(ROW) %>%
  summarise(A = mean(A), B = median(B),
            C = C[which.max(C)])

# A tibble: 3 x 4
    ROW     A     B     C
  <int> <dbl> <dbl> <dbl>
1     1  2.63     5     3
2     2  5.07     4     2
3     3  4.4     10     2

A: You can put all the dataframes in a list :
list_df <- mget(ls(pattern = 'df_\\d+'))

Then calculate the stats for each column separately.
data.frame(A = Reduce(`+`, lapply(list_df, `[[`, 1))/length(list_df),
           B = apply(do.call(rbind, lapply(list_df, `[[`, 2)), 2, median),
           C = apply(do.call(rbind, lapply(list_df, `[[`, 3)), 2, Mode),
           row.names = NULL)

#         A  B C
#1 2.633333  5 3
#2 5.066667  4 2
#3 4.400000 10 2

where Mode function is taken from here :
Mode <- function(x) {
   ux <- unique(x)
   ux[which.max(tabulate(match(x, ux)))]
}


text:
Q: Expanding text format in VI The following code is taken from the superfish module for websites:

(function($){$.fn.hoverIntent=function(f,g){var
  cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var
  cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY;};var
  compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))

And once upon a time when editing this kind of file, I once accidentally hit a shortcut key that restructured the code:
(function($){$.fn.hoverIntent=function(f,g){
 var cfg={sensitivity:7,interval:100,timeout:0};
 cfg=$.extend(cfg,g?{over:f,out:g}:f);
 var cX,cY,pX,pY;
 var track=function(ev){cX=ev.pageX;cY=ev.pageY;};
 var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);
 if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity
  {$(ob).unbind("mousemove",track)
  etc..........

I want to know what that shortcut is o.0
It's like the formatting already exists but VI didn't render it?

A: The vim command to format source code is gg=G, it always worked for me with java or c source code; it does not work with your snippet probably because it only works with syntactically correct files.


text:
Q: cant seem to see images on node.js server What it looks like when the server is running on localhost:300 :

What the HTML looks like itself:

I am very new to this and trying to make a video game website for people to purchase things. I wanted to have pictures of the game so that it can make the webpage look nicer but I can't seem to see the pictures on the server. I can see them on the HTML file when opened in chrome but not on localhost. I have done a lot of research on this and can't seem to figure it out. Is there any chance I can get some help on being able to get the images to show on the server?
HTML Code
<!DOCTYPE HTML>

<title>Jonathan's Database Game Store</title>
<link rel="stylesheet" type="text/css" href="nav.css">

Jonathan's Database Game Store

Login

PC Games

Xbox Games

Playstation Gmaes

Raingbow Six Seige

server.js Code
const http = require('http')
const fs = require('fs')
const port = 3000

const server = http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/html'})
fs.readFile('home.html', function(error, data) {
    if (error) {
        res.writeHead(404)
        res.write('Error: File Not Found')
    } else {
        res.write(data)
    }
    res.end()
 })

})

server.listen(port, function(error){
if (error) {
    console.log('something went wrong', error)
} else {
    console.log('server is listening on port ' + port)
}

})

A: The problem
Using NodeJS' HTTP module to make a HTTP server is pretty tedious, what the problem is, is that you aren't hosting the images on your HTTP server.
The fix
I would recommend that you use Express which makes everything way easier.
Install it with npm i express in console then you can use this code for your HTTP server
const express = require("express")
const app = express()

const server = app.listen(3000, () => { // create a HTTP server on port 3000
    console.log(`Express running → PORT ${server.address().port}`)
});

app.use(express.static(__dirname, { // host the whole directory
        extensions: ["html", "htm", "gif", "png"],
    }))

app.get("/", (req, res) => {
    return res.sendFile("./PC.html")
})

app.get("*", (req, res) => {
    return res.sendStatus(404)
})

A: I have figured out why Mushroom idiot's previous code did not work.  was missing the __dirname + in the following code res.sendFile(__dirname + "/PC.html"). Here is the final code that works with the HTML and images.
const express = require("express")
const app = express()

const server = app.listen(3000, () => { // create a HTTP server on
port 3000
console.log(`Express running → PORT ${server.address().port}`)
});

app.use(express.static(__dirname, { // host the whole directory
    extensions: ["html", "htm", "gif", "png"],
}))

app.get("/", (req, res) => {
res.sendFile(__dirname + "/PC.html")
})

app.get("*", (req, res) => {
return res.sendStatus(404)
})


text:
Q: Compare two data frames and conditionally extract the value of another column I have two tables, quotes and trades. I need to extract the BidPrice of the quote where the timestamp of the quote is less than the timestamp of the trade. How do I create a loop or function that will compare the first quote timestamp and then proceed to the need quote timestamp?
I've tried for loops, nested for loops, creating my own function but the result is either the first BidPrice of the data frame or condenses all the BidPrices into one vector.
for(i in 1:length(trades_reduced_f100[,3])){
  #outer loop is running. It is going up to 100
  for(j in 1:length(quotes_reduced_f100[,3])){
    while(quotes_reduced_f100$Timestamp[j] <= trades_reduced_f100$Timestamp){
      trades_reduced_f100$BidPrice[i] <- subset(quotes_reduced_f100)$BidPrice
      # print(trades_reduced_f100$BidPrice[i])
    break
    }

  }
}

I expect the output to be a different BidPrice as the loop runs through the quote timestamp, but the output is just the first BidPrice for all. That means that the loop is getting stuck at the first quote.
UPDATE
I was able to solve using two nested for loops as shown in the example.
Code:
for(i in 1:length(trades_full[,3])){
  for(j in 1:length(quotes[,3])){
    if(quotes$Timestamp[j] <= trades_full$Timestamp[i] &
       quotes$Timestamp[j+1] > trades_full$Timestamp[i]){
         trades_full$BidPrice[i] <- quotes$BidPrice[j]
    break
  }
 }
}

However, run over the large data set the processing speed is very slow. What are some alternate methods that perhaps won't take as much time/are more efficient?


text:
Q: How to compute tangent of a discretized curve I have a discretized curve defined by a 2D matrix $M$ where $M(i,j)=1$ means the point $(i,j)$ is on the curve. For each of these points, I want to calculate its tangent vector by fitting a polynomial thru the neighbouring points using Taylor series expansion. Could someone please let me know what is the Taylor formula in this case? Thank you.
EDIT:

*

*I want to consider the 8 neighbors (3x3 matrix).

*The curve is taken from a photo so the case of all-1 submatrix would be rare. But I'm curious how one would approach that case.

*Cubic spline sounds great but doesn't it mean that I have to find ${a,b,c,d}$ for $y = ax^3+bx^2+cx+d$ and then calculate derivatives? Taylor expansion seems to give me that in one go.

I'm grateful for any suggestion.

A: This is, to me, very poorly posed.

*

*What do you mean be "neighbors"? In a matrix, each internal point has four neighbors, or eight if you can go diagonally.

*What do you want to do if all nine points in a 3x3 subarray are 1?

*If you are going to get a tangent vector, this seems to imply that there is some order to the points where the array has a 1. What is this order?

*How is this set of points obtained? Methods used might be very different if the points are gotten sequentially or by scanning a drawing of a curve.

*If the array entries are gotten by scanning an image of some kind, can the points look like a line with thickness greater than one?
In the past, when I have been given a series of points and required to get tangents at each point, if the points were reasonably smooth, I took the line through the preceding and following points to get the slope of the tangent. If the points were not smooth, I usually took some sort of moving average.


text:
Q: Drawing 3D graphics on top of an imported picture with asymptote I am trying to draw stuff on top of an imported picture with asymptote, following this nice answer. Here is my MWE
     \documentclass{article}
     \usepackage[inline]{asymptote}
     \begin{document}
     \begin{asy}
     size(10cm);
     import graph3;
     import three;
     import labelpath3;
     import graph;
     import math;

     // it is not important which precise picture gets imported
     defaultpen(fontsize(10pt));
     real sc=2;
     unitsize(sc*1bp);
     real wd=120*sc;
     real ht=80*sc;
     label(
       shift(wd/2,ht/2)*
       graphic("earth.pdf"
       ,"width="+string(wd)+"bp"
       +",height="+string(ht)+"bp"
       +",scale="+string(sc)
       ),(0,0)
     );
     layer();

     int ngrid=10;
     int n=(int)(wd/ngrid/sc);
     int m=(int)(ht/ngrid/sc);
     add(scale(ngrid)*grid(n,m,yellow));

     xaxis( 0,wd/sc,RightTicks(Step=ngrid));
     yaxis(0,ht/sc,LeftTicks(Step=ngrid));

     draw(((0,0)--(wd,ht)/sc),blue+2pt);

     triple f(real t) {
       return (3*cos(0.125*2pi*t)+0.08*cos(2pi*t), 3*sin(0.125*2pi*t),0+ 0.08*sin(2pi*t));
     }

     path3 helix = graph(f, 0, 8, n=500, operator..);

     surface helixtube = tube(helix, width=0.4).s;

     draw(helixtube, surfacepen=material(blue+opacity(0.3), emissivepen=0.2*white));

     real R=300;
     real a=100;

     triple f(pair t) {
       return ((R+a*cos(t.y))*cos(t.x),(R+a*cos(t.y))*sin(t.x),a*sin(t.y));
     }

     surface s=surface(f,(radians(90),0),(radians(345),2pi),8,8,Spline);
     draw(s,gray,render(compression=Low,merge=true));

     // ---

     draw(((0,0)--(wd,ht)/sc),blue+2pt);

     \end{asy}
     \end{document}
     \endinput

It produces

As one can see, the 2-dimensional stuff, i.e. the grid and the blue line, really appears in front of the picture. However, the 3-dimensional stuff, i.e. the torus, does not. (No, of course I am not expecting asymptote to recognize that the imported stuff is also 3-dimensional.) I'd like to see the 3D stuff also in front of the imported picture. Is that possible?
(Of course, in the best of all worlds, somebody might figure out how to draw a 3D earth with e.g. Mathematicas GeoData in asymptote. Here I just want to put the 3D stuff in front of the background picture. It would be great if opacity would also work...)

A: 5th Approach: Wrapping a world map sphere with surfaces
A combination of the 2nd and 4th approaches.
Output:

Code:
\documentclass{standalone}
    \usepackage[inline]{asymptote}
        \begin{document}
            \begin{asy}
                import math;
                import three;
                import graph3;
                size(500);

                //file fin=input("world.dat"); //1317 limit for the for loop
                file fin=input("world_110m.dat"); //5254 limit for the for loop

                real zenith  = pi/12.0;
                real azimuth = pi/12.0;
                currentprojection = perspective(cos(azimuth)*cos(zenith),
                                                sin(azimuth)*cos(zenith),
                                                sin(zenith));
                //------------------------------------------------- TUBE
                    defaultpen(0.5mm);
                    pen darkgreen=rgb(0,138/255,122/255);

                    real R=3;
                    real a=0.75;

                    triple f(pair t) {
                    return ((R+a*cos(t.y))*cos(t.x),(R+a*cos(t.y))*sin(t.x),a*sin(t.y));
                    }

                    surface s=surface(f,(radians(90),0),(radians(345),2pi),8,8,Spline);
                    draw(s,surfacepen=material(gray+opacity(0.9), emissivepen=0.2*white),render(compression=Low,merge=true));

                //-------------------------------------------------- RING
                    triple f(real t) {
                    return (3*cos(0.125*2pi*t)+0.08*cos(2pi*t), 3*sin(0.125*2pi*t),0+ 0.08*sin(2pi*t));
                    }
                    path3 helix = graph(f, 0, 8, n=500, operator..);

                    surface helixtube = tube(helix, width=0.5).s;

                    draw(helixtube, red);

                  //--------------------------------------------------- PLANET EARTH

                    real r = 1.25;
                    real ar = 1.2;

                    path3 myarc = Arc(c=O,normal=X, v1=-Z*r, v2=Z*r, n=24);
                    surface sphere = surface(myarc, angle1=0, angle2=360, c=O, axis=Z, n=24);
                    draw(sphere, surfacepen=material(royalblue+opacity(0.9),ambientpen=white));

                    real[][] a=fin.dimension(0,2);
                    a=transpose(a);

                    for(int i=0; i <=5254; ++i){
                    real u=a[0][i];
                    real v=a[1][i];
                    real U=a[0][i+1];
                    real V=a[1][i+1];
                    if (u==360 & v==360 | U==360 & V==360){}
                        else{
                            real x1=r*Cos(v)*Cos(u);
                            real y1=r*Cos(v)*Sin(u);
                            real z1=r*Sin(v);
                            real x2=r*Cos(V)*Cos(U);
                            real y2=r*Cos(V)*Sin(U);
                            real z2=r*Sin(V);
                            draw((x1,y1,z1)--(x2,y2,z2), darkolive+linewidth(0.2mm));
                            }
                    }
            \end{asy}
\end{document}

4th Approach: A world map sphere
Answer to:

Of course, in the best of all worlds, somebody might figure out how to draw a 3D earth with e.g. Mathematicas GeoData in asymptote. Here I just want to put the 3D stuff in front of the background picture. It would be great if opacity would also work.

The package pst-map3d (pst-geo) offers the possibility to plot a 3D world map. The data set is based on the CIA World DataBank II. Gnuplot contains also a world.dat file with a low resolution world map data. Natural Earth is a public domain map dataset available at 1:10m, 1:50m, and 1:110 million scales. Based on the approaches Plotting the world and Plotting the world revisited given by Hagen Wierstorf on his website Gnuplotting, its implementation in asymptote or tikz is possible.
Joining pair of points with draw: draw((x1,y1,z1)--(x2,y2,z2), darkolive);
The coastlines are drawn joining a pair of points.
guide3 and path3 in combination with draw and surface is used to fill the surface with a color.
     guide3 g;
     g=g--(x1,y1,z1);
     path3 s=g;
     draw(surface(s--cycle),heavygreen);

Unfortunately, it does not work as expected. Any other ideas how to fill with a color the right surfaces?
Output for modified ´world_110m.dat´ with fill color (small scale data):

Output for modified ´world.dat´ with fill color (low resolution data):

Output for modified ´world_110m.dat´ without fill color (small scale data):

Output for modified ´world.dat´ without fill color (low resolution data):

Code:
\documentclass{standalone}
    \usepackage[inline]{asymptote}
        \begin{document}
            \begin{asy}
                import solids;
                import three;
                import graph3;
                size(6cm);

                //file fin=input("world.dat"); //1317 limit for the for loop
                file fin=input("world_110m.dat"); //5254 limit for the for loop

                real zenith  = pi/12.0;
                real azimuth = pi/12.0;
                currentprojection = perspective(cos(azimuth)*cos(zenith),
                                                sin(azimuth)*cos(zenith),
                                                sin(zenith));
                real r = 1;
                real ar = 1.2;

                path3 myarc = Arc(c=O,normal=X, v1=-Z*r, v2=Z*r, n=24);
                surface sphere = surface(myarc, angle1=0, angle2=360, c=O, axis=Z, n=24);
                draw(sphere, surfacepen=material(royalblue+opacity(0.7),ambientpen=white));

                real[][] a=fin.dimension(0,2);
                a=transpose(a);
                guide3 g;
                for(int i=0; i <=5254; ++i){
                real u=a[0][i];
                real v=a[1][i];
                real U=a[0][i+1];
                real V=a[1][i+1];
                if (u==360 & v==360 | U==360 & V==360){}
                    else{
                        real x1=r*Cos(v)*Cos(u);
                        real y1=r*Cos(v)*Sin(u);
                        real z1=r*Sin(v);
                        real x2=r*Cos(V)*Cos(U);
                        real y2=r*Cos(V)*Sin(U);
                        real z2=r*Sin(V);
                        draw((x1,y1,z1)--(x2,y2,z2), darkolive);
                        g=g--(x1,y1,z1);
                        }
                }
               path3 s=g;
               //draw(surface(s--cycle),heavygreen);
            \end{asy}
\end{document}

Building a guide3 / path3 with single points: draw(p3,black)
The coastlines as well as the colored filling are drawn with guide3, paht3 an subpath in combination with draw and surface.
Unfortunately, it compiles only for the first 202 pair of points (world_110m.dat). For a higher number of points brings an error (the next pair of points (203)  is a new segment (360 360)). I have not found the error yet. Any ideas?
Output for modified world_110m.dat with fill color (small scale data):

Code:
\documentclass{standalone}
    \usepackage[inline]{asymptote}
        \begin{document}
            \begin{asy}
                import solids;
                import three;
                import graph3;
                size(6cm);
                //file fin=input("world.dat"); //1317 limit for the for loop
                file fin=input("world_110m.dat"); //5254 limit for the for loop

                real zenith  = pi/12.0;
                real azimuth = pi/12.0;
                currentprojection = perspective(cos(azimuth)*cos(zenith),
                                                sin(azimuth)*cos(zenith),
                                                sin(zenith));
                real r = 1;
                real ar = 1.2;

                path3 myarc = Arc(c=O,normal=X, v1=-Z*r, v2=Z*r, n=24);
                surface sphere = surface(myarc, angle1=0, angle2=360, c=O, axis=Z, n=24);
                draw(sphere, surfacepen=material(royalblue+opacity(0.5),ambientpen=white));

                real[][] a=fin.dimension(0,2);
                a=transpose(a);
                int j=0;
                guide3 g;
                for(int i=0; i<=202; ++i){
                    real u=a[0][i];
                    real v=a[1][i];
                    if (u!=360){
                            real x=r*Cos(v)*Cos(u);
                            real y=r*Cos(v)*Sin(u);
                            real z=r*Sin(v);
                            g=g--(x,y,z);
                            ++j;
                        } else{
                            int n0=i-1-j;
                            int nn=i-1;
                            path3 s=g;
                            path3 sp3=subpath(s,n0,nn);
                            draw(sp3--cycle,darkolive);
                            draw(surface(sp3--cycle),heavygreen);
                            j=0;
                        }
                    }

            \end{asy}
\end{document}

Joining pair of points with Arc: Arc(O,r,one.y,one.x,two.y,two.x);
An other solution could be to implement the approach from Fill enclosed region on sphere by Frenzy Li.
Output for modified world_110m.dat without fill color (small scale data):
(only for a few points (70) since Overleaf (free version) returns the error:  Timed out. Sorry, your compile took too long to run and timed out. This may be due to a large number of high-res images, or complicated diagrams).

Code:
\documentclass{standalone}
    \usepackage[inline]{asymptote}
        \begin{document}
            \begin{asy}
                import solids;
                import three;
                import graph3;
                size(6cm);

                //file fin=input("world.dat"); //1317 limit for the for loop
                //file fin=input("world_110m.dat"); //5254 limit for the for loop
                real zenith  = pi/12.0;
                real azimuth = pi/12.0;
                currentprojection = perspective(cos(azimuth)*cos(zenith),
                                                sin(azimuth)*cos(zenith),
                                                sin(zenith));
                real r = 1;
                real ar = 1.2;

                path3 myarc = Arc(c=O,normal=X, v1=-Z*r, v2=Z*r, n=24);
                surface sphere = surface(myarc, angle1=0, angle2=360, c=O, axis=Z, n=24);
                draw(sphere, surfacepen=material(royalblue+opacity(0.7),ambientpen=white));

                real[][] a=fin.dimension(0,2);
                a=transpose(a);

                pair[] region = new pair[];
                for(int i=0; i <=60; ++i){
                region[i]=(a[0][i],a[1][i]);}

                for(int i=1; i<region.length; ++i){
                  pair one, two;
                  if (region[i].x==360 & region[i].y==360 | region[i-1].x==360 & region[i-1].y==360){} else{
                  if(region[i-1].y < region[i].y){
                    one = (region[i]  .x, 90 - region[i]  .y);
                    two = (region[i-1].x, 90 - region[i-1].y);
                  }else if(region[i-1].y > region[i].y){
                    one = (region[i-1].x, 90 - region[i-1].y);
                    two = (region[i]  .x, 90 - region[i]  .y);
                  }else if(region[i-1].x > region[i].x){
                    one = (region[i]  .x, 90 - region[i]  .y);
                    two = (region[i-1].x, 90 - region[i-1].y);
                  }else{
                    one = (region[i-1].x, 90 - region[i-1].y);
                    two = (region[i]  .x, 90 - region[i]  .y);
                  }
                  path3 temp = Arc(O,r,one.y,one.x,two.y,two.x);
                  draw(temp,darkolive+linewidth(.3pt));}
                  }
            \end{asy}
\end{document}

The original data contains blank lines to define the segment limits. These lines have been replaced with the pair 360 360. For instance, the first lines of world_110m.dat:
    -163.71289567772871 -78.595667413241543
    -163.105800951163786 -78.223338718578589
    -161.245113491846439 -78.380176690584435
    -160.24620805564453 -78.693645928866943
    -159.482404548154477 -79.046337579258974
    -159.208183560197654 -79.497007745276406
    -161.127601284814716 -79.634208673011329
    -162.439846768218416 -79.281465346186991
    -163.027407803377002 -78.928773695794959
    -163.06660437727038 -78.869965915846805
    -163.71289567772871 -78.595667413241543

    -6.197884894220991 53.867565009163364
    -6.032985398777611 53.153190009160497
    -6.788856573910849 52.260117906292336

Modified world_110m.dat:
    -163.71289567772871 -78.595667413241543
    -163.105800951163786 -78.223338718578589
    -161.245113491846439 -78.380176690584435
    -160.24620805564453 -78.693645928866943
    -159.482404548154477 -79.046337579258974
    -159.208183560197654 -79.497007745276406
    -161.127601284814716 -79.634208673011329
    -162.439846768218416 -79.281465346186991
    -163.027407803377002 -78.928773695794959
    -163.06660437727038 -78.869965915846805
    -163.71289567772871 -78.595667413241543
     360  360
    -6.197884894220991 53.867565009163364
    -6.032985398777611 53.153190009160497
    -6.788856573910849 52.260117906292336

In this way, with a conditional expression it is possible to know when a new segment starts.
3rd Attempt: Wrapping a label with surfaces
I have tried a combination of the 1st and 2nd approaches. That is to say, trying to replace the planet by the imported picture.
There is a possibility to draw a label in 3D by using the base modules three and labelpath3. For example:
    path3 g=(0,-5,0)..(0,5,0);
    string world="earth";
    draw(labelpath(world,subpath(g,0,reltime(g,0.95)),angle=-90),orange);

gives the following output:

Since (p. 9 of the documentation):

The  function string graphic(string name, string options="") returns  a  string that can be used to include an encapsulated PostScript (EPS) file.

I thought that defining
    real sc=2;
    unitsize(sc*1bp);
    real wd=100*sc;
    real ht=80*sc;
    string world2=graphic("earth.pdf","width="+string(wd)+"bp"+",height="+string(ht)+"bp"+",scale="+string(sc));
    draw(labelpath(world2,subpath(g,0,reltime(g,0.95)),angle=-90));

could work, but unfortunately it did not.
Code:
\documentclass{standalone}
    \usepackage[inline]{asymptote}
        \begin{document}
            \begin{asy}
                import graph3;
                import math;
                import three;
                import labelpath3;

                size(500);
                currentprojection=perspective(
                    camera=(25,5,5),
                    up=Z,
                    target=(-0.6,0.7,-0.6),
                    zoom=1,
                    autoadjust=true);
                    //------------------------------------------------- TUBE
                    defaultpen(0.5mm);
                    pen darkgreen=rgb(0,138/255,122/255);

                    real R=3;
                    real a=0.75;

                    triple f(pair t) {
                    return ((R+a*cos(t.y))*cos(t.x),(R+a*cos(t.y))*sin(t.x),a*sin(t.y));
                    }

                    surface s=surface(f,(radians(90),0),(radians(345),2pi),8,8,Spline);
                    draw(s,surfacepen=material(gray+opacity(0.9), emissivepen=0.2*white),render(compression=Low,merge=true));
                    //-------------------------------------------------- RING
                    triple f(real t) {
                    return (3*cos(0.125*2pi*t)+0.08*cos(2pi*t), 3*sin(0.125*2pi*t),0+ 0.08*sin(2pi*t));
                    }
                    path3 helix = graph(f, 0, 8, n=500, operator..);

                    surface helixtube = tube(helix, width=0.5).s;

                    draw(helixtube, red);

                    //--------------------------------------------------- PLANET
                    material m=
                    //  diffusepen, ambientpen, emissivepen,  specularpen
                    material( green,      yellow,     blue,      black);
                    //draw(surface(sphere(1.2)), m);
                    //--------------------------------------------------- LABEL TEXT
                    path3 g=(0,-5,0)..(0,5,0);
                    string world="earth";
                    draw(labelpath(world,subpath(g,0,reltime(g,0.95)),angle=-90),orange);
                    //--------------------------------------------------- LABEL PICTURE
                    real sc=2;
                    unitsize(sc*1bp);
                    real wd=100*sc;
                    real ht=80*sc;
                    string world2=graphic("earth.pdf","width="+string(wd)+"bp"+",height="+string(ht)+"bp"+",scale="+string(sc));
                    draw(labelpath(world2,subpath(g,0,reltime(g,0.95)),angle=-90));
            \end{asy}
\end{document}

2nd Approach: Wrapping a sphere with surfaces
Answer to:

However, I want to create an output i which the tube wraps around the planet.

Output:

Code:
\documentclass{standalone}
    \usepackage[inline]{asymptote}
        \begin{document}
            \begin{asy}
                import graph3;
                import solids;
                import interpolate;
                import math;
                import three;
                import labelpath3;

                size(500);
                currentprojection=perspective(
                    camera=(25,5,5),
                    up=Z,
                    target=(-0.6,0.7,-0.6),
                    zoom=1,
                    autoadjust=true);
                    //------------------------------------------------- TUBE
                    defaultpen(0.5mm);
                    pen darkgreen=rgb(0,138/255,122/255);

                    real R=3;
                    real a=0.75;

                    triple f(pair t) {
                    return ((R+a*cos(t.y))*cos(t.x),(R+a*cos(t.y))*sin(t.x),a*sin(t.y));
                    }

                    surface s=surface(f,(radians(90),0),(radians(345),2pi),8,8,Spline);
                    draw(s,gray,render(compression=Low,merge=true));
                    //-------------------------------------------------- RING

                    triple f(real t) {
                    return (3*cos(0.125*2pi*t)+0.08*cos(2pi*t), 3*sin(0.125*2pi*t),0+ 0.08*sin(2pi*t));
                    }
                    path3 helix = graph(f, 0, 8, n=500, operator..);

                    surface helixtube = tube(helix, width=0.5).s;

                    draw(helixtube, surfacepen=material(red+opacity(0.9), emissivepen=0.2*white));

                    //--------------------------------------------------- PLANET
                    material m=
                    //  diffusepen, ambientpen, emissivepen,  specularpen
                    material( green,      yellow,     blue,      black);
                    draw(surface(sphere(1.2)), m);
            \end{asy}
\end{document}

However, the background is not transparent ...
1st Approach: Overlay of saved pictures in Asymptote
Answer to:

I'd like to see the 3D stuff also in front of the imported picture. Is that possible?

Output:

Firstly compile the code pdflatex asy pdflatex to save the pictures and then compile it again by commenting the shipout("");´s:
 //shipout("D2FIG");
 //shipout("D3FIG1");
 //shipout("D3FIG2");

Code:
\documentclass[12pt]{article}
\usepackage[inline]{asymptote}

\begin{document}
    \begin{asy}
        size(10cm);
        import graph3;
        import three;
        import labelpath3;
        import graph;
        import math;
        // ----------------------------------------------------2D
            // it is not important which precise picture gets imported
            defaultpen(fontsize(10pt));
            real sc=2;
            unitsize(sc*1bp);
            real wd=100*sc;
            real ht=80*sc;
            label(
            shift(wd/2,ht/2)*
            graphic("earth.pdf"
            ,"width="+string(wd)+"bp"
            +",height="+string(ht)+"bp"
            +",scale="+string(sc)
            ),(0,0)
            );
            layer();

            int ngrid=10;
            int n=(int)(wd/ngrid/sc);
            int m=(int)(ht/ngrid/sc);
            add(scale(ngrid)*grid(n,m,green));

            xaxis(0,wd/sc,RightTicks(Step=ngrid));
            yaxis(0,ht/sc,LeftTicks(Step=ngrid));

            draw(((0,0)--(wd,ht)/sc),blue+2pt);
            shipout("D2FIG");

            picture D2FIG = currentpicture;
        // ----------------------------------------------------3D1
            currentpicture = new picture;
            size(10cm);
            import graph3;
            import three;
            import labelpath3;
            import graph;
            import math;
            triple f(real t) {
            return (3*cos(0.125*2pi*t)+0.08*cos(2pi*t), 3*sin(0.125*2pi*t),0+ 0.08*sin(2pi*t));
            }

            path3 helix = graph(f, 0, 8, n=500, operator..);

            surface helixtube = tube(helix, width=0.4).s;

            draw(helixtube, surfacepen=material(blue+opacity(0.3), emissivepen=0.2*white));
            shipout("D3FIG1");

            picture D3FIG1 = currentpicture;
        // ----------------------------------------------------3D2
            currentpicture = new picture;
            size(10cm);
            import graph3;
            import three;
            import labelpath3;
            import graph;
            import math;
            real R=300;
            real a=100;

            triple f(pair t) {
            return ((R+a*cos(t.y))*cos(t.x),(R+a*cos(t.y))*sin(t.x),a*sin(t.y));
            }

            surface s=surface(f,(radians(90),0),(radians(345),2pi),8,8,Spline);
            draw(s,gray,render(compression=Low,merge=true));
            shipout("D3FIG2");

            picture D3FIG2 = currentpicture;
        // ----------------------------------------------------Merge/Overlay
            currentpicture = new picture;
            size(10cm);
            add(D2FIG);
            label(graphic("D3FIG1+0_0.pdf"),(0,0));
            label(graphic("D3FIG2+0_0.pdf"),(25,-25));
    \end{asy}
\end{document}

I have taken the earth picture from MATLAB script for 3D visualizing geodata on a rotating globe

A: Yes, it is possible to draw 3D graphics in front of an imported picture. That doesn't work with layering (2D) but by moving the objects directly toward (or away from) the camera (3D).
There are several ways to do this in Asymptote:

*

*label position parameter

*currentprojection.camera

*triple cameradirection

*triple towardcamera


text:
Q: Parameterize the node texts in tikzset I have the following code which draws a linked list
Initially it printed the node texts as leaning against the right edges of the nodes. Putting \hspace*{-3pt} in front each text solves this horizontal misalignment problem.

\documentclass[a4paper,openany,14pt]{extbook}

\usepackage{tikz}
\usetikzlibrary{shapes.multipart,chains,positioning,arrows,calc,arrows.meta}

\newcommand{\columnratio}{0.62} % to be able to fit the TikZ drawing
\newcommand{\columnseper}{12pt} % inside small sections

\begin{document}

\pgfmathsetlengthmacro{\ourwidth}{\columnratio * \linewidth - \columnseper}

\tikzset{thebox/.style = {
    % args={2}, % Nope
    rectangle split, rectangle split horizontal,
    rectangle split parts=2,
    very thick, draw=black!100,
    align=center,font=\footnotesize,
    text width=0.047 * \ourwidth,
    minimum width=0.040 * \ourwidth,
    text height=0.023 * \ourwidth,
    text depth=2.7pt,
    inner xsep=0.30cm,
    % inner xsep west = 0.10cm % Nope
    node distance = 4mm,
% \nodepart[]{one} text = {\hspace*{-3pt}#1}, % Attempt to parameterize the text
% \nodepart[]{two} text = {\hspace*{-3pt}#2},
} }

\tikzset{arr/.style = {very thick,{Circle[length=6pt,sep=-3pt]}-{Stealth} } }
\noindent\begin{tikzpicture}[start chain=1,start chain=2,start chain=3,start chain=4]
\tikzset{every node}=[font=\small\ttfamily]

\node[rectangle, on chain=1,inner xsep=0.05cm,](ORIG){\footnotesize 1511};

\node (A) [thebox,on chain=1,right=0.0cm of ORIG]
     {\nodepart[]{one}\hspace*{-3pt}1111 \nodepart[]{two}}; % comment \hspace*{-3pt}1111

\node (B) [thebox, on chain=1,] % right=0.4cm of A,
     {\nodepart[]{one}\hspace*{-3pt} \nodepart[]{two}\hspace*{-3pt}};

\node (C) [thebox, on chain=1,] % right=0.4cm of B,
     {\nodepart[]{one}\hspace*{-3pt}2111 \nodepart[]{two}};

\node (D) [thebox, on chain=1,] % right=0.4cm of C
     {\nodepart[]{one} \nodepart[]{two}\hspace*{-3pt}0000};

\node (E) [thebox, on chain=3,below=0.55cm of D] at (9.65, -0.3)
     {\nodepart[]{one}\hspace*{-3pt}6700 \nodepart[]{two}\hspace*{-3pt}};

\node (F) [thebox, on chain=3,] % right=0.4 of E
     {\nodepart[]{one}\hspace*{-3pt}8000 \nodepart[]{two}\hspace*{-3pt}0000};

\node (G) [thebox, on chain=2,below=1.4cm of B] at (4.6, -0.5)
      {\nodepart[]{one}\hspace*{-3pt}3422 \nodepart[]{two}\hspace*{-3pt}};

\node (H) [thebox, on chain=2,] %at (4.5, -0.5) % right=0.4cm of G
     {\nodepart[]{one}\hspace*{-3pt} \nodepart[]{two}\hspace*{-3pt}};

\node (I) [thebox, on chain=4,below=0.6cm of H] at (7.6, -2.5)
      {\nodepart[]{one}\hspace*{-3pt}4000 \nodepart[]{two}\hspace*{-3pt}};

\node (J) [thebox, on chain=2,] % right=0.4cm of H
      {\nodepart[]{one}\hspace*{-3pt}5321 \nodepart[]{two}\hspace*{-3pt}0000};

\node (K) [thebox, on chain=4,] % right=0.4cm of I
     {\nodepart[]{one}\hspace*{-3pt}7222 \nodepart[]{two}\hspace*{-3pt}0000};

 \draw[arr] ($(A.two)!0.32!(A.east)$) -- (B.west);
 \draw[arr] ($(B.west)!0.10!(B.east)$) |- (G.west);
 \draw[arr] ($(B.two)!0.32!(B.east)$) -- (C.west);
 \draw[arr] ($(C.two)!0.32!(C.east)$) -- (D.west);
 \draw[arr] ($(D.west)!0.10!(D.east)$) |- (E.west);
 \draw[arr] ($(E.two)!0.32!(E.east)$) -- (F.west);
 \draw[arr] ($(G.two)!0.32!(G.east)$) -- (H.west);
 \draw[arr] ($(H.west)!0.08!(H.east)$) |- (I.west);
 \draw[arr] ($(H.two)!0.32!(H.east)$) -- (J.west);
 \draw[arr] ($(I.two)!0.32!(I.east)$) -- (K.west);
\end{tikzpicture}
\end{document}

In order to avoid manual repetition, I consider parameterizing the node text in  tikzset=thebox/.style{...
I've added
  \nodepart[]{one} text = {\hspace*{-3pt} #1 }
  \nodepart[]{two} text = {\hspace*{-3pt} #2}

not surprisingly they didn't work. I've looked up similar posts like this one
Is there a way to set the text of a multipart node using \tikzset?
and I've added n args={2} next to thebox/.style but this caused compile error. I've looked up the TikZ manual, which is over 1300 pages (!) and no clear example about this particular problem.
How to correctly parameterize the node text inside the \tikzset ?

A: It seems to me that the problem is caused by too-narrow text width with settings align=center, inner xsep=0.30cm. With enough width, for example text width=1cm, the output looks fine (hence there's no need for \hspace{-3pt}).
Additionally, to start the arrow rightly from the center of node part two, I've changed every
\draw[arr] ($(X.two)!0.32!(A.east)$) -- (Y.west);

to
\draw[arr] ($(X.one split)!0.5!(A.east)$) -- (Y.west);

Full example
\documentclass[a4paper,openany,14pt]{extbook}

\usepackage{tikz}
\usetikzlibrary{shapes.multipart,chains,positioning,arrows,calc,arrows.meta}

\newcommand{\columnratio}{0.62} % to be able to fit the TikZ drawing
\newcommand{\columnseper}{12pt} % inside small sections

\begin{document}

\pgfmathsetlengthmacro{\ourwidth}{\columnratio * \linewidth - \columnseper}

\tikzset{
  thebox/.style = {
    rectangle split,
    rectangle split horizontal,
    rectangle split parts=2,
    very thick,
    draw=black!100,
    align=center,
    text width=1cm,
    text height=1.5ex,
    text depth=.35ex,
    inner xsep=0.08cm,
    node distance=2mm and 4mm,
  },
  arr/.style = {
    very thick,
    {Circle[length=6pt,sep=-3pt]}-{Stealth},
  },
}

\noindent
\begin{tikzpicture}[
  start chain/.list={1,2,3,4},
  nodes={font=\footnotesize\ttfamily}]

  \node[on chain=1] (ORIG) {1511};

  \node (A) [thebox, on chain=1, right=0cm of ORIG]
       {\nodepart{one}1111 \nodepart{two}};

  \node (B) [thebox, on chain=1,] % right=0.4cm of A,
       {\nodepart[]{one} \nodepart[]{two}};

  \node (C) [thebox, on chain=1,] % right=0.4cm of B,
       {\nodepart[]{one} 2111 \nodepart[]{two}};

  \node (D) [thebox, on chain=1,] % right=0.4cm of C
       {\nodepart[]{one} \nodepart[]{two} 0000};

  \node (E) [thebox, on chain=3, below right=.3cm and -1.5cm of D]
       {\nodepart[]{one} 6700 \nodepart[]{two}};

  \node (F) [thebox, on chain=3,] % right=0.4 of E
       {\nodepart[]{one} 8000 \nodepart[]{two} 0000};

  \node (G) [thebox, on chain=2, below right=1.3cm and -1.5cm of B]
        {\nodepart[]{one} 3422 \nodepart[]{two} };

  \node (H) [thebox, on chain=2,] %at (4.5, -0.5) % right=0.4cm of G
       {\nodepart[]{one} \nodepart[]{two} };

  \node (I) [thebox, on chain=4, below right=0.3cm and -1.3cm of H]
        {\nodepart[]{one} 4000 \nodepart[]{two}};

  \node (J) [thebox, on chain=2,] % right=0.4cm of H
        {\nodepart[]{one} 5321 \nodepart[]{two} 0000};

  \node (K) [thebox, on chain=4,] % right=0.4cm of I
       {\nodepart[]{one} 7222 \nodepart[]{two} 0000};

   \draw[arr] ($(A.one split)!0.5!(A.east)$) -- (B.west);
   \draw[arr] ($(B.west)!0.10!(B.east)$) |- (G.west);
   \draw[arr] ($(B.one split)!0.5!(B.east)$) -- (C.west);
   \draw[arr] ($(C.one split)!0.5!(C.east)$) -- (D.west);
   \draw[arr] ($(D.west)!0.10!(D.east)$) |- (E.west);
   \draw[arr] ($(E.one split)!0.5!(E.east)$) -- (F.west);
   \draw[arr] ($(G.one split)!0.5!(G.east)$) -- (H.west);
   \draw[arr] ($(H.west)!0.10!(H.east)$) |- (I.west);
   \draw[arr] ($(H.one split)!0.5!(H.east)$) -- (J.west);
   \draw[arr] ($(I.one split)!0.5!(I.east)$) -- (K.west);
\end{tikzpicture}
\end{document}

To parameterize the text of node parts, in theory you can add options execute at begin node and execute at end node to styles every <part name> node part, like
every one node part/.style={
  execute at begin node=...,
  execute at end node=...
}

But currently there's a bug that execute at end node is executed twice for the first node part, see https://github.com/pgf-tikz/pgf/issues/1155.

A: You can set the node text using node contents, e.g.
\tikzset{thebox/.style n args={2}{
        node contents={\nodepart{one}\hspace*{-3pt}#1\nodepart{two}\hspace*{-3pt}#2},
    }
}

and then \node (C) [thebox={2111}{},on chain=1];.

Here is a MWE based on your code. I allowed myself to do some modifications to make it shorter. The box size is determined only by text width and minimum height. You don't need \hspace*{-3pt} here. Also, for every box I define two coordinates x-one and x-two to simplify the arrows.

\documentclass[a4paper,openany,14pt]{extbook}

\usepackage{tikz}
\usetikzlibrary{shapes.multipart,chains,positioning,arrows.meta,calc}

\begin{document}

\tikzset{thebox/.style n args={2}{
        rectangle split,
        rectangle split horizontal,
        rectangle split parts=2,
        very thick,
        draw=black,
        align=center,
        text width=25, % adjust box width here
        minimum height=18, % adjust box height here
        node distance=4mm,
        node contents={\nodepart{one}#1\nodepart{two}#2},
        append after command={% define x-one and x-two coordinates for connecting arrows
            \pgfextra{\edef\currentnode{\tikzlastnode}}
            (\currentnode.two north|-\currentnode.east) coordinate (\currentnode-two)
            ($(\currentnode.west)!0.1!(\currentnode.east)$) coordinate (\currentnode-one)
        },
    },
    arr/.style={very thick,{Circle[length=6pt,sep=-3pt]}-{Stealth}},
    every node/.append style={font=\footnotesize\ttfamily},
}

\noindent\begin{tikzpicture}[start chain=1,start chain=2,start chain=3,start chain=4]

\node[rectangle,on chain=1,inner xsep=0.05cm,] (ORIG) {1511};

\node (A) [thebox={1111}{},on chain=1,right=0.0cm of ORIG];
\node (B) [thebox={}{},on chain=1];
\node (C) [thebox={2111}{},on chain=1];
\node (D) [thebox={}{0000},on chain=1];
\node (E) [thebox={6700}{},on chain=3,below right=0.55cm and 0.75cm of D.south west];
\node (F) [thebox={8000}{0000},on chain=3];
\node (G) [thebox={3422}{},on chain=2,below right=1.4cm and 0.75cm of B.south west];
\node (H) [thebox={}{},on chain=2];
\node (I) [thebox={4000}{},on chain=4,below right=0.6cm and 0.75cm of H.south west];
\node (J) [thebox={5321}{0000},on chain=2];
\node (K) [thebox={7222}{0000},on chain=4];

\draw[arr] (A-two) -- (B);
\draw[arr] (B-two) -- (C);
\draw[arr] (C-two) -- (D);
\draw[arr] (D-one) |- (E);
\draw[arr] (E-two) -- (F);
\draw[arr] (B-one) |- (G);
\draw[arr] (G-two) -- (H);
\draw[arr] (H-one) |- (I);
\draw[arr] (I-two) -- (K);
\draw[arr] (H-two) -- (J);
\end{tikzpicture}
\end{document}


text:
Q: Escaping partial regex pattern I search to built a pattern composed by some fixed parts and a variable (in reality Business Unit name). In fact, there is high chance that the variable contains some specific regex characters which can be recognize as regex control ones (i.e + or *).
Is there any regex tag that notice that a pattern subpart should be considered only as text, and ignore specific char meaning?
some kind of :
regex_fixed_part [escape]business + unit[/espace] regex_fixed_part

here, business + unit will be replaced in the parser by business \+ unit
Obviously, I could escape manually all regex char, but I search a more tidy method.
Thanks

A: Many regex flavors have a utility method that automatically escapes meta characters. Java does this using Pattern.quote(String) and PHP has a similar function: preg_quote(string). Many PCRE implementations also support the \Q and \E escape sequences. \Q will let the regex engine interpret all characters after it as plain literals until the next \E.
Example:
a\Q+*\Eb+

will match the string a+*bbb.

A: What language?
In python:
import re
regex_fixed = re.escape("business + unit")

In php, use preg_quote()

A: In Java, use Pattern.quote() or "\\Qprotected part\\E" if you want to do it manually.

A: Replace [[\]\^\-\\\/?*+$().|] with \$& (backslash followed by $&, the matched string) with the global flag on.


text:
Q: hide fieldset elements on page load or when a radio button option is already selected I am trying to hide fieldset elements on page load when the radio button 'No' is already checked and when 'yes' is checked the fieldset should appear. Currently, the fieldset hides if the user checks 'No' and/or shows if user checks 'Yes'. But i want the fieldset to be hidden on page load or if 'No' is already checked, and the fieldset and its contents should be displayed once 'Yes' is checked.
hide_show_field.js
function ToggleDisplay(Section, boolHide) {
    if (boolHide) {
        Section.style.display = "none";
    }
    else {
        Section.style.display = "block";
    }
}

function disableElement(element, boolHide)
{
    var input = document.getElementById(element).getElementsByTagName("input");
        for(var i = 0; i < input.length; i++)
        {
            input[i].removeAttribute("disabled");
        }
}

function hideShowElement(CurrentSection, OtherSection, DisableSection)
{
    var sectionVal = CurrentSection.value;
        if (sectionVal == 'No') {
            ToggleDisplay(OtherSection, true);
            disableElement(DisableSection, "true");
        }
        else {
            ToggleDisplay(OtherSection, false);
            disableElement(DisableSection, "false");
        }
}

form.php

            Transferred
            <input type="radio" name="transferred" value="Yes" onchange="hideShowElement(this, mydiv, 'optionGroup');">Yes
            <input type="radio" name="transferred" value="No" onchange="hideShowElement(this, mydiv, 'optionGroup');">No

    </fieldset>

<fieldset class="group" id="optionGroup">
    <legend>Transfer</legend>

            Transferred To
            <select name="transferTo">
                <option value="Select Station"></option>
                <?php include('php/selectlocation.php'); ?>
            </select>

            Date Transferred
            <input type="date" name="dateTransferredTo" id="datepicker1" placeholder="YYYY-MM-DD" >

            Transferred From
            <select name="transferFrom" >
                <option value="0"></option>
                <?php include('php/selectlocation.php'); ?>
            </select>

            Date Transferred
            <input type="date" name="dateTransferredFrom" id="datepicker2" placeholder="YYYY-MM-DD" >

            Rank Transferred With
            <select name="rankTransferredWith">
                <option value="0"></option>
                <?php include('php/selectranks.php'); ?>
            </select>

</fieldset>

Could someone provide some assistance please

A: Maybe the easiest way is to set the input for the "no" checked="true" in the php...
But the way you activate your js it will probably not work. It is better to select those elements in the js code and check if they are selected. You probably need to use an anonymous function, to make sure everything works well...
(function () {
     if (radio.checked) {
        //hide or show
     }
}()):


text:
Q: Does exist a method to migrate database between different version in odoo Can someone tell me to how migrate odoo v9 to odoo v10. I want to migrate all data in the database. thanks a lot

A: Migrating Odoo is a non-trivial operation.
If you are an enterprise customer, check Odoo's upgrade service here: https://upgrade.odoo.com/database/upload.
Check this answer to get the idea: How to migrate odoo 8 to odoo 10.
You will have to migrate your custom or third-party modules, if not yet available, and then you have to migrate the database.
Some people use Open Upgrade: https://github.com/OCA/OpenUpgrade


text:
Q: Vue.js: v-for behaves different with template literals Why does v-for behave different when using either numbers or template literals?
Here is an example:

new Vue({
  el: "#app",
})

Result with template literal

    <li
      v-for="pages in `${2+2}`"
      :key="pages"
    >

{{pages}}

Result with straight number

{{pages}}

A: They are not the same. In the first one, you are using v-for on a string. In which case, vue will loop through the characters and display each of them in a li. In the second one, it's an integer. In which case, vue will use the range mechanism

new Vue({
  el: "#app",
})

Result with template literal

    <li
      v-for="pages in `100`"
      :key="pages"
    >

{{pages}}

Result with straight number

{{pages}}


text:
Q: How to generate exponential series of values with known initial and end values in Excel In Excel, I want to generate 1000 rows of values, I know the initial and final values.
For example, cell a1=1400 and cell a1000=1190, the total reduction is 15%, how to generate 1000 rows of values excel so that the values decrease exponentially?
Any idea how could I create a formula to achieve this? Thank you

A: Suggested answer: Get the x variable on column A from 1 to 1000 and then create the y variable on column b so in x=1 y=1400,
And when x=1000 then y=1190
Then add chart with xy scatter and add power trend line.
Set add equation on chart you will get y=1400X^-0.024. This will be your equation.

A: Put 1 in A1, 2 in A2, 3 in A3 an so on... till A1000, then
write this in B1 =1400.2278*EXP(-0.00016268*A1) and continue to B1000, set B column 2 decimals format number.
Exponential regression equation is the form y=a*e^(bx).
Power regression equation is the form y=a*x^(b).
In excel EXP(x) function return e^x, e is euler number ~2.718281828 (Approximate)

A: First type 1400 into A1 and 1190 in A1000.
Next, tap F5 and when the GoTo dialog opens, type A1:A1000 in the Reference: text box and click OK.
Choose Home ► Editing ► Fill ► Series (Alt+H,FI,S).
When the Series dialog opens, click OK. The increment (-0.21021021021021) will already be set.


text:
Q: Can frontend js framework be used for non-single page apps? Someone told me that frontend frameworks such as backbone, angularjs, knockout, etc work only for single-page apps since one has to define routes based on hashed arguments and these frameworks trigger appropriate controllers/modals/views.
My question is can these frontend frameworks be used for non-single page apps as well ? Let's assume I have these three pages:

*

*index.html

*about.html

*contact.html

And I wrote code for routes in app.js included in above files. Then will these frameworks be able to figure out which page we are on and trigger appropriate controllers (and other stuff with modals, loading appropriate views) automatically unlike single page apps based on hashes? If possible, optionally can somebody give simple example of how to define routes (non-hased in this case ofcourse) for above three pages using any of above framework ?
Thanks for the help

A: As mentioned in the comments there is nothing that precludes you from using any of these frameworks in a traditional, round-trip-per-page web application. That being said, you should pick the right tool for the job.
Disclaimer:
I have used both Angular and Knockout extensively on real world applications. I have only used backbone a little, but I prefer the declarative style of Angular and Knockout over the imperative style of backbone.
Backbone and Angular are really designed and optimized for building single page applications. However, there are many shades of grey in between. You could load up a "Customers" page and have a handful of routes defined there, but when you navigate over to "Admin" that could be a total page refresh and you would have multiple routes defined there.
Knockout is not a SPA framework. It does not come with a router, and therefore doesn't handle side loading of views. You use something like Sammy.js to achieve the routing you want.
If you aren't building a SPA then don't use a SPA framework.
I would personally go with Knockout if I were you since you don't need a router.
However, if you plan to eventually build this out to a SPA, or a hybrid application, then go with a framework like Angular, Backbone or Ember.

A: It is perfectly possible to do so.
the only difference will be that your ViewModel will be recreated every time you change page plus the data will be reloaded, but depending on the design of an app this is not much different from what you may do in a single page app.

A: In Angular you can do something like follows to achieve this:
<html>
   <head>
     <title>index.html</title>
   </head>
   <body ng-app="myApp" ng-controller="indexController">
     <h2>{{title}}</h2>

     <script type="text/javascript">
        (function(app) {

            var indexController($scope) {
                $scope.title = "Index title!";
            };

            app.controller('indexController', ['$scope', indexController]);

        }(angular.module('myApp')));
     </script>
   </body>
</html>

Knockout for example is not a full blown SPA framework. If you want routing you will have to  rely on 3rd party libraries, i.e. sammy.js


text:
Q: Admin grid: Response is not displayed in Backend in magento2 I have created admin grid and associated form,It saved the items and worked good, But failed to show the response message.Please provide me a solution
<?php

namespace X\Y\Controller\Adminhtml\aaa;

use X\Y\Model\ImageFactory;
use Magento\Framework\Message\ManagerInterface;

class Save extends \Magento\Backend\App\Action
{

    protected $model;
    protected $_messageManager;

    public function __construct(
    \Magento\Backend\App\Action\Context $context, ImageFactory $model, ManagerInterface $messageManager, \Magento\Backend\Model\View\Result\RedirectFactory $resultRedirectFactory, \Magento\Backend\Model\Auth\Session $authSession
    )
    {
        $this->_messageManager = $messageManager;
        $this->model = $model;
        $this->resultRedirectFactory = $resultRedirectFactory;
        $this->authSession = $authSession;
        parent::__construct($context);
    }

    public function execute()
    {
        $id = $this->getRequest()->getParam('id');
        try {
            $imageData = $this->model->create();
            //If gets id loads the model
            if ($id) {
                $imageData = $imageData->load($id);
            }

            $formData = $this->getRequest()->getParam('general');
            $user = $this->getCurrentUser();

            if (empty($formData ['id'])) {

                $formData['id'] = null;
                // update the current user name for both created and updated
                $formData['created_by'] = $user;
                $formData['updated_by'] = $user;
            }

            $formData['updated_by'] = $user;

            if (isset($formData['image'])) {
                $formData['image'] = $formData['image'][0]['name'];
            } else {
                $formData['image'] = null;
            }

            //Set all the data in DB from form
            $imageData->setData($formData);
            $imageData->save();

           //After saved the item it failed to show the below success message
           $this->_messageManager->addSuccess(__("Your Slide has been saved !"));

        } catch (Exception $e) {

            $this->_messageManager->addError($e->getMessage());
        }
        //Result redirected to index controller
        return $this->resultRedirectFactory->create()->setPath('a/b/index');
    }

    public function getCurrentUser()
    { //Get the current user name using session
        return $this->authSession->getUser()->getUsername();
    }

}


text:
Q: How to reset a cancelled subscription bound to SwiftUI In the following example code, a SwiftUI form holds an Observable object that holds a trivial pipeline that passes a string through to a @Published value. That object is being fed by the top line of the SwiftUI form, and the output is being displayed on the second line.
The value in the text field in the first row gets propagated to the output line in the second row, whenever we hit the "Send" button, unless we hit the "End" button, which cancels the subscription, as we'd expect.
import SwiftUI
import Combine

class ResetablePipeline: ObservableObject {
    @Published var output = ""
    var input = PassthroughSubject<String, Never>()

    init(output: String = "") {
        self.output = output
        self.input
            .assign(to: &$output)
    }

    func reset()
    {
        // What has to go here to revive a completed pipeline?
        self.input
            .assign(to: &$output)

    }
}

struct ResetTest: View {
    @StateObject var pipeline = ResetablePipeline()
    @State private var str = "Hello"

    var body: some View {
        Form {
            HStack {
                TextField(text: $str, label: { Text("String to Send")})
                Button {
                    pipeline.input.send(str)
                } label: {
                    Text("Send")
                }.buttonStyle(.bordered)
                Button {
                    pipeline.input.send(completion: .finished)
                } label: {
                    Text("End")
                }.buttonStyle(.bordered)
            }
            Text("Output: \(pipeline.output)")
            Button {
                pipeline.reset()
            } label: {
                Text("Reset")
            }
        }
    }
}

struct ResetTest_Previews: PreviewProvider {
    static var previews: some View {
        ResetTest()
    }
}

My understanding is that hitting "End" and completing/cancelling the subscription will delete all the Combine nodes that were set up in the ResetablePipeline.init function (currently only the assign operator).
But if we wanted to reset that connection, how would we do that (without creating a new ResetablePipeline object). What would you have to do in reset() to reconnect the plumbing in the ResetablePipeline object, so that the Send button would work again? Why does the existing code not work?

A: It is part of the fundamental nature of a Publisher that once the Publisher has finished, or has emitted an error, that the publisher will never emit another value.
This is described in Reactive X in the Observable Contract
The fundamental reason for this is that when the pipeline finishes, the stages in the pipeline are free to release any resources they may have obtained.  For example, if a collect operator has set aside memory for its connected items, it can release that memory once the pipeline finishes.
In short, there is no way to do what you want to do.  You cannot restart a pipeline that has finished, though you can construct a new one.

A: Well I'll be. If I simply add input = PassthroughSubject<String, Never>() to the start of reset() (ie replace the original cancelled head-publisher with a fresh one), it seems to do the trick.
Now, I'm not entirely sure if this code is not leaking something since I don't know exactly what assign(to:) does with the old subscription, but assuming that it's sensible, this might be OK.
Can anyone see anything wrong with this approach?


text:
Q: Terms and conditions from Static block magento2 I need to show Terms and condition text before place order button of each payment method.
Which file i need to override to show content from static block. As i checked terms and conditions text comes from html and not from phtml file.
So is it possibile to display content from the cms static block?
Please anyone help on this. Thanks

A: I assume that you want to show a formatted content in the terms and conditions section in the checkout page.
By default, it is not possible to call the content in this block from a CMS block.
I have a workaround for it.

*

*Create a temporary static block and write your HTML content in it. Check the preview of HTML. Once finalized, go to step 2.

*Go to Stores >> Settings (Terms and Conditions) and edit existing or create a new condition with the following settings:
-- Status: Enabled
-- Show Content as: HTML
Now, copy the HTML content from the static block which you created in step #1 and paste its Content in the content section of this condition. Save the condition.

*Now go to Stores >> Configuration >> Sales (Checkout) section and under Checkout Options, change the value of Enable Terms and Conditions to Yes. Save Config.
That's all.


text:
Q: Google Drive API performance (large number of files, large number of sharing) I created an account with the Business option of G-suite and added 5 users to use unlimited Google storage.
After I create a folder on that storage and upload the file, I will share it with other users with the View Only option.
Please Look at this directory structure.
enter image description here
In this case, I'm worrying about performance issue.
I need to prepare for the case where the number of users increases and our system slows down.
Do you know how much IOPS(input/output operations per second) does Google Drive provide?
And, Do you know What is different team drive and my drive and what is better?

A: With regard to your Team Drive and Google Drive comparison inquiry, refer to this
What can you do with Team Drives?:

Google Team Drives are shared spaces where teams can easily store,
  search, and access their files anywhere, from any device. Unlike files
  in My Drive, files in Team Drive belong to the team instead of an
  individual. Even if members leave, the files stay exactly where they
  are so your team can continue to share information and get work done.
  Note: Team Drives is available on G Suite Enterprise, G Suite
  Business, or G Suite for Education editions. If you can't use Team
  Drives, contact your G Suite administrator.

Not sure if Google's IO operations/second is openly disclosed but if you think you're about to run into scaling problem, by looking at your Google Drive API dashboard, you can always reach out to Drive team to request for more quota.


text:
Q: Where is the item folder located for Dota 2? I want to ask where is the location of items folder [hero items] for using customized hero images, etc?

A: This is discussed in more length on the Gamepedia DOTA 2 page for customizing game files. All of these paths are relative to your Dota 2 installation folder, so if your Steam library installs inside the Steam folder and Steam is installed in its default location all of these paths will be prefixed with C:\Program Files (x86)\Steam\steamapps\common\dota 2\dota or C:\Program Files (x86)\Steam\steamapps\common\dota 2 beta\dota if you initially installed the game during beta:

*

*Cosmetic item data: scripts\items\items_game.txt

*Cosmetic item icons: resource\flash2\images\econ

*Interface customizations: materials\console\loadingscreens, resource\flash3\images\hud_skins and resource\flash3\images\emoticons

*Game assets: resource\flash3\images

*Hero images: resource\flash3\images\heroes
Note these locations may not physically exist on the filesystem as Dota 2 uses VPK files to store all of their data, this means you will need to create the relevant folders if you wish to override the VPK files.


text:
Q: What information is stored in a python map object? I'm not able to wrap my mind on the map() function.
I have taken code from an example.
I'd like to know what exactly happen on this line of code.
labels = map(itemgetter(1),map(os.path.split,map(os.path.dirname,labels)))

The values of labels before this statement is
<class 'list'>: ['classify-test/aligned/clapton/clapton-1.png', 'classify-test/aligned/clapton/clapton-2.png', 'classify-test/aligned/lennon/lennon-1.png', 'classify-test/aligned/lennon/lennon-2.png']

I know that If I did  map(os.path.split,map(os.path.dirname, labels[0])) I'd get the value clapton.
But can I use some other logic to conver this map. And what is the return type of the     labels=map(itemgetter(1),map(os.path.split,map(os.path.dirname,labels))) line.
Is it a list of strings or someting else?

A: Take the following pure-Python implementation of map:
def my_map (func, iterable):
    for item in iterable:
        yield func(item)

This is essentially was the built-in map does, just in native code, so it's a lot faster.
So map will just apply the function passed as the first argument to every single element of the iterable passed as the second argument. In your case, to understand what happens, you should read the line from the inside to the outside:
map(itemgetter(1), map(os.path.split, map(os.path.dirname, labels)))
                                                           ^^^^^^
                                               Start here: This is your iterable

                                          ^^^^^^^^^^^^^^^
                                          Run os.path.dirname(x) on every element x

                       ^^^^^^^^^^^^^
                       Run os.path.split(y) on every element y of the previous result

    ^^^^^^^^^^^^^
    Run itemgetter(1)(z) on every element z of the previous result

Since you are running map three times, you are applying three functions on the original element. You could combine those functions to make it a bit more clear:
def getDirectoryName(label):
    return os.path.split(os.path.dirname(label))[1]

result = map(getDirectoryName, labels)

Having those function calls properly chained makes this already a lot clearer, which allows us to easily guess what the combined function does: In this case, it gets the directory of the passed label (which is a path), and then splits that up, to get just the name of the directory. One could also use os.path.basename here instead of splitting the path manually.
Because this is so much clearer, this is the reason why you rarely see map being used in Python code. The often preferred way would be to use a list comprehension:
result = [os.path.split(os.path.dirname(label))[1] for label in labels]

Here you have the benefit of both: Everything in a concise way, yet easy to understand since it's imperative code instead of functional.


text:
Q: How to load local JavaScript libraries in Github Pages? I recently deployed my website to GitHub Pages - https://max-stevenson.github.io/my-year-in-books/
I have a two local JavaScript libraries (jQuery and swiped-events) downloaded and within the following directory: src/public/js/lib.
In my index.html file at the root directory, I am linking to the two libraries like so:
<script type="text/javascript" src="/src/public/js/lib/jquery-3.4.1.min.js"></script>
<script src="/src/public/js/lib/swiped-events.js"></script>

But when I access the page on GitHub Pages I get the following errors:
GET https://max-stevenson.github.io/src/public/js/lib/jquery-3.4.1.min.js net::ERR_ABORTED 404 (Not Found)
GET https://max-stevenson.github.io/src/public/js/lib/swiped-events.js net::ERR_ABORTED 404 (Not Found)

When I run a local instance on my machine via a node express server and visit the site at localhost:3000, everything works great.
Can anyone please advise me where I'm going wrong and how to correctly reference my scripts so that they are loaded in GitHub Pages?

A: Try:
<script type="text/javascript" src="/my-year-in-books/scr/js/lib/jquery-3.4.1.min.js"></script

Or:
<script type="text/javascript" src="./scr/public/js/lib/jquery-3.4.1.min.js"></script


text:
Q: using cakephp, how do I handle model operations that return no results so my view doesn't break? In my controller I have model operations that can return empty results. I've setup the view to display the results using a foreach loop. But if the model opertion is empty and returns no results then the foreach loop is breaking in my view.
This is the operation:
$match3 = $this->Draw->Match-> find('all',array('conditions'=>array('Match.draw_id'=>$id, 'Match.round_id'=> 1, 'Match.match_position' => 3)));
What do I need to add to the model operation to return null? Or is null the best way to handle this?
If there is no data then I don't want anything displayed.
I did try this but got an undefined index error:
if (!$match3)
   return null;
else
return $match3;
Is there a best practice when it comes to handling empty model operations?
Much appreciated.
-Paul

A: IMO, the "best practice" isn't CakePHP-specific. If your result set it empty, it's critical to inform your users of that fact. It's a simple test (in this case for an empty array as indicated by Travis) and a simple result. I typically do it like this in my views:
<?php if( empty( $match3 ) ): ?>

Display an appropriate empty set message.

<?php else: ?>
  # do whatever you need to do to display the result set
<?php endif; ?>

A: If your find operation has no results, it will just return an empty array.
In your view, just put some logic to make sure that $match3 isn't an empty array before you output that section.  E.g., in the view
<?php
 // some code here to output part of the page
 if( !empty( $match3 ) )
  foreach( $match3 as $matches )
   ; // do something with $matches
 // rest of your view code
?>

A: Very much depending on your app, the following responses may be appropriate:
$result = $this->Model->find(…);

if (!$result) {
    // redirect to another page and display message
    $this->Session->setFlash('No results found');
    $this->redirect(array('action' => 'index'));
}

or
if (!$result) {
    // throw a 404 (or any other) error
    $this->cakeError('error404');
}

Again, this very much depends on the app and the action in question, especially a 404 should not be a standard response. In many cases it's probably best to handle it in the view as advised by Rob.


text:
Q: Javascript to calculate total at row and column level I have a pageblocktable with one editable column in which numeric value for quantity will be entered. the next column to this is the Rate column which will have values from Salesforce. I want the Product of these 2 to be displayed in the last column as Total and also the sum of the Total column in Javascript so that on entering values in the inputtext, the total dynamically changes.
Below is my page :
<apex:page controller="DetailController" sidebar="false" id="pg">
<script>
function findTotal(){
alert(document.getElementById('pg:frmId:pb:pbt:0:qty').value);
//    alert(document.getElementById('pg:frmId:pb:pbt:0:j_id38').txt);
var qty = document.getElementById('pg:frmId:pb:pbt:0:qty').value;
var rate = document.getElementById('pg:frmId:pb:pbt:0:j_id38').text;
var totallineItem = qty*rate;
//    document.getElementById('pg:frmId:pb:pbt:0:qty').value
document.getElementById("pg:frmId:pb:pbt:0:j_id26").innerHTML = totallineItem ;
}

</script>
<apex:form id="frmId">

<apex:pageBlock title="Order Line Items" rendered="{!showDetails}" id="pb">
<apex:pageblockButtons location="bottom">
<apex:commandButton action="{!createOrder}" value="Save"/>
</apex:pageblockButtons>
<apex:pageBlockTable value="{!DispWrapper}" var="dw" id="pbt">
<apex:column value="{!dw.lineItemObj.Product__c}"/>
<apex:column value="{!dw.lineItemObj.Order__c }"/>
<apex:column headerValue="Delivered Quantity" >
<apex:inputtext value="{!dw.quantity}" id="qty" onchange="findTotal();"   styleClass="count-me"/>
 </apex:column>
 <apex:column value="{!dw.lineItemObj.Rate__c }" id="rate"/>
 <apex:column headerValue="Total">
 <apex:outputtext id="litotal"></apex:outputtext>
 </apex:column>
 </apex:pageBlockTable>
 </apex:pageBlock>

 </apex:form>
 </apex:page>

I am not familiar with Javascript and so this code is all I have which I tried. Please point me in the right direction to proceed with this!
The sample image below shows a typical table. The last column and the summary (Totals) need to be populated via Javascript.

A: The DOM Id values in Visualforce tables include a row number (the :0: in your JavaScript) so your logic needs to incorporate that. The approach that I think works best is to use a CSS class (that has no markup associated with it) instead of the DOM Id:
<apex:column headerValue="Delivered Quantity" >
    <apex:inputtext value="{!dw.quantity}" styleClass="quantityMarker"/>
</apex:column>
<apex:column value="{!dw.lineItemObj.Rate__c }" styleClass="rateMarker"/>
<apex:column headerValue="Total">
    <apex:outputtext styleClass="totalMarker"/>
    <apex:facet name="footer">
        <apex:outputtext styleClass="grandTotalMarker"/>
    </apex:facet>
</apex:column>

While you could achieve what you want with just JavaScript, I would recommend adding (as a static resource) and using jQuery in your page. The code then becomes something like this (that you should add to the end of the page so the page rendering is not held up):
<script src="{!$Resource.jQuery}"></script>
<script>
(function($) {
    $(document).ready(function() {
        $('.quantityMarker').change(function() {

            var defaultedFloat = function(s) {
                if (s !== null && s !== '') {
                    var r = parseFloat(s);
                    if (!isNaN(r)) return r;
                }
                return 0;
            };

            // Recalculate the row
            var q = $(this);
            var r = q.closest('tr').find('.rateMarker');
            var t = q.closest('tr').find('.totalMarker');
            // Better handling of rounding may be needed
            t.text(defaultedFloat(q.val()) * defaultedFloat(r.text()));

            // Recalculate total of all rows
            var total = 0;
            $('.totalMarker').each(function() {
                var t = $(this);
                total += defaultedFloat(t.text());
            });
            $('.grandTotalMarker').text(total);
        });
    });
})(jQuery.noConflict());
</script>

This code:

*

*Executes jQuery.noConflict() so any existing value of $ in the page is preserved

*Waits until the DOM is ready

*Then adds a function that is notified of changes on all elements that have class .quantityMarker

*When a change happens, the function finds the class rateMarker element in the same row and the totalMarker element in the same row

*Then sets the product in the totalMarker element
= Then sums all the row totals into the grand total